Programs & Examples On #Params keyword

params is a C# keyword that allows a variable number of parameters in function calls.

How to add target="_blank" to JavaScript window.location?

_x000D_
_x000D_
    var linkGo = function(item) {_x000D_
      $(item).on('click', function() {_x000D_
        var _$this = $(this);_x000D_
        var _urlBlank = _$this.attr("data-link");_x000D_
        var _urlTemp = _$this.attr("data-url");_x000D_
        if (_urlBlank === "_blank") {_x000D_
          window.open(_urlTemp, '_blank');_x000D_
        } else {_x000D_
          // cross-origin_x000D_
          location.href = _urlTemp;_x000D_
        }_x000D_
      });_x000D_
    };_x000D_
_x000D_
    linkGo(".button__main[data-link]");
_x000D_
.button{cursor:pointer;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>
_x000D_
_x000D_
_x000D_

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

I've had success with this solution. It's almost like Patrick's, with a little twist. You can use these expressions separately or in sequence. If the parameter is blank, it will be ignored and all values for the column that your searching will be displayed, including NULLS.

SELECT * FROM MyTable
WHERE 
    --check to see if @param1 exists, if @param1 is blank, return all
    --records excluding filters below
(Col1 LIKE '%' + @param1 + '%' OR @param1 = '')
AND
    --where you want to search multiple columns using the same parameter
    --enclose the first 'OR' expression in braces and enclose the entire 
    --expression 
((Col2 LIKE '%' + @searchString + '%' OR Col3 LIKE '%' + @searchString + '%') OR @searchString = '')
AND
    --if your search requires a date you could do the following
(Cast(DateCol AS DATE) BETWEEN CAST(@dateParam AS Date) AND CAST(GETDATE() AS DATE) OR @dateParam = '')

How to hide scrollbar in Firefox?

For more recent version of Firefox the old solutions don't work anymore, but I did succesfully used in v66.0.3 the scrollbar-color property which you can set to transparent transparent and which will make the scrollbar in Firefox on the desktop at least invisible (still takes place in the viewport and on mobile doesn't work, but there the scrollbar is a fine line that is placed over the content on the right).

overflow-y: auto; //or hidden if you don't want horizontal scrolling
overflow-y: auto;
scrollbar-color: transparent transparent;

Angular2 QuickStart npm start is not working correctly

  1. In devDependencies typescript is 1.7.3 but you have 1.7.5 fix common one.
  2. Import your js files in the correct order in index.html. for more info refer this repository https://github.com/pkozlowski-opensource/ng2-play/blob/master/index.html or refer to my repository here

    https://github.com/MrPardeep/Angular2-DatePicker

index.html

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script>
        System.config({
                    defaultJSExtensions: true,
                    map: {
                        rxjs: 'node_modules/rxjs'
                    },
                    packages: {
                        rxjs: {
                        defaultExtension: 'js'
                      }
                    }
                });
    </script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/router.dev.js"></script>
    <script src="node_modules/angular2/bundles/http.dev.js"></script>

<script>
    System.import('dist/bootstrap');
</script> 

How to write data to a JSON file using Javascript

Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.

For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.


For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.

If you want update your JSON file cross-browser you have to use server and client side together.

The client side script

On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).

var xhr = new XMLHttpRequest(),
    jsonArr,
    method = "GET",
    jsonRequestURL = "SOME_PATH/jsonFile/";

xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        // we convert your JSON into JavaScript object
        jsonArr = JSON.parse(xhr.responseText);

        // we add new value:
        jsonArr.push({"nissan": "sentra", "color": "green"});

        // we send with new request the updated JSON file to the server:
        xhr.open("POST", jsonRequestURL, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // if you want to handle the POST response write (in this case you do not need it):
        // xhr.onreadystatechange = function(){ /* handle POST response */ };
        xhr.send("jsonTxt="+JSON.stringify(jsonArr));
        // but on this place you have to have a server for write updated JSON to the file
    }
};
xhr.send(null);

Server side scripts

You can use a lot of different servers, but I would like to write about PHP and Node.js servers.

By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.

PHP server side script solution

The PHP script for reading and writing from JSON file:

<?php

// This PHP script must be in "SOME_PATH/jsonFile/index.php"

$file = 'jsonFile.txt';

if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
    file_put_contents($file, $_POST["jsonTxt"]);
    //may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
    echo file_get_contents($file);
    //may be some error handeling if you want
}
?>

Node.js server side script solution

I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:

The Node.js script for reading and writing from JSON file:

var http = require("http"),
    fs = require("fs"),
    port = 8080,
    pathToJSONFile = '/SOME_PATH/jsonFile.txt';

http.createServer(function(request, response)
{
    if(request.method == 'GET')
    {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(fs.readFile(pathToJSONFile, 'utf8'));
        response.end();
    }
    else if(request.method == 'POST')
    {
        var body = [];

        request.on('data', function(chunk)
        {
            body.push(chunk);
        });

        request.on('end', function()
        {
            body = Buffer.concat(body).toString();
            var myJSONdata = body.split("=")[1];
            fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
        });
    }
}).listen(port);

Related links for Node.js:

How do I output lists as a table in Jupyter notebook?

If you don't mind using a bit of html, something like this should work.

from IPython.display import HTML, display

def display_table(data):
    html = "<table>"
    for row in data:
        html += "<tr>"
        for field in row:
            html += "<td><h4>%s</h4><td>"%(field)
        html += "</tr>"
    html += "</table>"
    display(HTML(html))

And then use it like this

data = [[1,2,3],[4,5,6],[7,8,9]]
display_table(data)

enter image description here

How can I change the font size using seaborn FacetGrid?

The FacetGrid plot does produce pretty small labels. While @paul-h has described the use of sns.set as a way to the change the font scaling, it may not be the optimal solution since it will change the font_scale setting for all plots.

You could use the seaborn.plotting_context to change the settings for just the current plot:

with sns.plotting_context(font_scale=1.5):
    sns.factorplot(x, y ...)

Case statement with multiple values in each 'when' block

Another nice way to put your logic in data is something like this:

# Initialization.
CAR_TYPES = {
  foo_type: ['honda', 'acura', 'mercedes'],
  bar_type: ['toyota', 'lexus']
  # More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }

case @type_for_name[car]
when :foo_type
  # do foo things
when :bar_type
  # do bar things
end

VS Code - Search for text in all files in a directory

And by the way for you fellow googlers for selecting multiple folders in the search input you separate your directories with a comma. Works both for exclude and include

Example: ./src/public/,src/components/

Limiting the number of characters in a string, and chopping off the rest

The solution may be java.lang.String.format("%" + maxlength + "s", string).trim(), like this:

int maxlength = 20;
String longString = "Any string you want which length is greather than 'maxlength'";
String shortString = "Anything short";
String resultForLong = java.lang.String.format("%" + maxlength + "s", longString).trim();
String resultForShort = java.lang.String.format("%" + maxlength + "s", shortString).trim();
System.out.println(resultForLong);
System.out.println(resultForShort);

ouput:

Any string you want w

Anything short

What do hjust and vjust do when making a plot using ggplot?

Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.

enter image description here

However, it is not quite that simple. hjust and vjust as described there are how it works in geom_text and theme_text (sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust of 0.5 and a vjust of 0.5 center the box on the reference point. Reducing hjust moves the box right by an amount of the box width times 0.5-hjust. Thus when hjust=0, the left edge of the box is at the reference point. Increasing hjust moves the box left by an amount of the box width times hjust-0.5. When hjust=1, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5 box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].

But, sometimes this doesn't work. For example

DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))

The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider

p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))

The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.

Convert YYYYMMDD to DATE

The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?

To find the values that are causing issues (so you (or whoever designed this table) can fix them):

SELECT GRADUATION_DATE FROM mydb
  WHERE ISDATE(GRADUATION_DATE) = 0;

Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.

ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;

Now you don't have to worry about the formatting - you can always format as YYYYMMDD or YYYY-MM-DD on the client, or using CONVERT in SQL. When you have a valid date as a string literal, you can use:

SELECT CONVERT(CHAR(10), '20120101', 120);

...but this is better done on the client (if at all).

There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

Simply download javax.servlet.jsp.jstl.jar and add to your build path and WEB-INF/lib if you simply developing dynamic web application.

When you develop dynamic web application using maven then add javax.servlet.jsp.jstl dependency in pom file.

Thanks

nirmalrajsanjeev

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I also had the same error .. I did this to fix it

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets" />

change to

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />

and it's done.

Extracting specific columns in numpy array

You can use the following:

extracted_data = data.ix[:,['Column1','Column2']]

What is the meaning of "this" in Java?

In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie 'this') as an ActionListener for components.

public class MyDialog extends JDialog implements ActionListener
{
    public MyDialog()
    {
        JButton myButton = new JButton("Hello");
        myButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent evt)
    {
        System.out.println("Hurdy Gurdy!");
    }

}

Does "\d" in regex mean a digit?

\d matches any single digit in most regex grammar styles, including python. Regex Reference

What is the difference between typeof and instanceof and when should one be used vs. the other?

with performance in mind, you'd better use typeof with a typical hardware, if you create a script with a loop of 10 million iterations the instruction: typeof str == 'string' will take 9ms while 'string' instanceof String will take 19ms

Java JDBC - How to connect to Oracle using Service Name instead of SID

So there are two easy ways to make this work. The solution posted by Bert F works fine if you don't need to supply any other special Oracle-specific connection properties. The format for that is:

jdbc:oracle:thin:@//HOSTNAME:PORT/SERVICENAME

However, if you need to supply other Oracle-specific connection properties then you need to use the long TNSNAMES style. I had to do this recently to enable Oracle shared connections (where the server does its own connection pooling). The TNS format is:

jdbc:oracle:thin:@(description=(address=(host=HOSTNAME)(protocol=tcp)(port=PORT))(connect_data=(service_name=SERVICENAME)(server=SHARED)))

If you're familiar with the Oracle TNSNAMES file format, then this should look familiar to you. If not then just Google it for the details.

Is it possible to add an HTML link in the body of a MAILTO link

The specification for 'mailto' body says:

The body of a message is simply lines of US-ASCII characters. The only two limitations on the body are as follows:

  • CR and LF MUST only occur together as CRLF; they MUST NOT appear independently in the body.
  • Lines of characters in the body MUST be limited to 998 characters, and SHOULD be limited to 78 characters, excluding the CRLF.

https://tools.ietf.org/html/rfc5322#section-2.3

Generally nowadays most email clients are good at autolinking, but not all do, due to security concerns. You can likely find some work-arounds, but it won't necessarily work universally.

H2 in-memory database. Table not found

I had the same problem and changed my configuration in application-test.properties to this:

#Test Properties
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop

And my dependencies:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.198</version>
        <scope>test</scope>
    </dependency>

And the annotations used on test class:

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("test")
public class CommentServicesIntegrationTests {
...
}

DataGridView.Clear()

try:

datagrid.DataSource = null;
datagrid.DataBind();

Basically you will need to clear the datasource your binding to the grid.

Can't get Python to import from a different folder

The right way to import a module located on a parent folder, when you don't have a standard package structure, is:

import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))

(you can merge the last two lines but this way is easier to understand).

This solution is cross-platform and is general enough to need not modify in other circumstances.

Is there a better jQuery solution to this.form.submit();?

this.form.submit();

This is probably your best bet. Especially if you are not already using jQuery in your project, there is no need to add it (or any other JS library) just for this purpose.

Character reading from file in Python

Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.

You'll have to google for "iconvcodec", since the module seems not to be supported anymore and I can't find a canonical home page for it.

>>> import iconvcodec
>>> from locale import setlocale, LC_ALL
>>> setlocale(LC_ALL, '')
>>> u'\u2018'.encode('ascii//translit')
"'"

Alternatively you can use the iconv command line utility to clean up your file:

$ xxd foo
0000000: e280 980a                                ....
$ iconv -t 'ascii//translit' foo | xxd
0000000: 270a                                     '.

How to call an async method from a getter or setter?

When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:

string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();

You could argue that I abuse the framework, but it works.

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

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

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

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

Keep only first n characters in a string?

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Add php variable inside echo statement as href link address?

If you want to print in the tabular form with, then you can use this:

echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;

Is __init__.py not required for packages in Python 3.3+

Based on my experience, even with python 3.3+, an empty __init__.py is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m test.foo, it didn't work until I created an empty __init__.py under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.

Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty __init__.py in your package folder.

Python - round up to the nearest ten

Here is one way to do it:

>>> n = 46
>>> (n + 9) // 10 * 10
50

Javascript array search and remove string?

const changedArray = array.filter( function(value) {
  return value !== 'B'
});

or you can use :

const changedArray = array.filter( (value) => value === 'B');

The changedArray will contain the without value 'B'

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

regular expression: match any word until first space

Derived from the answer of @SilentGhost I would use:

^([\S]+)

Check out this interactive regexr.com page to see the result and explanation for the suggested solution.

How to use session in JSP pages to get information?

_x000D_
_x000D_
form action="editinfo" method="post">_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Username:</td>_x000D_
    <td>_x000D_
      <input type="text" value="<%if( request.getSession().getAttribute(" parameter_whatever_you_passed ") != null_x000D_
{_x000D_
request.getSession().getAttribute("parameter_whatever_you_passed ").toString();_x000D_
}_x000D_
 %>" />_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Tensorflow: how to save/restore a model?

Use tf.train.Saver to save a model, remerber, you need to specify the var_list, if you want to reduce the model size. The val_list can be tf.trainable_variables or tf.global_variables.

Bootstrap radio button "checked" flag

In case you want to use bootstrap radio to check one of them depends on the result of your checked var in the .ts file.

component.html

<h1>Radio Group #1</h1>
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
   <label [ngClass]="checked ? 'active' : ''" class="btn btn-outline-secondary">
     <input name="radio" id="radio1" value="option1" type="radio"> TRUE
   </label>
   <label [ngClass]="!checked ? 'active' : ''" class="btn btn-outline-secondary">
     <input name="radio" id="radio2" value="option2" type="radio"> FALSE
   </label>
</div>

component.ts file

@Component({
  selector: '',
  templateUrl: './.component.html',
  styleUrls: ['./.component.css']
})
export class radioComponent implements OnInit {
  checked = true;
}

How to resolve ORA 00936 Missing Expression Error?

Remove the comma?

select /*+USE_HASH( a b ) */ to_char(date, 'MM/DD/YYYY HH24:MI:SS') as LABEL,
ltrim(rtrim(substr(oled, 9, 16))) as VALUE
from rrfh a, rrf b
where ltrim(rtrim(substr(oled, 1, 9))) = 'stata kish' 
and a.xyz = b.xyz

Have a look at FROM

SELECTING from multiple tables You can include multiple tables in the FROM clause by listing the tables with a comma in between each table name

Installing RubyGems in Windows

Installing Ruby

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

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

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

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

Installing Gem

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

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

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

If not, please correct path to your ruby folders.

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

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

A child container failed during start java.util.concurrent.ExecutionException

check if you JAVA_HOME is set to 1.7 or below. because tomcat 7 is not compatible with jdk 1.8

This worked for me

The calling thread must be STA, because many UI components require this

You can also try this

// create a thread  
Thread newWindowThread = new Thread(new ThreadStart(() =>  
{  
    // create and show the window
    FaxImageLoad obj = new FaxImageLoad(destination);  
    obj.Show();  
    
    // start the Dispatcher processing  
    System.Windows.Threading.Dispatcher.Run();  
}));  

// set the apartment state  
newWindowThread.SetApartmentState(ApartmentState.STA);  

// make the thread a background thread  
newWindowThread.IsBackground = true;  

// start the thread  
newWindowThread.Start();  

How to detect a USB drive has been plugged in?

Microsoft API Code Pack. ShellObjectWatcher class.

removing bold styling from part of a header

It is super simple, By using "font" inside paragraph. An example is shown below:

<h1>Heading 1</h1>
<p><font size="6"> Heading 1</font></p>

Heading 1

Heading 1

ValueError when checking if variable is None or numpy.array

You can see if object has shape or not

def check_array(x):
    try:
        x.shape
        return True
    except:
        return False

How do I make the first letter of a string uppercase in JavaScript?

If you are wanting to reformat all-caps text, you might want to modify the other examples as such:

function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

This will ensure that the following text is changed:

TEST => Test
This Is A TeST => This is a test

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

From the jQuery documentation: you specify the asynchronous option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function (node, targetNode, type, to) {
    jQuery.ajax({
        url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
        success: function (result) {
            if (result.isOk == false) alert(result.message);
        },
        async: false
    });
}

error: expected declaration or statement at end of input in c

Normally that error occurs when a } was missed somewhere in the code, for example:

void mi_start_curr_serv(void){
    #if 0
    //stmt
    #endif

would fail with this error due to the missing } at the end of the function. The code you posted doesn't have this error, so it is likely coming from some other part of your source.

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

Here's an example where isinstance achieves something that type cannot:

class Vehicle:
    pass

class Truck(Vehicle):
    pass

in this case, a truck object is a Vehicle, but you'll get this:

isinstance(Vehicle(), Vehicle)  # returns True
type(Vehicle()) == Vehicle      # returns True
isinstance(Truck(), Vehicle)    # returns True
type(Truck()) == Vehicle        # returns False, and this probably won't be what you want.

In other words, isinstance is true for subclasses, too.

Also see: How to compare type of an object in Python?

Position buttons next to each other in the center of page

Utilize regular buttons and set the display property to inline in order to center the buttons on a single line. Setting the display property to inline-block will also put them on the same line, but they will not be centered via that display property setting.

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

Event for Handling the Focus of the EditText

Here is the focus listener example.

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
            Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
        }
    }
});

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

you need to add jersey-bundle-1.17.1.jar to lib of project

<servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <!-- <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> --> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <!-- <param-name>jersey.config.server.provider.packages</param-name> --> <param-value>package.package.test</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

moving committed (but not pushed) changes to a new branch after pull

If you have a low # of commits and you don't care if these are combined into one mega-commit, this works well and isn't as scary as doing git rebase:

unstage the files (replace 1 with # of commits)

git reset --soft HEAD~1

create a new branch

git checkout -b NewBranchName

add the changes

git add -A

make a commit

git commit -m "Whatever"

How can I find whitespace in a String?

Use this code, was better solution for me.

public static boolean containsWhiteSpace(String line){
    boolean space= false; 
    if(line != null){


        for(int i = 0; i < line.length(); i++){

            if(line.charAt(i) == ' '){
            space= true;
            }

        }
    }
    return space;
}

How to undo a git pull?

This worked for me.

git reset --hard ORIG_HEAD 

Undo a merge or pull:

$ git pull                         (1)
Auto-merging nitfol
CONFLICT (content): Merge conflict in nitfol
Automatic merge failed; fix conflicts and then commit the result.
$ git reset --hard                 (2)
$ git pull . topic/branch          (3)
Updating from 41223... to 13134...
Fast-forward
$ git reset --hard ORIG_HEAD       (4)

Checkout this: HEAD and ORIG_HEAD in Git for more.

How to set focus on input field?

HTML has an attribute autofocus.

<input type="text" name="fname" autofocus>

http://www.w3schools.com/tags/att_input_autofocus.asp

How to Correctly Check if a Process is running and Stop it

The way you're doing it you're querying for the process twice. Also Lynn raises a good point about being nice first. I'd probably try something like the following:

# get Firefox process
$firefox = Get-Process firefox -ErrorAction SilentlyContinue
if ($firefox) {
  # try gracefully first
  $firefox.CloseMainWindow()
  # kill after five seconds
  Sleep 5
  if (!$firefox.HasExited) {
    $firefox | Stop-Process -Force
  }
}
Remove-Variable firefox

Android Fragments and animation

As for me, i need the view diraction:

in -> swipe from right

out -> swipe to left

Here works for me code:

slide_in_right.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="50%p" android:toXDelta="0"
            android:duration="@android:integer/config_mediumAnimTime"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
            android:duration="@android:integer/config_mediumAnimTime" />
</set>

slide_out_left.xml

 <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate android:fromXDelta="0" android:toXDelta="-50%p"
                android:duration="@android:integer/config_mediumAnimTime"/>
        <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
                android:duration="@android:integer/config_mediumAnimTime" />
    </set>

transaction code:

inline fun FragmentActivity.setContentFragment(
        containerViewId: Int,
        backStack: Boolean = false,
        isAnimate: Boolean = false,
        f: () -> Fragment

): Fragment? {
    val manager = supportFragmentManager
    return f().apply {
        manager.beginTransaction().let {
            if (isAnimate)
                it.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)

            if (backStack) {
                it.replace(containerViewId, this, "Fr").addToBackStack("Fr").commit()
            } else {
                it.replace(containerViewId, this, "Fr").commit()
            }
        }
    }
}

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark - NSSecureCoding

The main purpose of "pragma" is for developer reference.enter image description here

You can easily find a method/Function in a vast thousands of coding lines.

Xcode 11+:

Marker Line in Top

// MARK: - Properties

Marker Line in Top and Bottom

// MARK: - Properties - 

Marker Line only in bottom

// MARK: Properties -

Stop and Start a service via batch or cmd file?

or you can start remote service with this cmd : sc \\<computer> start <service>

Installation of VB6 on Windows 7 / 8 / 10

I've installed and use VB6 for legacy projects many times on Windows 7.

What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.

Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721

Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm

vba pass a group of cells as range to function

As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.

So as on the above question I have putted my basic efforts.

Function multi_add(a As Range, ParamArray b() As Variant) As Double

    Dim ele As Variant

    Dim i As Long

    For Each ele In a
        multi_add = a + ele.Value **- a**
    Next ele

    For i = LBound(b) To UBound(b)
        For Each ele In b(i)
            multi_add = multi_add + ele.Value
        Next ele
    Next i

End Function

- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.

Simulator or Emulator? What is the difference?

Both terms are something completely different and only intersect very little. To find the right term is actually very easy, just think about following:

A simulation does not do anything for real. You can study it, for example how computer work, but it usually has no outcome other than that. A plane crash in a Flight Simulator causes no real harm. A weather forecast simulation itself does not change the weather.

An emulation does something for real. You can work with an emulated computer like with a physical one and create documents with it. And a plane crash in a Flight Emulator would have an outcome, like people experiencing the real impact including possible physical harm.

Your confusion probably stems from the fact, that "studying the simulation" and "accessing the emulation" often is quite the same thing.

You are not alone with your confusion. The Film "Matrix" speaks of a simulation. However The Matrix is running an emulation, as it has real impact on all members of The Matrix. In contrast the training room has no real impact, so this is a simulation (of The Matrix).

Let's see some examples.

Simulated vs. Emulated Rain

Take a water hose in the garden and let it rain. What's the difference between simulation and emulation here?

When you are simulating rain, people still will blame you for getting wet. Your rain has some real impact on the world, but your simulation hasn't, as the simulation does not fool anybody in that it is real rain.

In contrast, when you are emulating rain, people would blame the weather. This is, your emulated rain really behaves like rain in reality. This rain emulation hence distorts reality, in making people belie in the wrong culprit.

It took me quite some time to understand that. Hence it isn't easy nor obvious which explains all the confusion.

Keep in mind that a simulation can have sideeffects, like the weather forecast is based on simulations, which takes quite some computing power and thus electrical energy, which has an environmental impact.

Hence in the example of "simulated rain", people getting wet just is a sideffect and not part of the simulation. Same is true if you simulate a rainbow with this simulated rain. While the property of "how rainbows work" is part of this simulation, the simulation itself is not providing the rainbow, this just happens due to refraction of the sun on the sideffect of the waterdrops.

Simulated vs. Emulated Computer

While you might think "a simulated computer can have an outcome" this is practically wrong reasoning. If you save files onto a simulated harddrive, these files cannot leave the simulated drive outside of the simulation. You can obtain the files by studying the simulated drive, but this is not part of the simulation itself.

In case the harddrive saves the data such, that the data is actually usable outside of the simulation, you have an emulated harddrive within the simulation to do so.

So an emulation can be part of a simulation and vice versa.

Simulated vs. Emulated Filesystem

If you simulate a filesystem, you probably, for practicability, will choose to save the files onto your real filesystem as-is (perhaps with some additional meta-information). In that case the simulation seems to create real "value" outside of the simulation: Usable files!

But this is just by coincidence, because your simulated filesystem actually emulates a filesystem as well. You actually emulated the outside filesystem inside your simulation!

Simulated vs. Emulated TPM or HSM

A good example of the difference is, when you think of security. A TPM is a specific device to keep it's own keys secure (source of identity) while an HSM is a general device to secure foreign keys (verify identity).

Fun Fact: My fingers constantly type TMP instead of TPM.

If you simulate a TPM this has a huge effect on security, because then you can observe the internal states of the TPM. Which renders all the security void. Even that such a simulation can give you valuable hints of improving the design of a TPM itself, you won't want to expose precious data to the simulated TPM for real.

However if you emulate a TPM you will try to hide these internal states to the outside as good as you can. Such an emulated TPM then can be possibly used to really secure something else better than without it.

With a real TPM you cannot emulate the properties of a real HSM. All you can archive is to simulate an HSM, but this will not have the security properties of a real HSM, so all data which is stored in this simulated HSM will not be protected (they will only be protected within the simulation itself).

In contrast, with a real HSM you can emulate a TPM with all properties of a real TPM. For this the HSM needs to be constructed such, that no information needs to leave the HSM which does not leave a TPM as well.

(Please note that I do not know anything about HSMs or TPMs in particular, so it might be that there are no HSMs out there which are able to provide emulated TPMs.)

Simulated vs. Emulated World

If our world is simulated, we are simulations, too. Hence some spectator (let's call her God) can look at us and change the simulation any time. Also we cannot find out if we are simulated or not. As I am pretty sure that I know that I am, I do not think I am simulated, because self-awareness looks like an effect with a real component to me, which contradicts simulation. This also means, our world cannot be a simulation, too, as a simulation can only affect me like the world does, if I am part of the simulation.

But our world still can be emulated (like in the Film "Matrix"), as all I have to "prove the world" is my state of mind and sensory input, which I cannot verify, as I cannot leave myself. If I am not part of the emulation, then there should be a chance to observe discontinuity (like in the film "Matrix"), in case the emulation does not work flawlessly.

This changes when I emulated, too, like running an OS in an emulator. Then I cannot observe such errors, as my state can be reset from within the emulation (call it: Sleep) without observable discontinuation.

However I rather think that the world is a holographic hallucination than something like an emulation. Because if it is emulated, then I am pwned by somebody (call him Rick) who is running the emulation for some purpose, while a hallucination is purely my own thing.

I stop here, because hallucinations lead us to something completely different.

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as

<class>com.yourCompanyName.WhateverEntityClass</class>

In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.

Add space between HTML elements only using CSS

span:not(:last-child) {
    margin-right: 10px;
}

Run PostgreSQL queries from the command line

  1. Open a command prompt and go to the directory where Postgres installed. In my case my Postgres path is "D:\TOOLS\Postgresql-9.4.1-3".After that move to the bin directory of Postgres.So command prompt shows as "D:\TOOLS\Postgresql-9.4.1-3\bin>"
  2. Now my goal is to select "UserName" from the users table using "UserId" value.So the database query is "Select u."UserName" from users u Where u."UserId"=1".

The same query is written as below for psql command prompt of postgres.

D:\TOOLS\Postgresql-9.4.1-3\bin>psql -U postgres -d DatabaseName -h localhost - t -c "Select u.\"UserName\" from users u Where u.\"UserId\"=1;

How to convert Blob to File in JavaScript

Typescript

public blobToFile = (theBlob: Blob, fileName:string): File => {       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}

Javascript

function blobToFile(theBlob, fileName){       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}

Output

screenshot

File {name: "fileName", lastModified: 1597081051454, lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 601887, …}
lastModified: 1597081051454
lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time) {}
name: "fileName"
size: 601887
type: "image/png"
webkitRelativePath: ""
__proto__: File

Updating PartialView mvc 4

Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.

So, in JS:

$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");

In Controller:

var model = _newPoints;
return PartialView(model);

In View

<div id="divPoints"></div>
@Html.Hidden("newpoints", Model)

how concatenate two variables in batch script?

You can do it without setlocal, because of the setlocal command the variable won't survive an endlocal because it was created in setlocal. In this way the variable will be defined the right way.

To do that use this code:

set var1=A

set var2=B

set AB=hi

call set newvar=%%%var1%%var2%%%

echo %newvar% 

Note: You MUST use call before you set the variable or it won't work.

How to install libusb in Ubuntu

Usually to use the library you need to install the dev version.

Try

sudo apt-get install libusb-1.0-0-dev

Is there a way to specify how many characters of a string to print out using printf()?

In C++, I do it in this way:

char *buffer = "My house is nice";
string showMsgStr(buffer, buffer + 5);
std::cout << showMsgStr << std::endl;

Please note this is not safe because when passing the second argument I can go beyond the size of the string and generate a memory access violation. You have to implement your own check for avoiding this.

How to have comments in IntelliSense for function in Visual Studio?

To generate an area where you can specify a description for the function and each parameter for the function, type the following on the line before your function and hit Enter:

  • C#: ///

  • VB: '''

See Recommended Tags for Documentation Comments (C# Programming Guide) for more info on the structured content you can include in these comments.

Android, How to create option Menu

Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method This will help

And you should also have the onCreate method in your activity

How can I stop float left?

A standard approach is to add a clearing div between the two floating block level elements:

<div style="clear:both;"></div>

How to put a component inside another component in Angular2?

You don't put a component in directives

You register it in @NgModule declarations:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyChildComponent ],
  bootstrap: [ App ]
})

and then You just put it in the Parent's Template HTML as : <my-child></my-child>

That's it.

Cannot deserialize the current JSON array (e.g. [1,2,3])

You can use this to solve your problem:

private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
    HttpClient webClient = new HttpClient();
    Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
    HttpResponseMessage response = await webClient.GetAsync(uri);
    var jsonString = await response.Content.ReadAsStringAsync();
    var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
    foreach (Student Student in _Data)
    {
        tb1.Text = Student.student_name;
    }
}

MySQL - How to select rows where value is in array?

If you use the FIND_IN_SET function:

FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others

AND

FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others

So if record1 is (a,b,c) and record2 is (a)

FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

Is there a way to override class variables in Java?

Of course using private attributes, and getters and setters would be the recommended thing to do, but I tested the following, and it works... See the comment in the code

class Dad
{
    protected static String me = "dad";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    protected static String me = "son";

    /* 
    Adding Method printMe() to this class, outputs son 
    even though Attribute me from class Dad can apparently not be overridden
    */

    public void printMe()
    {
        System.out.println(me);
    }
}

class Tester
{
    public static void main(String[] arg)
    {
        new Son().printMe();
    }
}

Sooo ... did I just redefine the rules of inheritance or did I put Oracle into a tricky situation ? To me, protected static String me is clearly overridden, as you can see when you execute this program. Also, it does not make any sense to me why attributes should not be overridable.

EditText, inputType values (xml)

Supplemental answer

Here is how the standard keyboard behaves for each of these input types.

enter image description here

See this answer for more details.

What are the differences between LDAP and Active Directory?

LDAP is a standard, AD is Microsoft's (proprietary) implementation (and more). Wikipedia has a good article that delves into the specifics. I found this document with a very detailed evaluation of AD from an LDAP perspective.

Problem in running .net framework 4.0 website on iis 7.0

If you don't have ISAPI and CGI Restrictions option listed, here is how to add it. How to add ISAPI and CGI Restrictions

enter image description here

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

A solution is presented here not exactly for your problem but exactly for the given error.

  1. Start --> All Programs --> Microsoft SQL Server 2005 --> Configuration Tools --> SQL Server Surface Area Configuration

  2. Add New Administrator

  3. Select 'Member of SQL Server SysAdmin role on SQLEXPRESS' and add it to right box.

  4. Click Ok.

How to remove square brackets in string using regex?

here you go

var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'

How to change app default theme to a different app theme?

To change your application to a different built-in theme, just add this line under application tag in your app's manifest.xml file.

Example:

<application 
    android:theme="@android:style/Theme.Holo"/>

<application 
    android:theme="@android:style/Theme.Holo.Light"/>

<application 
    android:theme="@android:style/Theme.Black"/>

<application 
    android:theme="@android:style/Theme.DeviceDefault"/>

If you set style to DeviceDefault it will require min SDK version 14, but if you won't add a style, it will set to the device default anyway.

<uses-sdk
    android:minSdkVersion="14"/>

javascript get child by id

This works well:

function test(el){
  el.childNodes.item("child").style.display = "none";
}

If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.

git rebase fatal: Needed a single revision

You need to provide the name of a branch (or other commit identifier), not the name of a remote to git rebase.

E.g.:

git rebase origin/master

not:

git rebase origin

Note, although origin should resolve to the the ref origin/HEAD when used as an argument where a commit reference is required, it seems that not every repository gains such a reference so it may not (and in your case doesn't) work. It pays to be explicit.

What possibilities can cause "Service Unavailable 503" error?

Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.

This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.

Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.

Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks

How can I play sound in Java?

There is an alternative to importing the sound files which works in both applets and applications: convert the audio files into .java files and simply use them in your code.

I have developed a tool which makes this process a lot easier. It simplifies the Java Sound API quite a bit.

http://stephengware.com/projects/soundtoclass/

Checking something isEmpty in Javascript?

It depends on what you mean by "empty". The most common pattern is to check to see if the variable is undefined. Many people also do a null check, for example:
if (myVariable === undefined || myVariable === null)...

or, in a shorter form:
if (myVariable || myVariable === null)...

Number of elements in a javascript object

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

Probably the closest you'll get is something like this

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

Convert PEM traditional private key to PKCS8 private key

To convert the private key from PKCS#1 to PKCS#8 with openssl:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.

IE 8: background-size fix

Also i have found another useful link. It is a background hack used like this

.selector { background-size: cover; -ms-behavior: url(/backgroundsize.min.htc); }

https://github.com/louisremi/background-size-polyfill

How to send image to PHP file using Ajax?

Jquery code which contains simple ajax :

   $("#product").on("input", function(event) {
      var data=$("#nameform").serialize();
    $.post("./__partails/search-productbyCat.php",data,function(e){
       $(".result").empty().append(e);

     });


    });

Html elements you can use any element:

     <form id="nameform">
     <input type="text" name="product" id="product">
     </form>

php Code:

  $pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
  $Catagoryf=$_POST['product'];

 $pricef=$_POST['price'];
  $colorf=$_POST['color'];

  $stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
  $stmtcat->execute(array($Catagoryf));

  while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
  $iddb=$result['ID'];
     $namedb=$result['Name'];
    $pricedb=$result['Price'];
     $colordb=$result['Color'];

   echo "<tr>";
   echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>'; 
   echo "<td><pre>$pricedb</pre></td>";
   echo "<td><pre>    $colordb</pre>";
   echo "</tr>";

The easy way

What is the default lifetime of a session?

But watch out, on most xampp/ampp/...-setups and some linux destributions it's 0, which means the file will never get deleted until you do it within your script (or dirty via shell)

PHP.INI:

; Lifetime in seconds of cookie or, if 0, until browser is restarted.
; http://php.net/session.cookie-lifetime
session.cookie_lifetime = 0

LISTAGG function: "result of string concatenation is too long"

Since the aggregates string can be longer than 4000 bytes, you can't use the LISTAGG function. You could potentially create a user-defined aggregate function that returns a CLOB rather than a VARCHAR2. There is an example of a user-defined aggregate that returns a CLOB in the original askTom discussion that Tim links to from that first discussion.

Rounding integer division (instead of truncating)

double a=59.0/4;
int b=59/4;
if(a-b>=0.5){
    b++;
}
printf("%d",b);
  1. let exact float value of 59.0/4 be x(here it is 14.750000)
  2. let smallest integer less than x be y(here it is 14)
  3. if x-y<0.5 then y is the solution
  4. else y+1 is the solution

get list of packages installed in Anaconda

in terminal, type : conda list to obtain the packages installed using conda.

for the packages that pip recognizes, type : pip list

There may be some overlap of these lists as pip may recognize packages installed by conda (but maybe not the other way around, IDK).

There is a useful source here, including how to update or upgrade packages..

Eclipse error ... cannot be resolved to a type

There are two ways to solve the issue "cannot be resolved to a type ":

  1. For non maven project, add jars manually in a folder and add it in java build path. This would solve the compilation errors.
  2. For maven project, right click on the project and go to maven -> update project. Select all the projects where you are getting compilation errors and also check "Force update of snapshots/releases". This will update the project and fix the compilation errors.

Why doesn't TFS get latest get the latest?

Go with right click: Advanced > Get Specific Version. Select "Letest Version" and now, important, mark two checks: enter image description here

The checks are:
Overwrite writeable files that are not checked

Overwrite all files even if the local version matches the specified version

How do I determine file encoding in OS X?

Classic 8-bit LaTeX is very restricted in which UTF8 characters it can use; it's highly dependent on the encoding of the font you're using and which glyphs that font has available.

Since you don't give a specific example, it's hard to know exactly where the problem is — whether you're attempting to use a glyph that your font doesn't have or whether you're not using the correct font encoding in the first place.

Here's a minimal example showing how a few UTF8 characters can be used in a LaTeX document:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}
\begin{document}
‘Héllø—thêrè.’
\end{document}

You may have more luck with the [utf8x] encoding, but be slightly warned that it's no longer supported and has some idiosyncrasies compared with [utf8] (as far as I recall; it's been a while since I've looked at it). But if it does the trick, that's all that matters for you.

How can we programmatically detect which iOS version is device running on?

I know I am too late to answer this question. I am not sure does my method still working on low iOS versions (< 5.0):

NSString *platform = [UIDevice currentDevice].model;

NSLog(@"[UIDevice currentDevice].model: %@",platform);
NSLog(@"[UIDevice currentDevice].description: %@",[UIDevice currentDevice].description);
NSLog(@"[UIDevice currentDevice].localizedModel: %@",[UIDevice currentDevice].localizedModel);
NSLog(@"[UIDevice currentDevice].name: %@",[UIDevice currentDevice].name);
NSLog(@"[UIDevice currentDevice].systemVersion: %@",[UIDevice currentDevice].systemVersion);
NSLog(@"[UIDevice currentDevice].systemName: %@",[UIDevice currentDevice].systemName);

You can get these results:

[UIDevice currentDevice].model: iPhone
[UIDevice currentDevice].description: <UIDevice: 0x1cd75c70>
[UIDevice currentDevice].localizedModel: iPhone
[UIDevice currentDevice].name: Someones-iPhone002
[UIDevice currentDevice].systemVersion: 6.1.3
[UIDevice currentDevice].systemName: iPhone OS

How do I find which program is using port 80 in Windows?

Use this nifty freeware utility:

CurrPorts is network monitoring software that displays the list of all currently opened TCP/IP and UDP ports on your local computer.

Enter image description here

How can I simulate a click to an anchor tag?

None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):

var clicker = null;
$('a').click(function(e){ 
    clicker=$(this); // capture the clicked dom object
    /* ... do something ... */
    e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.

SQL: IF clause within WHERE clause

Use a CASE statement
UPDATE: The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows:

WHERE OrderNumber LIKE
  CASE WHEN IsNumeric(@OrderNumber) = 1 THEN 
    @OrderNumber 
  ELSE
    '%' + @OrderNumber
  END

Or you can use an IF statement like @N. J. Reed points out.

Touch move getting stuck Ignored attempt to cancel a touchmove

The event must be cancelable. Adding an if statement solves this issue.

if (e.cancelable) {
   e.preventDefault();
}

In your code you should put it here:

if (this.isSwipe(swipeThreshold) && e.cancelable) {
   e.preventDefault();
   e.stopPropagation();
   swiping = true;
}

Scroll part of content in fixed position container

I changed scrollable div to be with absolute position, and everything works for me

div.sidebar {
    overflow: hidden;
    background-color: green;
    padding: 5px;
    position: fixed;
    right: 20px;
    width: 40%;
    top: 30px;
    padding: 20px;
    bottom: 30%;
}
div#fixed {
    background: #76a7dc;
    color: #fff;
    height: 30px;
}

div#scrollable {
    overflow-y: scroll;
    background: lightblue;

    position: absolute;
    top:55px; 
    left:20px;
    right:20px;
    bottom:10px;
}

DEMO with two scrollable divs

how to measure running time of algorithms in python

The programming language doesn't matter; measuring the runtime complexity of an algorithm works the same way regardless of the language. Analysis of Algorithms by Stanford on Google Code University is a very good resource for teaching yourself how to analyze the runtime complexity of algorithms and code.

If all you want to do is measure the elapsed time that a function or section of code took to run in Python, then you can use the timeit or time modules, depending on how long the code needs to run.

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

Open a URL without using a browser from a batch file

Not sure whether you have already gotten your owner solution. I have been using the following powshell command to achieve it:

powershell.exe -noprofile -command "Invoke-WebRequest -Uri http://your_url"

How to alter a column's data type in a PostgreSQL table?

If data already exists in the column you should do:

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;

As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.

Best way to store password in database

Background You never ... really ... need to know the user's password. You just want to verify an incoming user knows the password for an account.

Hash It: Store user passwords hashed (one-way encryption) via a strong hash function. A search for "c# encrypt passwords" gives a load of examples.

See the online SHA1 hash creator for an idea of what a hash function produces (But don't use SHA1 as a hash function, use something stronger such as SHA256).

Now, a hashed passwords means that you (and database thieves) shouldn't be able to reverse that hash back into the original password.

How to use it: But, you say, how do I use this mashed up password stored in the database?

When the user logs in, they'll hand you the username and the password (in its original text) You just use the same hash code to hash that typed-in password to get the stored version.

So, compare the two hashed passwords (database hash for username and the typed-in & hashed password). You can tell if "what they typed in" matched "what the original user entered for their password" by comparing their hashes.

Extra credit:

Question: If I had your database, then couldn't I just take a cracker like John the Ripper and start making hashes until I find matches to your stored, hashed passwords? (since users pick short, dictionary words anyway ... it should be easy)

Answer: Yes ... yes they can.

So, you should 'salt' your passwords. See the Wikipedia article on salt

See "How to hash data with salt" C# example (archived)

How to turn on front flash light programmatically in Android?

Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.

It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!

To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.


Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

Your persistence.xml is not valid and the EntityManagerFactory can't get created. It should be:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
  <persistence-unit name="customerManager" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>Customer</class>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>
      <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.connection.username" value="root"/>
      <property name="hibernate.connection.password" value="1234"/>
      <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/general"/>
      <property name="hibernate.max_fetch_depth" value="3"/>
    </properties>
  </persistence-unit>
</persistence>

(Note how the <property> elements are closed, they shouldn't be nested)

Update: I went through the tutorial and you will also have to change the Id generation strategy when using MySQL (as MySQL doesn't support sequences). I suggest using the AUTO strategy (defaults to IDENTITY with MySQL). To do so, remove the SequenceGenerator annotation and change the code like this:

@Entity
@Table(name="TAB_CUSTOMER")
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="CUSTOMER_ID", precision=0)
    private Long customerId = null;

   ...
}

This should help.

PS: you should also provide a log4j.properties as suggested.

How do I detect a click outside an element?

If you are scripting for IE and FF 3.* and you just want to know if the click occured within a certain box area, you could also use something like:

this.outsideElementClick = function(objEvent, objElement){   
var objCurrentElement = objEvent.target || objEvent.srcElement;
var blnInsideX = false;
var blnInsideY = false;

if (objCurrentElement.getBoundingClientRect().left >= objElement.getBoundingClientRect().left && objCurrentElement.getBoundingClientRect().right <= objElement.getBoundingClientRect().right)
    blnInsideX = true;

if (objCurrentElement.getBoundingClientRect().top >= objElement.getBoundingClientRect().top && objCurrentElement.getBoundingClientRect().bottom <= objElement.getBoundingClientRect().bottom)
    blnInsideY = true;

if (blnInsideX && blnInsideY)
    return false;
else
    return true;}

How to recover corrupted Eclipse workspace?

In my case only removing org.eclipse.e4.workbench directory (under .metadata/.plugins) and restarting Eclipse solved the problem.

Converting a Uniform Distribution to a Normal Distribution

There are plenty of methods:

  • Do not use Box Muller. Especially if you draw many gaussian numbers. Box Muller yields a result which is clamped between -6 and 6 (assuming double precision. Things worsen with floats.). And it is really less efficient than other available methods.
  • Ziggurat is fine, but needs a table lookup (and some platform-specific tweaking due to cache size issues)
  • Ratio-of-uniforms is my favorite, only a few addition/multiplications and a log 1/50th of the time (eg. look there).
  • Inverting the CDF is efficient (and overlooked, why ?), you have fast implementations of it available if you search google. It is mandatory for Quasi-Random numbers.

Error: No default engine was specified and no extension was provided

if you've got this error by using the express generator, I've solved it by using

express --view=ejs myapp

instead of

express --view=pug myapp

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

Get IPv4 addresses from Dns.GetHostEntry()

IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
    .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

appending array to FormData and send via AJAX

I've fixed the typescript version. For javascript, just remove type definitions.

  _getFormDataKey(key0: any, key1: any): string {
    return !key0 ? key1 : `${key0}[${key1}]`;
  }
  _convertModelToFormData(model: any, key: string, frmData?: FormData): FormData {
    let formData = frmData || new FormData();

    if (!model) return formData;

    if (model instanceof Date) {
      formData.append(key, model.toISOString());
    } else if (model instanceof Array) {
      model.forEach((element: any, i: number) => {
        this._convertModelToFormData(element, this._getFormDataKey(key, i), formData);
      });
    } else if (typeof model === 'object' && !(model instanceof File)) {
      for (let propertyName in model) {
        if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
        this._convertModelToFormData(model[propertyName], this._getFormDataKey(key, propertyName), formData);
      }
    } else {
      formData.append(key, model);
    }

    return formData;
  }

WCF, Service attribute value in the ServiceHost directive could not be found

Add reference of service in your service or copy dll.

How to search for a file in the CentOS command line

Try this command:

find / -name file.look

How to use null in switch

Java docs clearly stated that:

The prohibition against using null as a switch label prevents one from writing code that can never be executed. If the switch expression is of a reference type, such as a boxed primitive type or an enum, a run-time error will occur if the expression evaluates to null at run-time.

You must have to verify for null before Swithch statement execution.

if (i == null)

See The Switch Statement

case null: // will never be executed, therefore disallowed.

What are the -Xms and -Xmx parameters when starting JVM?

Run the command java -X and you will get a list of all -X options:

C:\Users\Admin>java -X
-Xmixed           mixed mode execution (default)
-Xint             interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
-Xdiag            show additional diagnostic messages
-Xnoclassgc       disable class garbage collection
-Xincgc           enable incremental garbage collection
-Xloggc:<file>    log GC status to a file with time stamps
-Xbatch           disable background compilation
-Xms<size>        set initial Java heap size.........................
-Xmx<size>        set maximum Java heap size.........................
-Xss<size>        set java thread stack size
-Xprof            output cpu profiling data
-Xfuture          enable strictest checks, anticipating future default
-Xrs              reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni       perform additional checks for JNI functions
-Xshare:off       do not attempt to use shared class data
-Xshare:auto      use shared class data if possible (default)
-Xshare:on        require using shared class data, otherwise fail.
-XshowSettings    show all settings and continue
-XshowSettings:all         show all settings and continue
-XshowSettings:vm          show all vm related settings and continue
-XshowSettings:properties  show all property settings and continue
-XshowSettings:locale      show all locale related settings and continue

The -X options are non-standard and subject to change without notice.

I hope this will help you understand Xms, Xmx as well as many other things that matters the most. :)

Getting the count of unique values in a column in bash

Here is a way to do it in the shell:

FIELD=2
cut -f $FIELD * | sort| uniq -c |sort -nr

This is the sort of thing bash is great at.

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

Waiting for another flutter command to release the startup lock

There are some action to do:

1- in pubspec.yaml press "packages get" or in terminal type " flutter packages get" and wait seconds.

if this doesn't work :

2-type flutter clean then do step(1)

if this doesn't work too :

3-type killtask /f /im dart.exe

if this doesn't work too :

4- close android studio and then restart your pc.

Selecting non-blank cells in Excel with VBA

The following VBA code should get you started. It will copy all of the data in the original workbook to a new workbook, but it will have added 1 to each value, and all blank cells will have been ignored.

Option Explicit

Public Sub exportDataToNewBook()
    Dim rowIndex As Integer
    Dim colIndex As Integer
    Dim dataRange As Range
    Dim thisBook As Workbook
    Dim newBook As Workbook
    Dim newRow As Integer
    Dim temp

    '// set your data range here
    Set dataRange = Sheet1.Range("A1:B100")

    '// create a new workbook
    Set newBook = Excel.Workbooks.Add

    '// loop through the data in book1, one column at a time
    For colIndex = 1 To dataRange.Columns.Count
        newRow = 0
        For rowIndex = 1 To dataRange.Rows.Count
            With dataRange.Cells(rowIndex, colIndex)

            '// ignore empty cells
            If .value <> "" Then
                newRow = newRow + 1
                temp = doSomethingWith(.value)
                newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
                End If

            End With
        Next rowIndex
    Next colIndex
End Sub


Private Function doSomethingWith(aValue)

    '// This is where you would compute a different value
    '// for use in the new workbook
    '// In this example, I simply add one to it.
    aValue = aValue + 1

    doSomethingWith = aValue
End Function

Convert array of integers to comma-separated string

int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);

How can I create a product key for my C# application?

You can do something like create a record which contains the data you want to authenticate to the application. This could include anything you want - e.g. program features to enable, expiry date, name of the user (if you want to bind it to a user). Then encrypt that using some crypto algorithm with a fixed key or hash it. Then you just verify it within your program. One way to distribute the license file (on windows) is to provide it as a file which updates the registry (saves the user having to type it).

Beware of false sense of security though - sooner or later someone will simply patch your program to skip that check, and distribute the patched version. Or, they will work out a key that passes all checks and distribute that, or backdate the clock, etc. It doesn't matter how convoluted you make your scheme, anything you do for this will ultimately be security through obscurity and they will always be able to this. Even if they can't someone will, and will distribute the hacked version. Same applies even if you supply a dongle - if someone wants to, they can patch out the check for that too. Digitally signing your code won't help, they can remove that signature, or resign it.

You can complicate matters a bit by using techniques to prevent the program running in a debugger etc, but even this is not bullet proof. So you should just make it difficult enough that an honest user will not forget to pay. Also be very careful that your scheme does not become obtrusive to paying users - it's better to have some ripped off copies than for your paying customers not to be able to use what they have paid for.

Another option is to have an online check - just provide the user with a unique ID, and check online as to what capabilities that ID should have, and cache it for some period. All the same caveats apply though - people can get round anything like this.

Consider also the support costs of having to deal with users who have forgotten their key, etc.

edit: I just want to add, don't invest too much time in this or think that somehow your convoluted scheme will be different and uncrackable. It won't, and cannot be as long as people control the hardware and OS your program runs on. Developers have been trying to come up with ever more complex schemes for this, thinking that if they develop their own system for it then it will be known only to them and therefore 'more secure'. But it really is the programming equivalent of trying to build a perpetual motion machine. :-)

Python time measure function

Timeit has two big flaws: it doesn't return the return value of the function, and it uses eval, which requires passing in extra setup code for imports. This solves both problems simply and elegantly:

def timed(f):
  start = time.time()
  ret = f()
  elapsed = time.time() - start
  return ret, elapsed

timed(lambda: database.foo.execute('select count(*) from source.apachelog'))
(<sqlalchemy.engine.result.ResultProxy object at 0x7fd6c20fc690>, 4.07547402381897)

How to set top position using jquery

You could also do

   var x = $('#element').height();   // or any changing value

   $('selector').css({'top' : x + 'px'});

OR

You can use directly

$('#element').css( "height" )

The difference between .css( "height" ) and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation. jquery doc

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

See Heroku “psql: FATAL: remaining connection slots are reserved for non-replication superuser connections”:

Heroku sometimes has a problem with database load balancing.

André Laszlo, markshiz and me all reported dealing with that in comments on the question.

To save you the support call, here's the response I got from Heroku Support for a similar issue:

Hello,

One of the limitations of the hobby tier databases is unannounced maintenance. Many hobby databases run on a single shared server, and we will occasionally need to restart that server for hardware maintenance purposes, or migrate databases to another server for load balancing. When that happens, you'll see an error in your logs or have problems connecting. If the server is restarting, it might take 15 minutes or more for the database to come back online.

Most apps that maintain a connection pool (like ActiveRecord in Rails) can just open a new connection to the database. However, in some cases an app won't be able to reconnect. If that happens, you can heroku restart your app to bring it back online.

This is one of the reasons we recommend against running hobby databases for critical production applications. Standard and Premium databases include notifications for downtime events, and are much more performant and stable in general. You can use pg:copy to migrate to a standard or premium plan.

If this continues, you can try provisioning a new database (on a different server) with heroku addons:add, then use pg:copy to move the data. Keep in mind that hobby tier rules apply to the $9 basic plan as well as the free database.

Thanks, Bradley

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

Call this before the query:

set define off;

Alternatively, hacky:

update t set country = 'Trinidad and Tobago' where country = 'trinidad &' || ' tobago';

From Tuning SQL*Plus:

SET DEFINE OFF disables the parsing of commands to replace substitution variables with their values.

Is there a way to ignore a single FindBugs warning?

The FindBugs initial approach involves XML configuration files aka filters. This is really less convenient than the PMD solution but FindBugs works on bytecode, not on the source code, so comments are obviously not an option. Example:

<Match>
   <Class name="com.mycompany.Foo" />
   <Method name="bar" />
   <Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" />
</Match>

However, to solve this issue, FindBugs later introduced another solution based on annotations (see SuppressFBWarnings) that you can use at the class or at the method level (more convenient than XML in my opinion). Example (maybe not the best one but, well, it's just an example):

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value="HE_EQUALS_USE_HASHCODE", 
    justification="I know what I'm doing")

Note that since FindBugs 3.0.0 SuppressWarnings has been deprecated in favor of @SuppressFBWarnings because of the name clash with Java's SuppressWarnings.

How do I set a value in CKEditor with Javascript?

<textarea id="editor1" name="editor1">This is sample text</textarea>

<div id="trackingDiv" ></div>

<script type="text/javascript">
    CKEDITOR.replace( 'editor1' );

</script>

Let try this..

Update :

To set data :

Create instance First::

var editor = CKEDITOR.instances['editor1'];

Then,

editor.setData('your data');

or

editor.insertHtml('your html data');

or

editor.insertText('your text data');  

And Retrieve data from your editor::

editor.getData();

If change the particular para HTML data in CKEditor.

var html = $(editor.editable.$);
$('#id_of_para',html).html('your html data');

These are the possible ways that I know in CKEditor

CSS3 animate border color

If you need the transition to run infinitely, try the below example:

_x000D_
_x000D_
#box {_x000D_
  position: relative;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: gray;_x000D_
  border: 5px solid black;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#box:hover {_x000D_
  border-color: red;_x000D_
  animation-name: flash_border;_x000D_
  animation-duration: 2s;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-name: flash_border;_x000D_
  -webkit-animation-duration: 2s;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
  -moz-animation-name: flash_border;_x000D_
  -moz-animation-duration: 2s;_x000D_
  -moz-animation-timing-function: linear;_x000D_
  -moz-animation-iteration-count: infinite;_x000D_
}_x000D_
_x000D_
@keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-moz-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}
_x000D_
<div id="box">roll over me</div>
_x000D_
_x000D_
_x000D_

How to add header data in XMLHttpRequest when using formdata?

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);

How to create a HTML Table from a PHP array?

I had a similar need, but my array could contain key/value or key/array or array of arrays, like this array:

$array = array(
    "ni" => "00000000000000",
    "situacaoCadastral" => array(
        "codigo" => 2,
        "data" => "0000-00-00",
        "motivo" => "",
    ),
    "naturezaJuridica" => array(
        "codigo" => "0000",
        "descricao" => "Lorem ipsum dolor sit amet, consectetur",
    ),
    "dataAbertura" => "0000-00-00",
    "cnaePrincipal" => array(
        "codigo" => "0000000",
        "descricao" => "Lorem ips",
    ),
    "endereco" => array(
        "tipoLogradouro" => "Lor",
        "logradouro" => "Lorem i",
        "numero" => "0000",
        "complemento" => "",
        "cep" => "00000000",
        "bairro" => "Lorem ",
        "municipio" => array(
            "codigo" => "0000",
            "descricao" => "Lorem ip",
        ),
    ),
    "uf" => "MS",
    "pais" => array(
        "codigo" => "105",
        "descricao" => "BRASIL",
    ),
    "municipioJurisdicao" => array(
        "codigo" => "0000000",
        "descricao" => "DOURADOS",
    ),
    "telefones" => array(
        array(
            'ddd' => '67',
            'numero' => '00000000',
        ),
    ),
    "correioEletronico" => "[email protected]",
    "capitalSocial" => 0,
    "porte" => "00",
    "situacaoEspecial" => "",
    "dataSituacaoEspecial" => ""
);

The function I created to solve was:

function array_to_table($arr, $first=true, $sub_arr=false){
    $width = ($sub_arr) ? 'width="100%"' : '' ;
    $table = ($first) ? '<table align="center" '.$width.' bgcolor="#FFFFFF" border="1px solid">' : '';
    $rows = array();
    foreach ($arr as $key => $value):
        $value_type = gettype($value);
        switch ($value_type) {
            case 'string':
                $val = (in_array($value, array(""))) ? "&nbsp;" : $value;
                $rows[] = "<tr><td><strong>{$key}</strong></td><td>{$val}</td></tr>";
                break;
            case 'integer':
                $val = (in_array($value, array(""))) ? "&nbsp;" : $value;
                $rows[] = "<tr><td><strong>{$key}</strong></td><td>{$value}</td></tr>";
                break;
            case 'array':
                if (gettype($key) == "integer"):
                    $rows[] = array_to_table($value, false);
                elseif(gettype($key) == "string"):
                    $rows[] = "<tr><td><strong>{$key}</strong></td><td>".
                        array_to_table($value, true, true) . "</td>";
                endif;
                break;
            default:
                # code...
                break;
        }
    endforeach;
    $ROWS = implode("\n", $rows);
    $table .= ($first) ? $ROWS . '</table>' : $ROWS;
    return $table;
}

echo array_to_table($array);

And the output is this

How to get the second column from command output?

If you have GNU awk this is the solution you want:

$ awk '{print $1}' FPAT='"[^"]+"' file
"A B"
"C"
"D"

How to align linearlayout to vertical center?

use RelativeLayout inside LinearLayout

example:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:text="Status"/>
        </RelativeLayout>
</LinearLayout>

Center align a column in twitter bootstrap

With bootstrap 3 the best way to go about achieving what you want is ...with offsetting columns. Please see these examples for more detail:
http://getbootstrap.com/css/#grid-offsetting

In short, and without seeing your divs here's an example what might help, without using any custom classes. Just note how the "col-6" is used and how half of that is 3 ...so the "offset-3" is used. Splitting equally will allow the centered spacing you're going for:

<div class="container">
<div class="col-sm-6 col-sm-offset-3">
your centered, floating column
</div></div>

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe.

  1. A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.
  2. In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.
    • Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.
  3. The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226).
  4. Windows 10 is the only OS that ships the UCRT in-box. All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista->8.1 and associated Server SKUs.

For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.

Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime?

The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state:

  1. If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being “Not Applicable”. Ensure KB2919355 is installed. Also, there were known issues with KB2919355 so before this the following hotfix should be installed. KB2939087 KB2975061
  2. If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy.
    • This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds).
  3. If the Windows Update service is in a non-ready state, you can see errors reflecting that.

    • We recently investigated a failure with an error code indicating the WUSA service was shutting down.
  4. To identify if the prerequisite KB2919355 is installed there are 2 options:

    1. Registry key: 64bit hive

      HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14
      CurrentState = 112
      

      32bit hive

      HKLM\SOFTWARE\[WOW6432Node\]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14
      CurrentState = 112
      
    2. Or check the file version of:

      C:\Windows\SysWOW64\wuaueng.dll
      C:\Windows\System32\wuaueng.dll
      

      is 7.9.9600.17031 or later

Include PHP inside JavaScript (.js) files

PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.

Proper use of mutexes in Python

This is the solution I came up with:

import time
from threading import Thread
from threading import Lock

def myfunc(i, mutex):
    mutex.acquire(1)
    time.sleep(1)
    print "Thread: %d" %i
    mutex.release()


mutex = Lock()
for i in range(0,10):
    t = Thread(target=myfunc, args=(i,mutex))
    t.start()
    print "main loop %d" %i

Output:

main loop 0
main loop 1
main loop 2
main loop 3
main loop 4
main loop 5
main loop 6
main loop 7
main loop 8
main loop 9
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9

How to cache Google map tiles for offline usage?

update:

I found the terms of use from Google Map:

Section 10.5

No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you may store limited amounts of Content solely for the purpose of improving the performance of your Maps API Implementation due to network latency (and not for the purpose of preventing Google from accurately tracking usage), and only if such storage: is temporary (and in no event more than 30 calendar days); is secure; does not manipulate or aggregate any part of the Content or Service; and does not modify attribution in any way.

It means we can cache for limited time actually

Tensorflow installation error: not a supported wheel on this platform

On Windows 10, with Python 3.6.X version I was facing same then after checking deliberately , I noticed I had Python-32 bit installation on my 64 bit machine. Remember TensorFlow is only compatible with 64bit installation of python. Not 32 bit of Python

installation requirements

If we download Python from python.org , the default installation would be 32 bit. So we have to download 64 bit installer manually to install Python 64 bit. And then add

  1. C:\Users\\AppData\Local\Programs\Python\Python36
  2. C:\Users\\AppData\Local\Programs\Python\Python36\Scripts

Then run gpupdate /Force on command prompt. If python command doesnt work for 64 bit restart your machine.

Then run python on command prompt. It should show 64 bit

C:\Users\YOURNAME>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

Then run below command to install tensorflow CPU version(recommended)

pip3 install --upgrade tensorflow

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

this is a version problem change version > 2.4 to 1.9 solve it

<dependency>  
<groupId>com.fasterxml.jackson.jaxrs</groupId>  
<artifactId>jackson-jaxrs-xml-provider</artifactId>  
<version>2.4.1</version>  

to

<dependency>  
<groupId>org.codehaus.jackson</groupId>  
<artifactId>jackson-mapper-asl</artifactId>  
<version>1.9.4</version>  

Swift: Reload a View Controller

If you need to update the canvas by redrawing views after some change, you should call setNeedsDisplay.

Thank you @Vincent from an earlier comment.enter image description here

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:

select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from 
CSPGI09_OVERSHIPMENT 

Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

Tomcat Servlet: Error 404 - The requested resource is not available

this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.

Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output

CSS3 :unchecked pseudo-class

I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.

input[type="checkbox"] {
  // Unchecked Styles
}
input[type="checkbox"]:checked {
  // Checked Styles
}

I apologize for bringing up an old thread but felt like it could have used a better answer.

EDIT (3/3/2016):

W3C Specs state that :not(:checked) as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"] selector. See example below for clarification.

input[type="checkbox"] {
  /* Base Styles aka unchecked */
  font-weight: 300; // Will be overwritten by :checked
  font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
  /* Explicit Unchecked Styles */
  border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
  /* Checked Styles */
  font-weight: 900; // Use a bold font when checked
}

Without using :not(:checked) in the example above the :checked selector would have needed to use a border: none; to achieve the same affect.

Use the input[type="checkbox"] for base styling to reduce duplication.

Use the input[type="checkbox"]:not(:checked) for explicit unchecked styles that you do not want to apply to the checked state.

Matrix multiplication using arrays

import java.util.*; public class Mult {

public static int[][] C;

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);

    System.out.println("Enter Row of Matrix A");
    int Rowa = s.nextInt();

    System.out.println("Enter Column of Matrix A");
    int Cola = s.nextInt();

    System.out.println("Enter Row of Matrix B");
    int Rowb = s.nextInt();

    System.out.println("Enter Column of Matrix B");
    int Colb = s.nextInt();

    int[][] A = new int[Rowa][Cola];
    int[][] B = new int[Rowb][Colb];

    C= new int[Rowa][Colb];
    //int[][] C = new int;
    System.out.println("Enter Values of Matrix A");

    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
            A[i][j] = s.nextInt();
        }

    }

    System.out.println("Enter Values of Matrix B");

    for(int i =0 ; i< B.length ; i++) {
        for(int j = 0 ; j<B.length;j++) {
            B[i][j] = s.nextInt();
        }
    }




    if(Cola==Rowb) {
        for(int i = 0;i < A.length;i++){
              for(int j = 0;j < A.length;j++){
                 C[i][j]=0;
                 for(int k = 0;k < B.length;k++){
                    C[i][j] += A[i][k] * B[k][j];
                 }
              }
           }
    }
    else {
        System.out.println("Cannot multiply");
    }









    // Printing matrix A
    /*
    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
        System.out.print(A[i][j]+ "\t");
        }
        System.out.println();
    }
    */

    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
        System.out.print(C[i][j]+ "\t");
        }
        System.out.println();
    }

}

}

Difficulty with ng-model, ng-repeat, and inputs

I tried the solution above for my problem at it worked like a charm. Thanks!

http://jsfiddle.net/leighboone/wn9Ym/7/

Here is my version of that:

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
    $scope.models = [{
        name: 'Device1',
        checked: true
    }, {
        name: 'Device1',
        checked: true
    }, {
        name: 'Device1',
        checked: true
    }];

}

and my HTML

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
         <h1>Fun with Fields and ngModel</h1>
        <p>names: {{models}}</p>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th></th>
                    <th>Feature 1</td>
                    <th>Feature 2</th>
                    <th>Feature 3</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Device</td>
                   <td ng-repeat="modelCheck in models" class=""> <span>
                                    {{modelCheck.checked}}
                                </span>

                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Which devices?</label>
                    </td>
                    <td ng-repeat="model in models">{{model.name}}
                        <input type="checkbox" class="checkbox inline" ng-model="model.checked" />
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

How to execute an .SQL script file using c#

I tried this solution with Microsoft.SqlServer.Management but it didn't work well with .NET 4.0 so I wrote another solution using .NET libs framework only.

string script = File.ReadAllText(@"E:\someSqlScript.sql");

// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

Connection.Open();
foreach (string commandString in commandStrings)
{
    if (!string.IsNullOrWhiteSpace(commandString.Trim()))
    {
        using(var command = new SqlCommand(commandString, Connection))
        {
            command.ExecuteNonQuery();
        }
    }
}     
Connection.Close();

SQL to LINQ Tool

I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).

When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.

It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

How to set cellpadding and cellspacing in table with CSS?

Use padding on the cells and border-spacing on the table. The former will give you cellpadding while the latter will give you cellspacing.

table { border-spacing: 5px; } /* cellspacing */

th, td { padding: 5px; } /* cellpadding */

jsFiddle Demo

Print directly from browser without print popup window

This should work, I tried it by myself and it worked for me. If you pass True instead of false, the print dialog will appear.

this.print(false);

Increasing the maximum post size

We can Increasing the maximum limit using .htaccess file.

php_value session.gc_maxlifetime 10800
php_value max_input_time         10800
php_value max_execution_time     10800
php_value upload_max_filesize    110M
php_value post_max_size          120M

If sometimes other way are not working, this way is working perfect.

error_reporting(E_ALL) does not produce error

In your php.ini file check for display_errors. If it is off, then make it on as below:

display_errors = On

It should display warnings/notices/errors .

Please read this

http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

You can try:

Open sql file by text editor find and replace all

utf8mb4 to utf8

Import again.

How should I unit test multithreaded code?

I have had the unfortunate task of testing threaded code and they are definitely the hardest tests I have ever written.

When writing my tests, I used a combination of delegates and events. Basically it is all about using PropertyNotifyChanged events with a WaitCallback or some kind of ConditionalWaiter that polls.

I am not sure if this was the best approach, but it has worked out for me.

Merge development branch with master

1. //push the latest changes of current development branch if any        
git push (current development branch)

2. //switch to master branch
git checkout master 

3. //pull all the changes if any from (current development branch)
git pull origin (current development branch)

4. //Now merge development into master    
git merge development

5. //push the master branch
git push origin master

Error
To https://github.com/rajputankit22/todos-posts.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/rajputankit22/todos-posts.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Then Use 
5. //push the master branch forcefully
git push -f origin master

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

Best Practices for securing a REST API / web service

Thanks for the excellent advice. We ended up using a custom HTTP header to pass an identity token from the client to the service, in preparation for integrating our RESTful API with the the upcoming Zermatt Identity framework from Microsoft. I have described the problem here and our solution here. I also took tweakt's advice and bought RESTful Web Services - a very good book if you're building a RESTful API of any kind.

Selecting the last value of a column

I'm surprised no one had ever given this answer before. But this should be the shortest and it even works in excel :

=ARRAYFORMULA(LOOKUP(2,1/(G2:G<>""),G2:G))

G2:G<>"" creates a array of 1/true(1) and 1/false(0). Since LOOKUP does a top down approach to find 2 and Since it'll never find 2,it comes up to the last non blank row and gives the position of that.

The other way to do this, as others might've mentioned, is:

=INDEX(G2:G,MAX((ISBLANK(G2:G)-1)*-ROW(G2:G))-1)

Finding the MAXimum ROW of the non blank row and feeding it to INDEX

In a zero blank interruption array, Using INDIRECT RC notation with COUNTBLANK is another option. If V4:V6 is occupied with entries, then,

V18:

=INDIRECT("R[-"&COUNTBLANK(V4:V17)+1&"]C",0)

will give the position of V6.

Send form data using ajax

I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
Following part of the function might be of interest:

  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
        continue; 
      //Add & to any subsequent entries (that means every iteration except the first one) 
      if(data_string.length>0)
        data_string+="&";
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
      {
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      }
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
      {
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      }
      //Get data from textfield
      else
      {
        data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
      }
    }
    return data_string; 
  }

It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.

Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:

function ajax_create_request_string(data, recursion) {
  var data_string = '';
  //Zpracovani formulare
  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
        continue; 
      //Add & to any subsequent entries (that means every iteration except the first one) 
      if(data_string.length>0)
        data_string+="&";
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
      {
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      }
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
      {
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      }
      //Get data from textfield
      else
      {
        if(elem[i].className.indexOf("autoempty")!=-1) {
          data_string += elem[i].name+"=";
        }
        else
          data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
      }
    }
    return data_string; 
  }
  //Loop through array
  if(data instanceof Array) {
    for(var i=0; i<data.length; i++) {
      if(data_string!="")
        data_string+="&";
      data_string+=recursion+"["+i+"]="+data[i];
    }
    return data_string;
  }
  //Loop through object (like foreach)
  for(var i in data) {
    if(data_string!="")
      data_string+="&";
    if(typeof data[i]=="object") {
      if(recursion==null)
        data_string+= ajax_create_request_string(data[i], i);
      else
        data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
    }
    else if(recursion==null)
      data_string+=i+"="+data[i];
    else 
      data_string+=recursion+"["+i+"]="+data[i];
  }
  return data_string;
}

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Can I get all methods of a class?

To know about all methods use this statement in console:

javap -cp jar-file.jar packagename.classname

or

javap class-file.class packagename.classname

or for example:

javap java.lang.StringBuffer

sqlite3.OperationalError: unable to open database file

For any one who has a problem with airflow linked to this issue.

In my case, I've initialized airflow in /root/airflow and run its scheduler as root. I used the run_as_user parameter to impersonate the web user while running task instances. However airflow was always failing to trigger my DAG with the following errors in logs:

sqlite3.OperationalError: unable to open database file
...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file

I also found once I triggered a DAG manually, a new airflow resource directory was automatically created under /home/web. I'm not clear about this behavior, but I make it work by removing the entire airflow resources from /root, reinitializing airflow database under /home/web and running the scheduler as web under:

[root@host ~]# rm -rf airflow
[web@host ~]$ airflow initdb
[web@host ~]$ airflow scheduler -D

If you want to try this approach, I may need to backup your data before doing anything.

What is the difference between dynamic and static polymorphism in Java?

Binding refers to the link between method call and method definition.

This picture clearly shows what is binding.

binding

In this picture, “a1.methodOne()” call is binding to corresponding methodOne() definition and “a1.methodTwo()” call is binding to corresponding methodTwo() definition.

For every method call there should be proper method definition. This is a rule in java. If compiler does not see the proper method definition for every method call, it throws error.

Now, come to static binding and dynamic binding in java.

Static Binding In Java :

Static binding is a binding which happens during compilation. It is also called early binding because binding happens before a program actually runs

.

Static binding can be demonstrated like in the below picture.

enter image description here

In this picture, ‘a1’ is a reference variable of type Class A pointing to object of class A. ‘a2’ is also reference variable of type class A but pointing to object of Class B.

During compilation, while binding, compiler does not check the type of object to which a particular reference variable is pointing. It just checks the type of reference variable through which a method is called and checks whether there exist a method definition for it in that type.

For example, for “a1.method()” method call in the above picture, compiler checks whether there exist method definition for method() in Class A. Because ‘a1' is Class A type. Similarly, for “a2.method()” method call, it checks whether there exist method definition for method() in Class A. Because ‘a2' is also Class A type. It does not check to which object, ‘a1’ and ‘a2’ are pointing. This type of binding is called static binding.

Dynamic Binding In Java :

Dynamic binding is a binding which happens during run time. It is also called late binding because binding happens when program actually is running.

During run time actual objects are used for binding. For example, for “a1.method()” call in the above picture, method() of actual object to which ‘a1’ is pointing will be called. For “a2.method()” call, method() of actual object to which ‘a2’ is pointing will be called. This type of binding is called dynamic binding.

The dynamic binding of above example can be demonstrated like below.

enter image description here

Reference static-binding-and-dynamic-binding-in-java

View list of all JavaScript variables in Google Chrome Console

The window object contains all the public variables, so you can type it in the console and then expand to view all variables/attributes/functions.

chrome-show-all-variables-expand-window-object

How do I get the last day of a month?

You can find the last date of any month by this code:

var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month);
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth);

Winforms TableLayoutPanel adding rows programmatically

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dt As New DataTable
        Dim dc As DataColumn
        dc = New DataColumn("Question", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)

        dc = New DataColumn("Ans1", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans2", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans3", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans4", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("AnsType", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)


        Dim Dr As DataRow
        Dr = dt.NewRow
        Dr("Question") = "What is Your Name"
        Dr("Ans1") = "Ravi"
        Dr("Ans2") = "Mohan"
        Dr("Ans3") = "Sohan"
        Dr("Ans4") = "Gopal"
        Dr("AnsType") = "Multi"
        dt.Rows.Add(Dr)

        Dr = dt.NewRow
        Dr("Question") = "What is your father Name"
        Dr("Ans1") = "Ravi22"
        Dr("Ans2") = "Mohan2"
        Dr("Ans3") = "Sohan2"
        Dr("Ans4") = "Gopal2"
        Dr("AnsType") = "Multi"
        dt.Rows.Add(Dr)
        Panel1.GrowStyle = TableLayoutPanelGrowStyle.AddRows
        Panel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
        Panel1.BackColor = Color.Azure
        Panel1.RowStyles.Insert(0, New RowStyle(SizeType.Absolute, 50))
        Dim i As Integer = 0

        For Each dri As DataRow In dt.Rows



            Dim lab As New Label()
            lab.Text = dri("Question")
            lab.AutoSize = True

            Panel1.Controls.Add(lab, 0, i)


            Dim Ans1 As CheckBox
            Ans1 = New CheckBox()
            Ans1.Text = dri("Ans1")
            Panel1.Controls.Add(Ans1, 1, i)

            Dim Ans2 As RadioButton
            Ans2 = New RadioButton()
            Ans2.Text = dri("Ans2")
            Panel1.Controls.Add(Ans2, 2, i)
            i = i + 1

            'Panel1.Controls.Add(Pan)
        Next

SSL Proxy/Charles and Android trouble

The top rated answers are working perfect (a bit old but still working), but I just want to mention that since Android N we all can configure your apps in order to have diff trust SSL certificates (for release , debug only and so on), including Charles SSL Proxy certificate (if you download the Charles certificate and put .pem file in your raw folder). More info can be found here: https://developer.android.com/training/articles/security-config.html

Also the official Charles documentation can be useful to setup this : https://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

Hope this will help to setup Charles inside your app project not on every single Android device.

How can I control Chromedriver open window size?

C# version of @yonatan-kiron's answer, and Selenium's using statement from their example code.

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--window-size=1300,1000");

using (IWebDriver driver = new ChromeDriver(chromeOptions))
{
    ...
}

How to add many functions in ONE ng-click?

You have 2 options :

  1. Create a third method that wrap both methods. Advantage here is that you put less logic in your template.

  2. Otherwise if you want to add 2 calls in ng-click you can add ';' after edit($index) like this

    ng-click="edit($index); open()"

See here : http://jsfiddle.net/laguiz/ehTy6/

Escape quotes in JavaScript

Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.

In order to escape single quotes, just enter a backward slash followed by a single quote like: \’ as part of the string. I used jQuery validator for this example, and you can use as per your convenience.

Valid String Examples:

'Hello'

'Hello', 'World'

'Hello','World'

'Hello','World',' '

'It\'s my world', 'Can\'t enjoy this without me.', 'Welcome, Guest'

HTML:

<tr>
    <td>
        <label class="control-label">
            String Field:
        </label>
        <div class="inner-addon right-addon">
            <input type="text" id="stringField"
                   name="stringField"
                   class="form-control"
                   autocomplete="off"
                   data-rule-required="true"
                   data-msg-required="Cannot be blank."
                   data-rule-commaSeparatedText="true"
                   data-msg-commaSeparatedText="Invalid comma separated value(s).">
        </div>
    </td>

JavaScript:

     /**
 *
 * @param {type} param1
 * @param {type} param2
 * @param {type} param3
 */
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {

    if (value.length === 0) {
        return true;
    }
    var expression = new RegExp("^((')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))(((,)|(,\\s))(')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))*$");
    return expression.test(value);
}, 'Invalid comma separated string values.');

PHP fopen() Error: failed to open stream: Permission denied

You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:

sudo chmod 777 markers.xml

You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.

Android app unable to start activity componentinfo

The question is answered already, but I want add more information about the causes.

Android app unable to start activity componentinfo

This error often comes with appropriate logs. You can read logs and can solve this issue easily.

Here is a sample log. In which you can see clearly ClassCastException. So this issue came because TextView cannot be cast to EditText.

Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050):     ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109):     ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167):     ... 11 more

Some Common Mistakes.

1.findViewById() of non existing view

Like when you use findViewById(R.id.button) when button id does not exist in layout XML.

2. Wrong cast.

If you wrong cast some class, then you get this error. Like you cast RelativeLayout to LinearLayout or EditText to TextView.

3. Activity not registered in manifest.xml

If you did not register Activity in manifest.xml then this error comes.

4. findViewById() with declaration at top level

Below code is incorrect. This will create error. Because you should do findViewById() after calling setContentView(). Because an View can be there after it is created.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
    //...
  }
}

5. Starting abstract Activity class.

When you try to start an Activity which is abstract, you will will get this error. So just remove abstract keyword before activity class name.

6. Using kotlin but kotlin not configured.

If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.

More information

Read about Downcast and Upcast

Read about findViewById() method of Activity class

Super keyword in Java

How to register activity in manifest

How to change font in ipython notebook

There is a much easier way to do without adding the CSS files and all the other methods suggested. But you have to do it every time you start the Jupiter notebook.

Go to inspect in your browser and click on the element selection icon and then click on the box. And at the bottom of the page, you will be seeing the styling option for CSS where you can easily change the font-size.

enter image description here

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):

CREATE OR REPLACE FUNCTION get_allitems
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems;
  RETURN my_cursor;
END get_allitems;

This will return the cursor.

Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.


If you really need to use dynamic SQL you can put your query in single quotes:

  OPEN my_cursor FOR 'SELECT * FROM allitems';

This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.

Make sure to use bind-variables where possible to avoid hard parses:

  OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;

Git merge develop into feature branch outputs "Already up-to-date" while it's not

Step by step self explaining commands for update of feature branch with the latest code from origin "develop" branch:

git checkout develop
git pull -p
git checkout feature_branch
git merge develop
git push origin feature_branch

Remove non-utf8 characters from string

try this:

$string = iconv("UTF-8","UTF-8//IGNORE",$string);

According to the iconv manual, the function will take the first parameter as the input charset, second parameter as the output charset, and the third as the actual input string.

If you set both the input and output charset to UTF-8, and append the //IGNORE flag to the output charset, the function will drop(strip) all characters in the input string that can't be represented by the output charset. Thus, filtering the input string in effect.

IPC performance: Named Pipe vs Socket

I would suggest you take the easy path first, carefully isolating the IPC mechanism so that you can change from socket to pipe, but I would definitely go with socket first. You should be sure IPC performance is a problem before preemptively optimizing.

And if you get in trouble because of IPC speed, I think you should consider switching to shared memory rather than going to pipe.

If you want to do some transfer speed testing, you should try socat, which is a very versatile program that allows you to create almost any kind of tunnel.

Java : Accessing a class within a package, which is the better way?

They're equivalent. The access is the same.

The import is just a convention to save you from having to type the fully-resolved class name each time. You can write all your Java without using import, as long as you're a fast touch typer.

But there's no difference in efficiency or class loading.

Encode/Decode URLs in C++

I ended up on this question when searching for an api to decode url in a win32 c++ app. Since the question doesn't quite specify platform assuming windows isn't a bad thing.

InternetCanonicalizeUrl is the API for windows programs. More info here

        LPTSTR lpOutputBuffer = new TCHAR[1];
        DWORD dwSize = 1;
        BOOL fRes = ::InternetCanonicalizeUrl(strUrl, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);
        DWORD dwError = ::GetLastError();
        if (!fRes && dwError == ERROR_INSUFFICIENT_BUFFER)
        {
            delete lpOutputBuffer;
            lpOutputBuffer = new TCHAR[dwSize];
            fRes = ::InternetCanonicalizeUrl(strUrl, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);
            if (fRes)
            {
                //lpOutputBuffer has decoded url
            }
            else
            {
                //failed to decode
            }
            if (lpOutputBuffer !=NULL)
            {
                delete [] lpOutputBuffer;
                lpOutputBuffer = NULL;
            }
        }
        else
        {
            //some other error OR the input string url is just 1 char and was successfully decoded
        }

InternetCrackUrl (here) also seems to have flags to specify whether to decode url

How to create a thread?

Your example fails because Thread methods take either one or zero arguments. To create a thread without passing arguments, your code looks like this:

void Start()
{
    // do stuff
}

void Test()
{
    new Thread(new ThreadStart(Start)).Start();
}

If you want to pass data to the thread, you need to encapsulate your data into a single object, whether that is a custom class of your own design, or a dictionary object or something else. You then need to use the ParameterizedThreadStart delegate, like so:

void Start(object data)
{
    MyClass myData = (MyClass)myData;
    // do stuff
}

void Test(MyClass data)
{
    new Thread(new ParameterizedThreadStart(Start)).Start(data);
}

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

How to obtain the start time and end time of a day?

I think the easiest would be something like:

// Joda Time

DateTime dateTime=new DateTime(); 

StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();

These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.

Replace HTML Table with Divs

I looked all over for an easy solution and found this code that worked for me. The right div is a third column which I left in for readability sake.

Here is the HTML:

<div class="container">
  <div class="row">
    <div class="left">
      <p>PHONE & FAX:</p>
    </div>
    <div class="middle">
      <p>+43 99 554 28 53</p>
    </div>
    <div class="right"> </div>
  </div>
  <div class="row">
    <div class="left">
      <p>Cellphone Gert:</p>
    </div>
    <div class="middle">
      <p>+43 99 302 52 32</p>
    </div>
    <div class="right"> </div>
  </div>
  <div class="row">
    <div class="left">
      <p>Cellphone Petra:</p>
    </div>
    <div class="middle">
      <p>+43 99 739 38 84</p>
    </div>
    <div class="right"> </div>
  </div>
</div>

And the CSS:

.container {
    display: table;
    }
.row  {
    display: table-row;
    }
.left, .right, .middle {
    display: table-cell;
    padding-right: 25px;
    }
.left p, .right p, .middle p {
    margin: 1px 1px;
   }

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

I had the same question. This should work for you:

s.nextLine();