Programs & Examples On #Dynamic rdlc generation

Use this tag for questions about the dynamic generation of the Client Report Definition Language file

Update statement with inner join on Oracle

MERGE with WHERE clause:

MERGE into table1
USING table2
ON (table1.id = table2.id)
WHEN MATCHED THEN UPDATE SET table1.startdate = table2.start_date
WHERE table1.startdate > table2.start_date;

You need the WHERE clause because columns referenced in the ON clause cannot be updated.

Asking the user for input until they give a valid response

The simplest way to accomplish this is to put the input method in a while loop. Use continue when you get bad input, and break out of the loop when you're satisfied.

When Your Input Might Raise an Exception

Use try and except to detect when the user enters data that can't be parsed.

while True:
    try:
        # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        #better try again... Return to the start of the loop
        continue
    else:
        #age was successfully parsed!
        #we're ready to exit the loop.
        break
if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

Implementing Your Own Validation Rules

If you want to reject values that Python can successfully parse, you can add your own validation logic.

while True:
    data = input("Please enter a loud message (must be all caps): ")
    if not data.isupper():
        print("Sorry, your response was not loud enough.")
        continue
    else:
        #we're happy with the value given.
        #we're ready to exit the loop.
        break

while True:
    data = input("Pick an answer from A to D:")
    if data.lower() not in ('a', 'b', 'c', 'd'):
        print("Not an appropriate choice.")
    else:
        break

Combining Exception Handling and Custom Validation

Both of the above techniques can be combined into one loop.

while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue

    if age < 0:
        print("Sorry, your response must not be negative.")
        continue
    else:
        #age was successfully parsed, and we're happy with its value.
        #we're ready to exit the loop.
        break
if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

Encapsulating it All in a Function

If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don't have to retype it every time.

def get_non_negative_int(prompt):
    while True:
        try:
            value = int(input(prompt))
        except ValueError:
            print("Sorry, I didn't understand that.")
            continue

        if value < 0:
            print("Sorry, your response must not be negative.")
            continue
        else:
            break
    return value

age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")

Putting It All Together

You can extend this idea to make a very generic input function:

def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
    if min_ is not None and max_ is not None and max_ < min_:
        raise ValueError("min_ must be less than or equal to max_.")
    while True:
        ui = input(prompt)
        if type_ is not None:
            try:
                ui = type_(ui)
            except ValueError:
                print("Input type must be {0}.".format(type_.__name__))
                continue
        if max_ is not None and ui > max_:
            print("Input must be less than or equal to {0}.".format(max_))
        elif min_ is not None and ui < min_:
            print("Input must be greater than or equal to {0}.".format(min_))
        elif range_ is not None and ui not in range_:
            if isinstance(range_, range):
                template = "Input must be between {0.start} and {0.stop}."
                print(template.format(range_))
            else:
                template = "Input must be {0}."
                if len(range_) == 1:
                    print(template.format(*range_))
                else:
                    expected = " or ".join((
                        ", ".join(str(x) for x in range_[:-1]),
                        str(range_[-1])
                    ))
                    print(template.format(expected))
        else:
            return ui

With usage such as:

age = sanitised_input("Enter your age: ", int, 1, 101)
answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))

Common Pitfalls, and Why you Should Avoid Them

The Redundant Use of Redundant input Statements

This method works but is generally considered poor style:

data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
    print("Sorry, your response was not loud enough.")
    data = input("Please enter a loud message (must be all caps): ")

It might look attractive initially because it's shorter than the while True method, but it violates the Don't Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input to raw_input, but accidentally change only the first input above? It's a SyntaxError just waiting to happen.

Recursion Will Blow Your Stack

If you've just learned about recursion, you might be tempted to use it in get_non_negative_int so you can dispose of the while loop.

def get_non_negative_int(prompt):
    try:
        value = int(input(prompt))
    except ValueError:
        print("Sorry, I didn't understand that.")
        return get_non_negative_int(prompt)

    if value < 0:
        print("Sorry, your response must not be negative.")
        return get_non_negative_int(prompt)
    else:
        return value

This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded. You may think "no fool would make 1000 mistakes in a row", but you're underestimating the ingenuity of fools!

How to bind a List to a ComboBox?

Try something like this:

yourControl.DataSource = countryInstance.Cities;

And if you are using WebForms you will need to add this line:

yourControl.DataBind();

Pass a local file in to URL in Java

I tried it with Java on Linux. The following possibilities are OK:

file:///home/userId/aaaa.html
file:/home/userId/aaaa.html
file:aaaa.html  (if current directory is /home/userId)

not working is:

file://aaaa.html

CodeIgniter: Load controller within controller

Just use

..............

self::index();

..............

Global Git ignore

To create global gitignore from scratch:

$ cd ~
$ touch .gitignore_global
$ git config --global core.excludesfile ~/.gitignore_global
  1. First line changes directory to C:/Users/User
  2. After that you create an empty file with .gitignore_global extension
  3. And finally setting global ignore to that file.
  4. Then you should open it with some kind of notepad and add the needed ignore rules.

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a js.map file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files. https://github.com/gruntjs/grunt-contrib-uglify/issues/71

I hope this makes sense.

jQuery: selecting each td in a tr

You can simply do the following inside your TR loop:

$(this).find('td').each (function() {
  // do your cool stuff
});                          

ClassNotFoundException com.mysql.jdbc.Driver

If you're facing this problem with Eclipse, I've been following many different solutions but the one that worked for me is this:

  1. Right click your project folder and open up Properties.

  2. From the right panel, select Java Build Path then go to Libraries tab.

  3. Select Add External JARs to import the mysql driver.

  4. From the right panel, select Deployment Assembly.

  5. Select Add..., then select Java Build Path Entries and click Next.

  6. You should see the sql driver on the list. Select it and click first.

And that's it! Try to run it again! Cheers!

How to connect to LocalDB in Visual Studio Server Explorer?

The following works with Visual Studio 2017 Community Edition on Windows 10 using SQLServer Express 2016.

Open a PowerShell check what it is called using SqlLocalDB.exe info and whether it is Running with SqlLocalDB.exe info NAME. Here's what it looks like on my machine:

> SqlLocalDB.exe info
MSSQLLocalDB
> SqlLocalDB.exe info MSSQLLocalDB
Name:               mssqllocaldb
Version:            13.0.1601.5
Shared name:
Owner:              DESKTOP-I4H3E09\simon
Auto-create:        Yes
State:              Running
Last start time:    4/12/2017 8:24:36 AM
Instance pipe name: np:\\.\pipe\LOCALDB#EFC58609\tsql\query
>

If it isn't running then you need to start it with SqlLocalDB.exe start MSSQLLocalDB. When it is running you see the Instance pipe name: which starts with np:\\. Copy that named pipe string. Within VS2017 open the view Server Explorer and create a new connection of type Microsoft SQL Server (SqlClient) (don't be fooled by the other file types you want the full fat connection type) and set the Server name: to be the instance pipe name you copied from PowerShell.

I also set the Connect to database to be the same database that was in the connection string that was working in my Dotnet Core / Entity Framework Core project which was set up using dotnet ef database update.

You can login and create a database using the sqlcmd and the named pipe string:

sqlcmd -S np:\\.\pipe\LOCALDB#EFC58609\tsql\query 1> create database EFGetStarted.ConsoleApp.NewDb; 2> GO

There are instructions on how to create a user for your application at https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility

Notice: Array to string conversion in

The problem is that $money is an array and you are treating it like a string or a variable which can be easily converted to string. You should say something like:

 '.... Money:'.$money['money']

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

This seems a little more elegant

'populate DT from .csv file

 Dim items = (From line In IO.File.ReadAllLines("C:YourData.csv") _
 Select Array.ConvertAll(line.Split(","c), Function(v) _ 
 v.ToString.TrimStart(""" ".ToCharArray).TrimEnd(""" ".ToCharArray))).ToArray

Dim Your_DT As New DataTable
For x As Integer = 0 To items(0).GetUpperBound(0)
Your_DT.Columns.Add()
Next

For Each a In items
Dim dr As DataRow = Your_DT.NewRow
dr.ItemArray = a
Your_DT.Rows.Add(dr)
Next

Your_DataGrid.DataSource = Your_DT           

Default parameters with C++ constructors

If creating constructors with arguments is bad (as many would argue), then making them with default arguments is even worse. I've recently started to come around to the opinion that ctor arguments are bad, because your ctor logic should be as minimal as possible. How do you deal with error handling in the ctor, should somebody pass in an argument that doesn't make any sense? You can either throw an exception, which is bad news unless all of your callers are prepared to wrap any "new" calls inside of try blocks, or setting some "is-initialized" member variable, which is kind of a dirty hack.

Therefore, the only way to make sure that the arguments passed into the initialization stage of your object is to set up a separate initialize() method where you can check the return code.

The use of default arguments is bad for two reasons; first of all, if you want to add another argument to the ctor, then you are stuck putting it at the beginning and changing the entire API. Furthermore, most programmers are accustomed to figuring out an API by the way that it's used in practice -- this is especially true for non-public API's used inside of an organization where formal documentation may not exist. When other programmers see that the majority of the calls don't contain any arguments, they will do the same, remaining blissfully unaware of the default behavior your default arguments impose on them.

Also, it's worth noting that the google C++ style guide shuns both ctor arguments (unless absolutely necessary), and default arguments to functions or methods.

Initializing multiple variables to the same value in Java

Way too late to this but the simplest way I've found is:

String foo = bar = baz = "hello"
println(foo)
println(bar)
println(baz)

Output:

hello
hello
hello

How do I capture SIGINT in Python?

You can handle CTRL+C by catching the KeyboardInterrupt exception. You can implement any clean-up code in the exception handler.

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Read a text file using Node.js?

You'll want to use the process.argv array to access the command-line arguments to get the filename and the FileSystem module (fs) to read the file. For example:

// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
  console.log('Usage: node ' + process.argv[1] + ' FILENAME');
  process.exit(1);
}
// Read the file and print its contents.
var fs = require('fs')
  , filename = process.argv[2];
fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err;
  console.log('OK: ' + filename);
  console.log(data)
});

To break that down a little for you process.argv will usually have length two, the zeroth item being the "node" interpreter and the first being the script that node is currently running, items after that were passed on the command line. Once you've pulled a filename from argv then you can use the filesystem functions to read the file and do whatever you want with its contents. Sample usage would look like this:

$ node ./cat.js file.txt
OK: file.txt
This is file.txt!

[Edit] As @wtfcoder mentions, using the "fs.readFile()" method might not be the best idea because it will buffer the entire contents of the file before yielding it to the callback function. This buffering could potentially use lots of memory but, more importantly, it does not take advantage of one of the core features of node.js - asynchronous, evented I/O.

The "node" way to process a large file (or any file, really) would be to use fs.read() and process each available chunk as it is available from the operating system. However, reading the file as such requires you to do your own (possibly) incremental parsing/processing of the file and some amount of buffering might be inevitable.

How does PHP 'foreach' actually work?

Great question, because many developers, even experienced ones, are confused by the way PHP handles arrays in foreach loops. In the standard foreach loop, PHP makes a copy of the array that is used in the loop. The copy is discarded immediately after the loop finishes. This is transparent in the operation of a simple foreach loop. For example:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    echo "{$item}\n";
}

This outputs:

apple
banana
coconut

So the copy is created but the developer doesn't notice, because the original array isn’t referenced within the loop or after the loop finishes. However, when you attempt to modify the items in a loop, you find that they are unmodified when you finish:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $item = strrev ($item);
}

print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
)

Any changes from the original can't be notices, actually there are no changes from the original, even though you clearly assigned a value to $item. This is because you are operating on $item as it appears in the copy of $set being worked on. You can override this by grabbing $item by reference, like so:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $item = strrev($item);
}
print_r($set);

This outputs:

Array
(
    [0] => elppa
    [1] => ananab
    [2] => tunococ
)

So it is evident and observable, when $item is operated on by-reference, the changes made to $item are made to the members of the original $set. Using $item by reference also prevents PHP from creating the array copy. To test this, first we’ll show a quick script demonstrating the copy:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $set[] = ucfirst($item);
}
print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [3] => Apple
    [4] => Banana
    [5] => Coconut
)

As it is shown in the example, PHP copied $set and used it to loop over, but when $set was used inside the loop, PHP added the variables to the original array, not the copied array. Basically, PHP is only using the copied array for the execution of the loop and the assignment of $item. Because of this, the loop above only executes 3 times, and each time it appends another value to the end of the original $set, leaving the original $set with 6 elements, but never entering an infinite loop.

However, what if we had used $item by reference, as I mentioned before? A single character added to the above test:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $set[] = ucfirst($item);
}
print_r($set);

Results in an infinite loop. Note this actually is an infinite loop, you’ll have to either kill the script yourself or wait for your OS to run out of memory. I added the following line to my script so PHP would run out of memory very quickly, I suggest you do the same if you’re going to be running these infinite loop tests:

ini_set("memory_limit","1M");

So in this previous example with the infinite loop, we see the reason why PHP was written to create a copy of the array to loop over. When a copy is created and used only by the structure of the loop construct itself, the array stays static throughout the execution of the loop, so you’ll never run into issues.

Moment.js transform to date object

Since momentjs has no control over javascript date object I found a work around to this.

_x000D_
_x000D_
const currentTime = new Date();    _x000D_
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");_x000D_
const convertTimeObject = new Date(convertTime);
_x000D_
_x000D_
_x000D_

This will give you a javascript date object with the converted time

SQL Server loop - how do I loop through a set of records

By using T-SQL and cursors like this :

DECLARE @MyCursor CURSOR;
DECLARE @MyField YourFieldDataType;
BEGIN
    SET @MyCursor = CURSOR FOR
    select top 1000 YourField from dbo.table
        where StatusID = 7      

    OPEN @MyCursor 
    FETCH NEXT FROM @MyCursor 
    INTO @MyField

    WHILE @@FETCH_STATUS = 0
    BEGIN
      /*
         YOUR ALGORITHM GOES HERE   
      */
      FETCH NEXT FROM @MyCursor 
      INTO @MyField 
    END; 

    CLOSE @MyCursor ;
    DEALLOCATE @MyCursor;
END;

If a folder does not exist, create it

A fancy way is to extend the FileUpload with the method you want.

Add this:

public static class FileUploadExtension
{
    public static void SaveAs(this FileUpload, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.SaveAs(destination);
    }
}

Then use it:

FileUpload file;
...
file.SaveAs(path,true);

PHP is_numeric or preg_match 0-9 validation

Not exactly the same.

From the PHP docs of is_numeric:

'42' is numeric
'1337' is numeric
'1e4' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric

With your regex you only check for 'basic' numeric values.

Also is_numeric() should be faster.

How to fix java.net.SocketException: Broken pipe?

I'd the same problem while I was developing a simple Java application that listens on a specific TCP. Usually, I had no problem, but when I run some stress test I noticed that some connection broke with error socket write exception.

After Investigation I found a solution that solves my problem. I know this question is quite old, but I prefer to share my solution, someone can find it useful.

The problem was on ServerSocket creation. I read from Javadoc there is a default limit of 50 pending sockets. If you try opening another connection, these will be refused. The solution consist simply in change this default configuration at server side. In the following case, I create a Socket server that listen at TCP port 10_000 and accept max 200 pending sockets.

new Thread(() -> {
      try (ServerSocket serverSocket = new ServerSocket(10_000, 200)) {
        logger.info("Server starts listening on TCP port {}", port);

        while (true) {
          try {
            ClientHandler clientHandler = clientHandlerProvider.getObject(serverSocket.accept(), this);
            executor.execute(clientHandler::start);
          } catch (Exception e) {
            logger.error(e.getMessage());
          }
        }

      } catch (IOException | SecurityException | IllegalArgumentException e) {
        logger.error("Could not open server on TCP port {}. Reason: {}", port, e.getMessage());
      }
    }).start();

From Javadoc of ServerSocket:

The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused.

How to make JQuery-AJAX request synchronous

The below is a working example. Add async:false.

const response = $.ajax({
                    type:"POST",
                    dataType:"json",
                    async:false, 
                    url:"your-url",
                    data:{"data":"data"}                        
                });                   
 console.log("response: ", response);

Excel formula to get cell color

Color is not data.

The Get.cell technique has flaws.

  1. It does not update as soon as the cell color changes, but only when the cell (or the sheet) is recalculated.
  2. It does not have sufficient numbers for the millions of colors that are available in modern Excel. See the screenshot and notice how the different intensities of yellow or purple all have the same number.

enter image description here

That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.

Again: Color is not data.

If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.

Displaying all table names in php from MySQL database

The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.

It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.

HttpClient does not exist in .net 4.0: what can I do?

read this...

Portable HttpClient for .NET Framework and Windows Phone

see paragraph Using HttpClient on .NET Framework 4.0 or Windows Phone 7.5 http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

Simple way to compare 2 ArrayLists

If your requirement is to maintain the insertion order plus check the contents of the two arraylist then you should do following:

List<String> listOne = new ArrayList<String>();
List<String> listTwo = new ArrayList<String>();

listOne.add("stack");
listOne.add("overflow");

listTwo.add("stack");
listTwo.add("overflow");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

This will return true.

However, if you change the ordering for example:

listOne.add("stack");
listOne.add("overflow");

listTwo.add("overflow");
listTwo.add("stack");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

will return false as ordering is different.

Validating file types by regular expression

You can use this template for every file type:

ValidationExpression="^.+\.(([pP][dD][fF])|([jJ][pP][gG])|([pP][nN][gG])))$"

for ex: you can add ([rR][aA][rR]) for Rar file type and etc ...

How to kill an application with all its activities?

You are correct: calling finish() will only exit the current activity, not the entire application. however, there is a workaround for this:

Every time you start an Activity, start it using startActivityForResult(...). When you want to close the entire app, you can do something like this:

setResult(RESULT_CLOSE_ALL);
finish();

Then define every activity's onActivityResult(...) callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode)
    {
    case RESULT_CLOSE_ALL:
        setResult(RESULT_CLOSE_ALL);
        finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

This will cause a cascade effect closing all activities.

Also, I support CommonsWare in his suggestion: store the password in a variable so that it will be destroyed when the application is closed.

send mail from linux terminal in one line

You can use an echo with a pipe to avoid prompts or confirmation.

echo "This is the body" | mail -s "This is the subject" [email protected]

tSQL - Conversion from varchar to numeric works for all but integer

Presumably, you want to convert values before the decimal place to an integer. If so, use case and check for the right format:

SELECT (case when varcharcol not like '%.%' then cast(varcharcol as int)
             else cast(left(varcharcol, chardindex('.', varcharcol) - 1) as int)
        end) IntVal
FROM MyTable;

How to automatically close cmd window after batch file execution?

This works for me

cd "C:\Program Files\SmartBear\SoapUI-5.6.0\bin"

start SoapUI-5.6.0.exe -w "C:\DATA\SoapUi\Workspaces\Production-workspace.xml"

exit

Quick Sort Vs Merge Sort

It is not true that quicksort is better. ALso, it depends on what you mean better, memory consumption, or speed.

In terms of memory consumption, in worst case, but quicksort can use n^2 memory (i.e. each partition is 1 to n-1), whereas merge sort uses nlogn.

The above follows in terms of speed.

Connect HTML page with SQL server using javascript

<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;

$.ajax({
      type:"GET",
      url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
      crossDomain:true,
      dataType:'jsonp',
      success: function jsondata(data)
           {

            var parsedata=JSON.parse(JSON.stringify(data));
            var logindata=parsedata["Status"];

            if("sucess"==logindata)
            {   
                alert("success");
            }
            else
            {
                alert("failed");
            }
          }  
    }); 
<script>

You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.

Pass props to parent component in React.js

Basically you use props to send information to and from Child and Parent.

Adding to all the wonderful answers, let me give a simple example that explains passing values from child to parent component in React

App.js

class App extends React.Component {
      constructor(){
            super();
            this.handleFilterUpdate = this.handleFilterUpdate.bind(this);
            this.state={name:'igi'}
      }
      handleFilterUpdate(filterValue) {
            this.setState({
                  name: filterValue
            });
      }
   render() {
      return (
        <div>
            <Header change={this.handleFilterUpdate} name={this.state.name} />
            <p>{this.state.name}</p>
        </div>
      );
   }
}

Header.js

class Header extends React.Component {
      constructor(){
            super();
            this.state={
                  names: 'jessy'
            }
      }
      Change(event) {

      // this.props.change(this.state.names);
      this.props.change('jessy');
  }

   render() {
      return (
       <button onClick={this.Change.bind(this)}>click</button>

      );
   }
}

Main.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(<App />, document.getElementById('app'));

Thats it , now you can pass values from your client to the server.

Take a look at the Change function in the Header.js

Change(event) {
      // this.props.change(this.state.names);
      this.props.change('jessy');
  }

This is how you push values into the props from client to the server

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

With arrays, why is it the case that a[5] == 5[a]?

Because array access is defined in terms of pointers. a[i] is defined to mean *(a + i), which is commutative.

What does the NS prefix mean?

When NeXT were defining the NextStep API (as opposed to the NEXTSTEP operating system), they used the prefix NX, as in NXConstantString. When they were writing the OpenStep specification with Sun (not to be confused with the OPENSTEP operating system) they used the NS prefix, as in NSObject.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

type checking in javascript

A clean approach

You can consider using a very small, dependency-free library like Not. Solves all problems:

// at the basic level it supports primitives
let number = 10
let array = []
not('number', 10) // returns false
not('number', []) // throws error

// so you need to define your own:
let not = Object.create(Not)

not.defineType({
    primitive: 'number',
    type: 'integer',
    pass: function(candidate) {
        // pre-ECMA6
        return candidate.toFixed(0) === candidate.toString()
        // ECMA6
        return Number.isInteger(candidate)
    }
})
not.not('integer', 4.4) // gives error message
not.is('integer', 4.4) // returns false
not.is('integer', 8) // returns true

If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.

function test (string, boolean) {
    // any of these below will throw errors to protect you
    not('string', string)
    not('boolean', boolean)

    // continue with your code.
}

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

It prevents the browser from doing MIME-type sniffing. Most browsers are now respecting this header, including Chrome/Chromium, Edge, IE >= 8.0, Firefox >= 50 and Opera >= 13. See :

https://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx?Redirected=true

Sending the new X-Content-Type-Options response header with the value nosniff will prevent Internet Explorer from MIME-sniffing a response away from the declared content-type.

EDIT:

Oh and, that's an HTTP header, not a HTML meta tag option.

See also : http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx

Get current value when change select option - Angular2

Checkout this working Plunker

<select (change)="onItemChange($event.target.value)">
    <option *ngFor="#value of values" [value]="value.key">{{value.value}}</option>
</select>

Handling data in a PHP JSON Object

You mean something like this?

<?php

$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

foreach ( $json_output->trends as $trend )
{
    echo "{$trend->name}\n";
}

How to use subList()

You could use streams in Java 8. To always get 10 entries at the most, you could do:

dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());

Laravel $q->where() between dates

@Tom : Instead of using 'now' or 'addWeek' if we provide date in following format, it does not give correct records

$projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();

it gives records having date form 2015-10-16 to less than 2015-10-23. If value of recur_at is 2015-10-23 00:00:00 then only it shows that record else if it is 2015-10-23 12:00:45 then it is not shown.

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

Getting a browser's name client-side

JavaScript side - you can get browser name like these ways...

if(window.navigator.appName == "") OR if(window.navigator.userAgent == "")

Ignoring new fields on JSON objects using Jackson

You can annotate the specific property in your POJO with @JsonIgnore.

What is the best regular expression to check if a string is a valid URL?

The best regex, i've found is: /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi

For ios swift : (^|\\s)((https?:\\/\\/)?[\\w-]+(\\.[\\w-]+)+\\.?(:\\d+)?(\\/\\S*)?)

http://jsfiddle.net/9BYdp/1/

Found here

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

Select default option value from typescript angular 6

Correct Way would be :

<select id="select-type-basic" [(ngModel)]="status">
    <option *ngFor="let status_item of status_values">
    {{status_item}}
    </option>
</select>

Value Should be avoided inside option if the value is to be dynamic,since that will set the default value of the 'Select field'. Default Selection should be binded with [(ngModel)] and Options should be declared likewise.

status : any = "47";
status_values: any = ["45", "46", "47"];

Laravel redirect back to original destination after login

First, you should know, how you redirect user to 'login' route:

return redirect()->guest('/signin');

Not like this:

return redirect()->intended('/signin');

Mark error in form using Bootstrap

(UPDATED with examples for Bootstrap v4, v3 and v3)

Examples of forms with validation classes for the past few major versions of Bootstrap.

Bootstrap v4

See the live version on codepen

bootstrap v4 form validation

<div class="container">
  <form>
    <div class="form-group row">
      <label for="inputEmail" class="col-sm-2 col-form-label text-success">Email</label>
      <div class="col-sm-7">
        <input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email">
      </div>
    </div>

    <div class="form-group row">
      <label for="inputPassword" class="col-sm-2 col-form-label text-danger">Password</label>
      <div class="col-sm-7">
        <input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password">
      </div>
      <div class="col-sm-3">
        <small id="passwordHelp" class="text-danger">
          Must be 8-20 characters long.
        </small>      
      </div>
    </div>
  </form>
</div>

Bootstrap v3

See the live version on codepen

bootstrap v3 form validation

<form role="form">
  <div class="form-group has-warning">
    <label class="control-label" for="inputWarning">Input with warning</label>
    <input type="text" class="form-control" id="inputWarning">
    <span class="help-block">Something may have gone wrong</span>
  </div>
  <div class="form-group has-error">
    <label class="control-label" for="inputError">Input with error</label>
    <input type="text" class="form-control" id="inputError">
    <span class="help-block">Please correct the error</span>
  </div>
  <div class="form-group has-info">
    <label class="control-label" for="inputError">Input with info</label>
    <input type="text" class="form-control" id="inputError">
    <span class="help-block">Username is taken</span>
  </div>
  <div class="form-group has-success">
    <label class="control-label" for="inputSuccess">Input with success</label>
    <input type="text" class="form-control" id="inputSuccess" />
    <span class="help-block">Woohoo!</span>
  </div>
</form>

Bootstrap v2

See the live version on jsfiddle

bootstrap v2 form validation

The .error, .success, .warning and .info classes are appended to the .control-group. This is standard Bootstrap markup and styling in v2. Just follow that and you're in good shape. Of course you can go beyond with your own styles to add a popup or "inline flash" if you prefer, but if you follow Bootstrap convention and hang those validation classes on the .control-group it will stay consistent and easy to manage (at least since you'll continue to have the benefit of Bootstrap docs and examples)

  <form class="form-horizontal">
    <div class="control-group warning">
      <label class="control-label" for="inputWarning">Input with warning</label>
      <div class="controls">
        <input type="text" id="inputWarning">
        <span class="help-inline">Something may have gone wrong</span>
      </div>
    </div>
    <div class="control-group error">
      <label class="control-label" for="inputError">Input with error</label>
      <div class="controls">
        <input type="text" id="inputError">
        <span class="help-inline">Please correct the error</span>
      </div>
    </div>
    <div class="control-group info">
      <label class="control-label" for="inputInfo">Input with info</label>
      <div class="controls">
        <input type="text" id="inputInfo">
        <span class="help-inline">Username is taken</span>
      </div>
    </div>
    <div class="control-group success">
      <label class="control-label" for="inputSuccess">Input with success</label>
      <div class="controls">
        <input type="text" id="inputSuccess">
        <span class="help-inline">Woohoo!</span>
      </div>
    </div>
  </form>

Postgresql 9.2 pg_dump version mismatch

Download the appropriate postgres version here:

https://www.postgresql.org/download/

Make sure to run the following commands (the postgresql.org/download URL will generate the specific URL for you to use; the one I use below is just an example for centos 7) as sudo:

sudo yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo yum install postgresql11-server

your pg_dump version should now be updated, verify with pg_dump -V

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

If you are using Jersey for REST API's you can do as below

You don't have to change your webservices implementation.

I will explain for Jersey 2.x

1) First add a ResponseFilter as shown below

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;

public class CorsResponseFilter implements ContainerResponseFilter {

@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}

2) then in the web.xml , in the jersey servlet declaration add the below

    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>YOUR PACKAGE.CorsResponseFilter</param-value>
    </init-param>

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

String Concatenation in EL

1.The +(operator) has not effect to that in using EL. 2.so this is the way,to use that

<c:set var="enabled" value="${value} enabled" />


<c:out value="${empty value ? 'none' : enabled}" />

is this helpful to You ?

is it possible to get the MAC address for machine using nmap

If you're using nmap, MAC addresses are only available if you're on the same network segment as the target. Newer versions of nmap will only show the MAC address to you if you're running as root.

i.e.:

sudo nmap -sP -n 192.168.0.0/24

Importing large sql file to MySql via command line

The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.

Here is the script https://github.com/kedarvj/mysqldumpsplitter

And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully

ThreeJS: Remove object from scene

THIS WORKS GREAT - I tested it so, please SET NAME for every object

give the name to the object upon creation

    mesh.name = 'nameMeshObject';

and use this if you have to delete an object

    delete3DOBJ('nameMeshObject');



    function delete3DOBJ(objName){
        var selectedObject = scene.getObjectByName(objName);
        scene.remove( selectedObject );
        animate();
    }

open a new scene , add object open new scene , add object

delete an object and create new delete object and create new

Why is volatile needed in C?

The Wiki say everything about volatile:

And the Linux kernel's doc also make a excellent notation about volatile:

How can you get the build/version number of your Android application?

try {
    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    String versionName = packageInfo.versionName;
    int versionCode = packageInfo.versionCode;
    //binding.tvVersionCode.setText("v" + packageInfo.versionName);
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

Setting focus on an HTML input box on page load

This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.

Fix :-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    element.focus();
    setTimeout(function () { element.focus(); }, 1);
}

And call FocusOnInput() on $(document).ready(function () {.....};

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

How to update column with null value

Use IS instead of = This will solve your problem example syntax:

UPDATE studentdetails
SET contactnumber = 9098979690
WHERE contactnumber IS NULL;

What is the SSIS package and what does it do?

Microsoft SQL Server Integration Services (SSIS) is a platform for building high-performance data integration solutions, including extraction, transformation, and load (ETL) packages for data warehousing. SSIS includes graphical tools and wizards for building and debugging packages; tasks for performing workflow functions such as FTP operations, executing SQL statements, and sending e-mail messages; data sources and destinations for extracting and loading data; transformations for cleaning, aggregating, merging, and copying data; a management database, SSISDB, for administering package execution and storage; and application programming interfaces (APIs) for programming the Integration Services object model.

As per Microsoft, the main uses of SSIS Package are:

• Merging Data from Heterogeneous Data Stores Populating Data

• Warehouses and Data Marts Cleaning and Standardizing Data Building

• Business Intelligence into a Data Transformation Process Automating

• Administrative Functions and Data Loading

For developers:

SSIS Package can be integrated with VS development environment for building Business Intelligence solutions. Business Intelligence Development Studio is the Visual Studio environment with enhancements that are specific to business intelligence solutions. It work with 32-bit development environment only.

Download SSDT tools for Visual Studio:

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

Creating SSIS ETL Package - Basics :

https://docs.microsoft.com/en-us/sql/integration-services/ssis-how-to-create-an-etl-package?view=sql-server-2017

Sample project of SSIS features in 6 lessons:

https://docs.microsoft.com/en-us/sql/integration-services/ssis-how-to-create-an-etl-package?view=sql-server-2017

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

How to POST form data with Spring RestTemplate?

here is the full program to make a POST rest call using spring's RestTemplate.

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}

Adding Apostrophe in every field in particular column for excel

I'm going to suggest the non-obvious. There is a fantastic (and often under-used) tool called the Immediate Window in Visual Basic Editor. Basically, you can write out commands in VBA and execute them on the spot, sort of like command prompt. It's perfect for cases like this.

Press ALT+F11 to open VBE, then Control+G to open the Immediate Window. Type the following and hit enter:

for each v in range("K2:K5000") : v.value = "'" & v.value : next

And boom! You are all done. No need to create a macro, declare variables, no need to drag and copy, etc. Close the window and get back to work. The only downfall is to undo it, you need to do it via code since VBA will destroy your undo stack (but that's simple).

Month name as a string

A sample way to get the date and time in this format "2018 Nov 01 16:18:22" use this

DateFormat dateFormat = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
        Date date = new Date();
         dateFormat.format(date);

Number to String in a formula field

I believe this is what you're looking for:

Convert Decimal Numbers to Text showing only the non-zero decimals

Especially this line might be helpful:

StringVar text     :=  Totext ( {Your.NumberField} , 6 , ""  )  ;

The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.

How to stop console from closing on exit?

You can simply press Ctrl+F5 instead of F5 to run the built code. Then it will prompt you to press any key to continue. Or you can use this line -> system("pause"); at the end of the code to make it wait until you press any key.

However, if you use the above line, system("pause"); and press Ctrl+F5 to run, it will prompt you twice!

Entity Framework 6 Code first Default value

After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.

1- Create custom code generator and override Generate for a ColumnModel.

   public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{

    protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
    {

        if (column.Annotations.Keys.Contains("Default"))
        {
            var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
            column.DefaultValue = value;
        }


        base.Generate(column, writer, emitName);
    }

}

2- Assign the new code generator:

public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
    public Configuration()
    {
        CodeGenerator = new ExtendedMigrationCodeGenerator();
        AutomaticMigrationsEnabled = false;
    }
}

3- Use fluent api to created the Annotation:

public static void Configure(DbModelBuilder builder){    
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);            
}

iOS - UIImageView - how to handle UIImage image orientation

Inspired from @Aqua Answer.....

in Objective C

- (UIImage *)fixImageOrientation:(UIImage *)img {

   UIGraphicsBeginImageContext(img.size);
   [img drawAtPoint:CGPointZero];

   UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if (newImg) {
       return newImg;
   }

   return img;
}

iOS detect if user is on an iPad

You can also use this

#define IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
...
if (IPAD) {
   // iPad
} else {
   // iPhone / iPod Touch
}

How do I display the current value of an Android Preference in the Preference summary?

You have to use bindPreferenceSummaryToValue function on the onCreate method.

Example:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add 'general' preferences, defined in the XML file
        addPreferencesFromResource(R.xml.pref_general);

        // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
        // updated when the preference changes.
        bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
        bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key)));
    }

See lesson 3 on Udacity Android Course: https://www.udacity.com/course/viewer#!/c-ud853/l-1474559101/e-1643578599/m-1643578601

Switching users inside Docker image to a non-root user

In case you need to perform privileged tasks like changing permissions of folders you can perform those tasks as a root user and then create a non-privileged user and switch to it:

From <some-base-image:tag>

# Switch to root user
USER root # <--- Usually you won't be needed it - Depends on base image

# Run privileged command
RUN apt install <packages>
RUN apt <privileged command>

# Set user and group
ARG user=appuser
ARG group=appuser
ARG uid=1000
ARG gid=1000
RUN groupadd -g ${gid} ${group}
RUN useradd -u ${uid} -g ${group} -s /bin/sh -m ${user} # <--- the '-m' create a user home directory

# Switch to user
USER ${uid}:${gid}

# Run non-privileged command
RUN apt <non-privileged command>

How to reload apache configuration for a site without restarting apache?

It should be possible using the command

sudo /etc/init.d/apache2 reload

I hope that helps.

Remove redundant paths from $PATH variable

If you just want to remove any duplicate paths, I use this script I wrote a while back since I was having trouble with multiple perl5/bin paths:

#!/bin/bash
#
# path-cleanup
#
# This must be run as "source path-cleanup" or ". path-cleanup"
# so the current shell gets the changes.

pathlist=`echo $PATH | sed 's/:/\n/g' | uniq`

# echo "Starting PATH: $PATH"
# echo "pathlist: $pathlist"
unset PATH
# echo "After unset, PATH: $PATH"
for dir in $pathlist
do
    if test -d $dir ; then
        if test -z $PATH; then
            PATH=$dir
        else
            PATH=$PATH:$dir
        fi
    fi
done
export PATH
# echo "After loop, PATH: $PATH"

And I put it in my ~/.profile at the end. Since I use BASH almost exclusively, I haven't tried it in other shells.

Perfect 100% width of parent container for a Bootstrap input?

Use .container-fluid, if you want to full-width as parent, spanning the entire width of your viewport.

Allow only numeric value in textbox using Javascript

// Solution to enter only numeric value in text box

$('#num_of_emp').keyup(function () { 
    this.value = this.value.replace(/[^0-9.]/g,'');
});

for an input box such as :

<input type='text' name='number_of_employee' id='num_of_emp' />

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Simple Steps

  1. 1 Open SQL Server Configuration Manager
  2. Under SQL Server Services Select Your Server
  3. Right Click and Select Properties
  4. Log on Tab Change Built-in-account tick
  5. in the drop down list select Network Service
  6. Apply and start The service

Get only filename from url in php without any variable values which exist in the url

Try the following code:

For PHP 5.4.0 and above:

$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);

For PHP Version < 5.4.0

$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy-1.9.2+mkl-cp27-none-win_amd64.whl as appropriate).

  1. Download (by right click and "save target") get-pip to local drive.

  2. At the command prompt, navigate to the directory containing get-pip.py and run

    python get-pip.py

    which creates files in C:\Python27\Scripts, including pip2, pip2.7 and pip.

  3. Copy the downloaded numpy-1.9.2+mkl-cp27-none-win_amd64.whl into the above directory (C:\Python27\Scripts)

  4. Still at the command prompt, navigate to the above directory and run:

    pip2.7.exe install "numpy-1.9.2+mkl-cp27-none-win_amd64.whl"

How to insert a large block of HTML in JavaScript?

Template literals may solve your issue as it will allow writing multi-line strings and string interpolation features. You can use variables or expression inside string (as given below). It's easy to insert bulk html in a reader friendly way.

I have modified the example given in question and please see it below. I am not sure how much browser compatible Template literals are. Please read about Template literals here.

_x000D_
_x000D_
var a = 1, b = 2;_x000D_
var div = document.createElement('div');_x000D_
div.setAttribute('class', 'post block bc2');_x000D_
div.innerHTML = `_x000D_
    <div class="parent">_x000D_
        <div class="child">${a}</div>_x000D_
        <div class="child">+</div>_x000D_
        <div class="child">${b}</div>_x000D_
        <div class="child">=</div>_x000D_
        <div class="child">${a + b}</div>_x000D_
    </div>_x000D_
`;_x000D_
document.getElementById('posts').appendChild(div);
_x000D_
.parent {_x000D_
  background-color: blue;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}_x000D_
.post div {_x000D_
  color: white;_x000D_
  font-size: 2.5em;_x000D_
  padding: 20px;_x000D_
}
_x000D_
<div id="posts"></div>
_x000D_
_x000D_
_x000D_

Java: how can I split an ArrayList in multiple small ArrayLists?

Apache Commons Collections 4 has a partition method in the ListUtils class. Here’s how it works:

import org.apache.commons.collections4.ListUtils;
...

int targetSize = 100;
List<Integer> largeList = ...
List<List<Integer>> output = ListUtils.partition(largeList, targetSize);

How do I pipe or redirect the output of curl -v?

add the -s (silent) option to remove the progress meter, then redirect stderr to stdout to get verbose output on the same fd as the response body

curl -vs google.com 2>&1 | less

Amazon S3 boto - how to create a folder?

Tried many method above and adding forward slash / to the end of key name, to create directory didn't work for me:

client.put_object(Bucket="foo-bucket", Key="test-folder/")

You have to supply Body parameter in order to create directory:

client.put_object(Bucket='foo-bucket',Body='', Key='test-folder/')

Source: ryantuck in boto3 issue

CSS list item width/height does not work

I think the problem is, that you're trying to set width to an inline element which I'm not sure is possible. In general Li is block and this would work.

Retrieve version from maven pom.xml in code

When using spring boot, this link might be useful: https://docs.spring.io/spring-boot/docs/2.3.x/reference/html/howto.html#howto-properties-and-configuration

With spring-boot-starter-parent you just need to add the following to your application config file:

# get values from pom.xml
[email protected]@

After that the value is available like this:

@Value("${pom.version}")
private String pomVersion;

Html.EditorFor Set Default Value

The clean way to do so is to pass a new instance of the created entity through the controller:

//GET
public ActionResult CreateNewMyEntity(string default_value)
{
    MyEntity newMyEntity = new MyEntity();
    newMyEntity._propertyValue = default_value;

    return View(newMyEntity);
}

If you want to pass the default value through ActionLink

@Html.ActionLink("Create New", "CreateNewMyEntity", new { default_value = "5" })

PHP: How to check if image file exists?

Read first 5 bytes form HTTP using fopen() and fread() then use this:

DEFINE("GIF_START","GIF");
DEFINE("PNG_START",pack("C",0x89)."PNG");
DEFINE("JPG_START",pack("CCCCCC",0xFF,0xD8,0xFF,0xE0,0x00,0x10)); 

to detect image.

Format Date/Time in XAML in Silverlight

In SL5 I found this to work:

<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat=dd-MMMM-yy hh:mm}">
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat='Justification Date: \{0:dd-MMMM-yy hh:mm\}'}">

Keeping ASP.NET Session Open / Alive

you can just write this code in you java script file thats it.

$(document).ready(function () {
        var delay = (20-1)*60*1000;
        window.setInterval(function () {
            var url = 'put the url of some Dummy page';
            $.get(url);                
        }, delay);
});

The (20-1)*60*1000 is refresh time, it will refresh the session timeout. Refresh timeout is calculated as default time out of iis = 20 minutes, means 20 × 60000 = 1200000 milliseconds - 60000 millisecond (One minutes before session expires ) is 1140000.

How to initialize a dict with keys from a list and empty value in Python?

dict.fromkeys([1, 2, 3, 4])

This is actually a classmethod, so it works for dict-subclasses (like collections.defaultdict) as well. The optional second argument specifies the value to use for the keys (defaults to None.)

Oracle - What TNS Names file am I using?

By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin directory on UNIX operating systems and in the ORACLE_HOME\network\admin directory on Windows operating systems. tnsnames.ora can also be stored the following locations:

The directory specified by the TNS_ADMIN environment variable (or registry value)

On UNIX operating systems, the global configuration directory. For example, on the Solaris Operating System, this directory is /var/opt/oracle

If you have multiple ORACLE_HOMES, be aware of which one you are using, as the location of the tnsnames.ora file can vary from one ORACLE_HOME to the next.

For the person who mentioned the TWO_TASK environment variable, that is used to set a default database service name to connect to (which could be a database on another server). The service name you set TWO_TASK to is then looked up in the tnsnames.ora file when you connect.

How to handle login pop up window using Selenium WebDriver?

This should works with windows server 2012 and IE.

var alert = driver.SwitchTo().Alert();

alert.SetAuthenticationCredentials("username", "password");

alert.Accept();

Can I send a ctrl-C (SIGINT) to an application on Windows?

Based on process id, we can send the signal to process to terminate forcefully or gracefully or any other signal.

List all process :

C:\>tasklist

To kill the process:

C:\>Taskkill /IM firefox.exe /F
or
C:\>Taskkill /PID 26356 /F

Details:

http://tweaks.com/windows/39559/kill-processes-from-command-prompt/

How to programmatically close a JFrame

You have to insert the call into the AWT message queue so all the timing happens correctly, otherwise it will not dispatch the correct event sequence, especially in a multi-threaded program. When this is done you may handle the resulting event sequence exactly as you would if the user has clicked on the [x] button for an OS suppled decorated JFrame.

public void closeWindow()
{
    if(awtWindow_ != null) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                awtWindow_.dispatchEvent(new WindowEvent(awtWindow_, WindowEvent.WINDOW_CLOSING));
            }
        });
    }
}

TypeError: got multiple values for argument

This exception also will be raised whenever a function has been called with the combination of keyword arguments and args, kwargs

Example:

def function(a, b, c, *args, **kwargs):
    print(f"a: {a}, b: {b}, c: {c}, args: {args}, kwargs: {kwargs}")

function(a=1, b=2, c=3, *(4,))

And it'll raise:

TypeError                                 Traceback (most recent call last)
<ipython-input-4-1dcb84605fe5> in <module>
----> 1 function(a=1, b=2, c=3, *(4,))

TypeError: function() got multiple values for argument 'a'

And Also it'll become more complicated, whenever you misuse it in the inheritance. so be careful we this stuff!

1- Calling a function with keyword arguments and args:

class A:
    def __init__(self, a, b, *args, **kwargs):
        self.a = a
        self.b = b
    
class B(A):
    def __init__(self, *args, **kwargs):

        a = 1
        b = 2
        super(B, self).__init__(a=a, b=b, *args, **kwargs)

B(3, c=2)

Exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-5-17e0c66a5a95> in <module>
     11         super(B, self).__init__(a=a, b=b, *args, **kwargs)
     12 
---> 13 B(3, c=2)

<ipython-input-5-17e0c66a5a95> in __init__(self, *args, **kwargs)
      9         a = 1
     10         b = 2
---> 11         super(B, self).__init__(a=a, b=b, *args, **kwargs)
     12 
     13 B(3, c=2)

TypeError: __init__() got multiple values for argument 'a'

2- Calling a function with keyword arguments and kwargs which it contains keyword arguments too:

class A:
    def __init__(self, a, b, *args, **kwargs):
        self.a = a
        self.b = b
    
class B(A):
    def __init__(self, *args, **kwargs):

        a = 1
        b = 2
        super(B, self).__init__(a=a, b=b, *args, **kwargs)

B(**{'a': 2})

Exception:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-c465f5581810> in <module>
     11         super(B, self).__init__(a=a, b=b, *args, **kwargs)
     12 
---> 13 B(**{'a': 2})

<ipython-input-7-c465f5581810> in __init__(self, *args, **kwargs)
      9         a = 1
     10         b = 2
---> 11         super(B, self).__init__(a=a, b=b, *args, **kwargs)
     12 
     13 B(**{'a': 2})

TypeError: __init__() got multiple values for keyword argument 'a'

php check if array contains all array values from another array

A bit shorter with array_diff

$musthave = array('a','b');
$test1 = array('a','b','c');
$test2 = array('a','c');

$containsAllNeeded = 0 == count(array_diff($musthave, $test1));

// this is TRUE

$containsAllNeeded = 0 == count(array_diff($musthave, $test2));

// this is FALSE

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Array as session variable

Yes, you can put arrays in sessions, example:

$_SESSION['name_here'] = $your_array;

Now you can use the $_SESSION['name_here'] on any page you want but make sure that you put the session_start() line before using any session functions, so you code should look something like this:

 session_start();
 $_SESSION['name_here'] = $your_array;

Possible Example:

 session_start();
 $_SESSION['name_here'] = $_POST;

Now you can get field values on any page like this:

 echo $_SESSION['name_here']['field_name'];

As for the second part of your question, the session variables remain there unless you assign different array data:

 $_SESSION['name_here'] = $your_array;

Session life time is set into php.ini file.

More Info Here

How do I create an Android Spinner as a popup?

This is from the Android SDK source code. As you can see you have a special constructor to create a Spinner with the specified mode you wanna use.

Hope it will help you :)

 /**
     * Construct a new spinner with the given context's theme, the supplied attribute set,
     * and default style. <code>mode</code> may be one of {@link #MODE_DIALOG} or
     * {@link #MODE_DROPDOWN} and determines how the user will select choices from the spinner.
     *
     * @param context The Context the view is running in, through which it can
     *        access the current theme, resources, etc.
     * @param attrs The attributes of the XML tag that is inflating the view.
     * @param defStyle The default style to apply to this view. If 0, no style
     *        will be applied (beyond what is included in the theme). This may
     *        either be an attribute resource, whose value will be retrieved
     *        from the current theme, or an explicit style resource.
     * @param mode Constant describing how the user will select choices from the spinner.
     * 
     * @see #MODE_DIALOG
     * @see #MODE_DROPDOWN
     */
    public Spinner(Context context, AttributeSet attrs, int defStyle, int mode) {
        super(context, attrs, defStyle);

Variably modified array at file scope

The reason for this warning is that const in c doesn't mean constant. It means "read only". So the value is stored at a memory address and could potentially be changed by machine code.

Listing available com ports with Python

Probably late, but might help someone in need.

import serial.tools.list_ports


class COMPorts:

    def __init__(self, data: list):
        self.data = data

    @classmethod
    def get_com_ports(cls):
        data = []
        ports = list(serial.tools.list_ports.comports())

        for port_ in ports:
            obj = Object(data=dict({"device": port_.device, "description": port_.description.split("(")[0].strip()}))
            data.append(obj)

        return cls(data=data)

    @staticmethod
    def get_description_by_device(device: str):
        for port_ in COMPorts.get_com_ports().data:
            if port_.device == device:
                return port_.description

    @staticmethod
    def get_device_by_description(description: str):
        for port_ in COMPorts.get_com_ports().data:
            if port_.description == description:
                return port_.device


class Object:
    def __init__(self, data: dict):
        self.data = data
        self.device = data.get("device")
        self.description = data.get("description")


if __name__ == "__main__":
    for port in COMPorts.get_com_ports().data:
        print(port.device)
        print(port.description)

    print(COMPorts.get_device_by_description(description="Arduino Leonardo"))
    print(COMPorts.get_description_by_device(device="COM3"))

How to iterate a loop with index and element in Swift

Yes. As of Swift 3.0, if you need the index for each element along with its value, you can use the enumerated() method to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:

for (index, element) in list.enumerated() {
  print("Item \(index): \(element)")
}

Before Swift 3.0 and after Swift 2.0, the function was called enumerate():

for (index, element) in list.enumerate() {
    print("Item \(index): \(element)")
}

Prior to Swift 2.0, enumerate was a global function.

for (index, element) in enumerate(list) {
    println("Item \(index): \(element)")
}

Python 3: ImportError "No Module named Setuptools"

pip uninstall setuptools

and then:

pip install setuptools

This works for me and fix my issue.

How to escape special characters of a string with single backslashes

We could use built-in function repr() or string interpolation fr'{}' escape all backwardslashs \ in Python 3.7.*

repr('my_string') or fr'{my_string}'

Check the Link: https://docs.python.org/3/library/functions.html#repr

How to insert double and float values to sqlite?

SQL Supports following types of affinities:

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • BLOB

If the declared type for a column contains any of these "REAL", "FLOAT", or "DOUBLE" then the column has 'REAL' affinity.

create table with sequence.nextval in oracle

In Oracle 12c you can also declare an identity column

CREATE TABLE identity_test_tab (
  id          NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  description VARCHAR2(30)
);

examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.

Differences between dependencyManagement and dependencies in Maven

There's still one thing that is not highlighted enough, in my opinion, and that is unwanted inheritance.

Here's an incremental example:

I declare in my parent pom:

<dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
</dependencies>

boom! I have it in my Child A, Child B and Child C modules:

  • Implicilty inherited by child poms
  • A single place to manage
  • No need to redeclare anything in child poms
  • I can still redelcare and override to version 18.0 in a Child B if I want to.

But what if I end up not needing guava in Child C, and neither in the future Child D and Child E modules?

They will still inherit it and this is undesired! This is just like Java God Object code smell, where you inherit some useful bits from a class, and a tonn of unwanted stuff as well.

This is where <dependencyManagement> comes into play. When you add this to your parent pom, all of your child modules STOP seeing it. And thus you are forced to go into each individual module that DOES need it and declare it again (Child A and Child B, without the version though).

And, obviously, you don't do it for Child C, and thus your module remains lean.

Sharing url link does not show thumbnail image on facebook

I found out that the image that you are specify with the og:image, has to actually be present in the HTML page inside an image tag.

the thumbnail appeared for me only after i added an image tag for the image. it was commented out. but worked.

Python 3.6 install win32api?

Take a look at this answer: ImportError: no module named win32api

You can use

pip install pypiwin32

get user timezone

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

mssql '5 (Access is denied.)' error during restoring database

The account that sql server is running under does not have access to the location where you have the backup file or are trying to restore the database to. You can use SQL Server Configuration Manager to find which account is used to run the SQL Server instance, and then make sure that account has full control over the .BAK file and the folder where the MDF will be restored to.

enter image description here

Reload chart data via JSON with Highcharts

If you are using push to push the data to the option.series dynamically .. just use

options.series = [];  

to clear it.

options.series = [];
$("#change").click(function(){
}

htaccess "order" Deny, Allow, Deny

Change your code to

<Limit GET POST>
deny from all

allow from 139.82.0.0/16
allow from 143.54.0.0/16
allow from 186.192.0.0/11
allow from 186.224.0.0/11
</Limit>

This way your htaccess will deny every except those that you explicitly allow with allow from..

A proxy within the allow range can easily be overwritten with an additional deny from.. rule.

Facebook Graph API error code list

I have also found some more error subcodes, in case of OAuth exception. Copied from the facebook bugtracker, without any garantee (maybe contain deprecated, wrong and discontinued ones):

/**
  * (Date: 30.01.2013)
  *
  * case 1: - "An error occured while creating the share (publishing to wall)"
  *         - "An unknown error has occurred."
  * case 2:    "An unexpected error has occurred. Please retry your request later."
  * case 3:    App must be on whitelist        
  * case 4:    Application request limit reached
  * case 5:    Unauthorized source IP address        
  * case 200:  Requires extended permissions
  * case 240:  Requires a valid user is specified (either via the session or via the API parameter for specifying the user."
  * case 1500: The url you supplied is invalid
  * case 200:
  * case 210:  - Subject must be a page
  *            - User not visible
  */

 /**
  * Error Code 100 several issus:
  * - "Specifying multiple ids with a post method is not supported" (http status 400)
  * - "Error finding the requested story" but it is available via GET
  * - "Invalid post_id"
  * - "Code was invalid or expired. Session is invalid."
  * 
  * Error Code 2: 
  * - Service temporarily unavailable
  */

Find and extract a number from a string

static string GetdigitFromString(string str)
    {
        char[] refArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        char[] inputArray = str.ToCharArray();
        string ext = string.Empty;
        foreach (char item in inputArray)
        {
            if (refArray.Contains(item))
            {
                ext += item.ToString();
            }
        }
        return ext;
    }

How to check the version of scipy

Using command line:

python -c "import scipy; print(scipy.__version__)"

Ajax Upload image

first in your ajax call include success & error function and then check if it gives you error or what?

your code should be like this

$(document).ready(function (e) {
    $('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#ImageBrowse").on("change", function() {
        $("#imageUploadForm").submit();
    });
});

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Execute command without keeping it in history

Start your command with a space and it won't be included in the history.

Be aware that this does require the environment variable $HISTCONTROL to be set.

  • Check that the following command returns ignorespace or ignoreboth

    #> echo $HISTCONTROL
    
  • To add the environment variable if missing, the following line can be added to the bash profile. E.g. %HOME/.bashrc

    export HISTCONTROL=ignorespace
    

After sourcing the profile again space prefixed commands will not be written to $HISTFILE

Get string character by index - Java

CharAt function not working

Edittext.setText(YourString.toCharArray(),0,1);

This code working fine

Constructors in Go

There are actually two accepted best practices:

  1. Make the zero value of your struct a sensible default. (While this looks strange to most people coming from "traditional" oop it often works and is really convenient).
  2. Provide a function func New() YourTyp or if you have several such types in your package functions func NewYourType1() YourType1 and so on.

Document if a zero value of your type is usable or not (in which case it has to be set up by one of the New... functions. (For the "traditionalist" oops: Someone who does not read the documentation won't be able to use your types properly, even if he cannot create objects in undefined states.)

How to hide Soft Keyboard when activity starts

To hide the softkeyboard at the time of New Activity start or onCreate(),onStart() etc. you can use the code below:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

How to get jSON response into variable from a jquery script

You should use data.response in your JS instead of json.response.

jQuery UI: Datepicker set year range dropdown to 100 years

This is a bit late in the day for suggesting this, given how long ago the original question was posted, but this is what I did.

I needed a range of 70 years, which, while not as much as 100, is still too many years for the visitor to scroll through. (jQuery does step through year in groups, but that's a pain in the patootie for most people.)

The first step was to modify the JavaScript for the datepicker widget: Find this code in jquery-ui.js or jquery-ui-min.js (where it will be minimized):

for (a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+
a.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');\">";b<=g;b++)
 a.yearshtml+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
a.yearshtml+="</select>";

And replace it with this:

a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+
 ".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');
 \" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');
 \">";
for(opg=-1;b<=g;b++) {
    a.yearshtml+=((b%10)==0 || opg==-1 ?
        (opg==1 ? (opg=0, '</optgroup>') : '')+
        (b<(g-10) ? (opg=1, '<optgroup label="'+b+' >">') : '') : '')+
        '<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
}
a.yearshtml+="</select>";

This surrounds the decades (except for the current) with OPTGROUP tags.

Next, add this to your CSS file:

.ui-datepicker OPTGROUP { font-weight:normal; }
.ui-datepicker OPTGROUP OPTION { display:none; text-align:right; }
.ui-datepicker OPTGROUP:hover OPTION { display:block; }

This hides the decades until the visitor mouses over the base year. Your visitor can scroll through any number of years quickly.

Feel free to use this; just please give proper attribution in your code.

How to view the current heap size that an application is using?

Use this code:

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory(); 

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

 // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory(); 

It was useful to me to know it.

How to force a web browser NOT to cache images

I made a PHP script that automatically adds the timestamps for all images in the HTML page. You just need to include this script in your pages. Enjoy!

http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/

Downloading a Google font and setting up an offline site that uses it

I followed duydb's answer to produce the python code below that automates this process.

import requests

with open("example.css", "r") as f:
    text = f.read()
    urls = re.findall(r'(https?://[^\)]+)', text)

for url in urls:
    filename = url.split("/")[-1]
    r = requests.get(url)
    with open("./fonts/" + filename, "wb") as f: 
        f.write(r.content)
    text = text.replace(url, "/fonts/" + filename)

with open("example.css", "w") as f:
        f.write(text)

Hope this helps with some of the copy-paste death.

Difference between checkout and export in SVN

Very simple difference, If you just want to see the structure of your project then go for export.

And if you want to work on your files then you need to checkout as it will include the .svn folder which contains the metadata which makes the working copy, else you get the error in export.

If you do svn export and then edit some files and then commit, then you will get an error:

../../xxx is not your working copy.

Bootstrap carousel width and height

I know this is an older post but Bootstrap is still alive and kicking!

Slightly different to @Eduardo's post, I had to modify:

#myCarousel.carousel.slide {
    width: 100%; 
    max-width: 400px; !important
}

When I only modified .carousel-inner {}, the actual image was fixed size but the left/right controls were displaying incorrectly off to the side of the div.

How to pass data to all views in Laravel 5?

1) In (app\Providers\AppServiceProvider.php)

// in boot function
       view()->composer('*', function ($view) {
            $data = User::messages();
            $view->with('var_messages',$data);
        });

2) in Your User Model

  public static function messages(){ // this is just example
        $my_id = auth()->user()->id;
        $data= Message::whereTo($my_id)->whereIs_read('0')->get(); 
        return $data; // return is required
    }

3) in Your View

 {{ $var_messages }}

What is the purpose of the HTML "no-js" class?

The no-js class gets removed by a javascript script, so you can modify/display/hide things using css if js is disabled.

Recover SVN password from local cache

On Windows, Subversion stores the auth data in %APPDATA%\Subversion\auth. The passwords however are stored encrypted, not in plaintext.

You can decrypt those, but only if you log in to Windows as the same user for which the auth data was saved.

Someone even wrote a tool to decrypt those. Never tried the tool myself so I don't know how well it works, but you might want to try it anyway:

http://www.leapbeyond.com/ric/TSvnPD/

Update: In TortoiseSVN 1.9 and later, you can do it without any additional tools:

Settings Dialog -> Saved Data, then click the "Clear..." button right of the text "Authentication Data". A new dialog pops up, showing all stored authentication data where you can chose which one(s) to clear. Instead of clearing, hold down the Shift and Ctrl button, and then double click on the list. A new column is shown in the dialog which shows the password in clear.

IIS7: Setup Integrated Windows Authentication like in IIS6

There's another thread elsewhere on Stack with a similar topic and the best solution I've come across is to use the free version of Helicon Ape

Once you've got that installed, follow the steps at the page Titled "HTTP Authentication and Authorization"

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

I was facing the same issue. I realised that I was using the Wrong provider class in persistence.xml

For Hibernate it should be

<provider>org.hibernate.ejb.HibernatePersistence</provider>

And for EclipseLink it should be

<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

Can I position an element fixed relative to parent?

I know this is an older post, but I think a good example of what Jiew Meng was trying to do can already be found on this site. Check out the side menu located here: https://stackoverflow.com/faq#questions. Looking at it without getting into it too deep, I can tell javascript attaches a fixed position once the scrolling hits below the anchor tag and removes the fixed positioning if the scrolling goes above that same anchor tag. Hopefully, that will get someone started in the right direction.

How do I check that a number is float or integer?

try this

let n;
return (n = value % 1) !== 0 && !isNaN(n);

when the return value is false means the input value is float number or float string, otherwise the input value is integer numbef or integer string.

basically it needs to check the precision value for not equal to zero.

another one is to check the correct string number also.

Equivalent of *Nix 'which' command in PowerShell?

I usually just type:

gcm notepad

or

gcm note*

gcm is the default alias for Get-Command.

On my system, gcm note* outputs:

[27] » gcm note*

CommandType     Name                                                     Definition
-----------     ----                                                     ----------
Application     notepad.exe                                              C:\WINDOWS\notepad.exe
Application     notepad.exe                                              C:\WINDOWS\system32\notepad.exe
Application     Notepad2.exe                                             C:\Utils\Notepad2.exe
Application     Notepad2.ini                                             C:\Utils\Notepad2.ini

You get the directory and the command that matches what you're looking for.

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

What is the difference between a .cpp file and a .h file?

The C++ build system (compiler) knows no difference, so it's all one of conventions.

The convention is that .h files are declarations, and .cpp files are definitions.

That's why .h files are #included -- we include the declarations.

Python equivalent of D3.js

See:

Is there a good interactive 3D graph library out there?

The accepted answer suggests the following program, which apparently has python bindings: http://ubietylab.net/ubigraph/

Edit

I'm not sure about the interactivity of NetworkX, but you can definitely make 3D graphs. There is at least one example in the gallery:

http://networkx.lanl.gov/examples/drawing/edge_colormap.html

And another example in the 'examples'. This one, however, requires that you have Mayavi.

http://networkx.lanl.gov/examples/3d_drawing/mayavi2_spring.html

Android check internet connection

Check to make sure it is "connected" to a network:

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}

Check to make sure it is "connected" to a internet:

public boolean isInternetAvailable() {
    try {
        InetAddress address = InetAddress.getByName("www.google.com");
        return !address.equals("");
    } catch (UnknownHostException e) {
        // Log error
    }
    return false;
}

Permission needed:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

https://stackoverflow.com/a/17583324/950427

How to convert a private key to an RSA private key?

Newer versions of OpenSSL say BEGIN PRIVATE KEY because they contain the private key + an OID that identifies the key type (this is known as PKCS8 format). To get the old style key (known as either PKCS1 or traditional OpenSSL format) you can do this:

openssl rsa -in server.key -out server_new.key

Alternately, if you have a PKCS1 key and want PKCS8:

openssl pkcs8 -topk8 -nocrypt -in privkey.pem

How to get my activity context?

The best and easy way to get the activity context is putting .this after the name of the Activity. For example: If your Activity's name is SecondActivity, its context will be SecondActivity.this

VBA Date as integer

Just use CLng(Date).

Note that you need to use Long not Integer for this as the value for the current date is > 32767

Subtract 1 day with PHP

How about this: convert it to a unix timestamp first, subtract 60*60*24 (exactly one day in seconds), and then grab the date from that.

$newDate = strtotime($date_raw) - 60*60*24;
echo date('Y-m-d',$newDate);

Note: as apokryfos has pointed out, this would technically be thrown off by daylight savings time changes where there would be a day with either 25 or 23 hours

Difference between == and ===

>> is arithmetic shift right, >>> is logical shift right.

In an arithmetic shift, the sign bit is extended to preserve the signedness of the number.

For example: -2 represented in 8 bits would be 11111110 (because the most significant bit has negative weight). Shifting it right one bit using arithmetic shift would give you 11111111, or -1. Logical right shift, however, does not care that the value could possibly represent a signed number; it simply moves everything to the right and fills in from the left with 0s. Shifting our -2 right one bit using logical shift would give 01111111.

Installing and Running MongoDB on OSX

Problem here is you are trying to open a mongo shell without starting a mongo db which is listening to port 127.0.0.1:27017(deafault for mongo db) thats what the error is all about:

Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145 exception: connect failed

The easiest solution is to open the terminal and type

$ mongod --dbpath ~/data/db

Note: dbpath here is "Users/user" where data/db directories are created

i.e., you need to create directory data and sub directory db in your user folder. For e.g say `

/Users/johnny/data

After mongo db is up. Open another terminal in new window and type

$ mongo

it will open mongo shell with your mongo db connection opened in another terminal.

Detect click outside React component

None of the other answers here worked for me. I was trying to hide a popup on blur, but since the contents were absolutely positioned, the onBlur was firing even on the click of inner contents too.

Here is an approach that did work for me:

// Inside the component:
onBlur(event) {
    // currentTarget refers to this component.
    // relatedTarget refers to the element where the user clicked (or focused) which
    // triggered this event.
    // So in effect, this condition checks if the user clicked outside the component.
    if (!event.currentTarget.contains(event.relatedTarget)) {
        // do your thing.
    }
},

Hope this helps.

Why Does OAuth v2 Have Both Access and Refresh Tokens?

To clear up some confusion you have to understand the roles of the client secret and the user password, which are very different.

The client is an app/website/program/..., backed by a server, that wants to authenticate a user by using a third-party authentication service. The client secret is a (random) string that is known to both this client and the authentication server. Using this secret the client can identify itself with the authentication server, receiving authorization to request access tokens.

To get the initial access token and refresh token, what is required is:

  • The user ID
  • The user password
  • The client ID
  • The client secret

To get a refreshed access token however the client uses the following information:

  • The client ID
  • The client secret
  • The refresh token

This clearly shows the difference: when refreshing, the client receives authorization to refresh access tokens by using its client secret, and can thus re-authenticate the user using the refresh token instead of the user ID + password. This effectively prevents the user from having to re-enter his/her password.

This also shows that losing a refresh token is no problem because the client ID and secret are not known. It also shows that keeping the client ID and client secret secret is vital.

Watch multiple $scope attributes

Why not simply wrap it in a forEach?

angular.forEach(['a', 'b', 'c'], function (key) {
  scope.$watch(key, function (v) {
    changed();
  });
});

It's about the same overhead as providing a function for the combined value, without actually having to worry about the value composition.

How to access ssis package variables inside script component

I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.

After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.

So to access the variable, I type

string fp = Variables.FilePath;

In the PreExecute() method of the Script Component.

The name 'controlname' does not exist in the current context

I fixed this in my project by backing up the current files (so I still had my code), deleting the current aspx (and child pages), making a new one, and copying the contents of the backup files into the new files.

How to choose between Hudson and Jenkins?

From the Jenkins website, http://jenkins-ci.org, the following sums it up.

In a nutshell Jenkins CI is the leading open-source continuous integration server. Built with Java, it provides over 300 plugins to support building and testing virtually any project.

Oracle now owns the Hudson trademark, but has licensed it under the Eclipse EPL. Jenkins is on the MIT license. Both Hudson and Jenkins are open-source. Based on the combination of who you work for and personal preference for open-source, the decision is straightforward IMHO.

Hope this was helpful.

How to force reloading php.ini file?

TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm service.

The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

/etc/init.d/php-fpm restart        # typical
/etc/init.d/php5-fpm restart       # debian-style
/etc/init.d/php7.0-fpm restart     # debian-style PHP 7

Using service wrapper script

service php-fpm restart        # typical
service php5-fpm restart       # debian-style
service php7.0-fpm restart.    # debian-style PHP 7

Using Upstart (e.g. ubuntu):

restart php7.0-fpm         # typical (ubuntu is debian-based) PHP 7
restart php5-fpm           # typical (ubuntu is debian-based)
restart php-fpm            # uncommon

Using systemd (newer servers):

systemctl restart php-fpm.service        # typical
systemctl restart php5-fpm.service       # uncommon
systemctl restart php7.0-fpm.service     # uncommon PHP 7

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

your 8080 port is already used by another application 1/ you can try to find out which app is using it, using "netstat -aon" and stop the process; 2/ you can go to server.xml and change from port 8080 to another one (ex: 8081)

How to set column header text for specific column in Datagridview C#

there is HeaderText property in Column object, you can find the column and set its HeaderText after initializing grid or do it in windows form designer via designer for DataGrid.

    public Form1()
    {
        InitializeComponent();

        grid.Columns[0].HeaderText = "First Column"; 
        //..............
    }

More details are here at MSDN. More details about DataGrid are here.

Nginx - Customizing 404 page

You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.

To redirect to a simple 404 not found page for a specific location:

location /my_blog {
    error_page    404 /blog_article_not_found.html;
}

A site wide 404 page:

server {
    listen 80;
    error_page  404  /website_page_not_found.html;
    ...

You can append standard error codes together to have a single page for several types of errors:

location /my_blog {
    error_page 500 502 503 504 /server_error.html
}

To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:

upstream server2 {
    server 10.0.0.1:80;
}
server {
    location /my_blog {
        error_page    404 @try_server2;
    }
    location @try_server2 {
        proxy_pass http://server2;
    }

The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.

Programmatically set image to UIImageView with Xcode 6.1/Swift

If you want to do it the way you showed in your question, this is a way to do it inline

class YourClass: UIViewController{

  @IBOutlet weak var tableView: UITableView!
  //other IBOutlets

  //THIS is how you declare a UIImageView inline
  let placeholderImage : UIImageView = {
        let placeholderImage = UIImageView(image: UIImage(named: "nophoto"))
        placeholderImage.contentMode = .scaleAspectFill
        return placeholderImage
    }()

   var someVariable: String!
   var someOtherVariable: Int!

   func someMethod(){
      //method code
   }

   //and so on
}

Twitter Bootstrap dropdown menu

<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js"></script>

Conversion of a datetime2 data type to a datetime data type results out-of-range value

I ran into this issue on a simple console app project and my quick solution is to convert any possible datetime2 dates to a nullable datetime by running this method:

static DateTime? ParseDateTime2(DateTime? date)
    {
        if (date == null || date.ToString() == "1/1/0001 12:00:00 AM")
        {
            return null;
        }
        else
        {
            return date;
        }
    }

This is certainly not a completely comprehensive method, but it worked for my needs and maybe it'll help others!

Is calling destructor manually always a sign of bad design?

No, you shouldn't call it explicitly because it would be called twice. Once for the manual call and another time when the scope in which the object is declared ends.

Eg.

{
  Class c;
  c.~Class();
}

If you really need to perform the same operations you should have a separate method.

There is a specific situation in which you may want to call a destructor on a dynamically allocated object with a placement new but it doesn't sound something you will ever need.

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

Copy Image from Remote Server Over HTTP

make folder and name it foe example download open note pad and insert this code

only change http://www.google.com/aa.zip to your file and save it to m.php for example

chamod the php file to 666 and the folder download to 777

<?php
define('BUFSIZ', 4095);
$url = 'http://www.google.com/aa.zip';
$rfile = fopen($url, 'r');
$lfile = fopen(basename($url), 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);
?>

finally from your browser enter to these URL http://www.example.com/download/m.php

you will see in download folder the file download from other server

thanks

Java difference between FileWriter and BufferedWriter

http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedWriter.html

In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.

When to choose mouseover() and hover() function?

As you can read at http://api.jquery.com/mouseenter/

The mouseenter JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.

Unable to Resolve Module in React Native App

If your file path is correct then check any one file contains

import React from './node_modules/react';

replace it with

import React, { Component } from 'react';

Deserialize json object into dynamic object using Json.net

Json.NET allows us to do this:

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);

Output:

 1000
 string
 6

Documentation here: LINQ to JSON with Json.NET

See also JObject.Parse and JArray.Parse

How to set time zone in codeigniter?

Add it to your project/index.php file, and it will work on all over your site.

date_default_timezone_set('Asia/kabul');

Adding images or videos to iPhone Simulator

The simplest solution is to simply sign into iCloud on the simulator then use that to transfer any files in the drive, including photos.

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

Check to see if you have more than one file with that name in the solution.

I had this on a project that I took over from someone else. The breakpoint list was full of line numbers in Controller.cs, some active and some not. I found this question, and tried a few options, but when I double-clicked on the breakpoints, they took me to different projects within the solution. Because the files were called the same, they appear to be the same, but they aren't. The answer is of course then to ignore the warning, as they will become active if you get to load that other file.

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

In your PHP code you have set the incorrect port, this is what the code should be

<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'test_db13';

The port in your code is set to 3360 when it should be 3306, however as this is the default port, you don't need to specify.

Hide html horizontal but not vertical scrollbar

Using wrap=virtual in your HTML form boxes gets rid of the horizontal scrollbar at the bottom of the box:

  <textarea name= "enquiry" rows="4" cols="30" wrap="virtual"></textarea>

See example here : http://jsbin.com/opube3/2 (Tested on FF and IE)

Python: Assign Value if None Exists

This is a very different style of programming, but I always try to rewrite things that looked like

bar = None
if foo():
    bar = "Baz"

if bar is None:
    bar = "Quux"

into just:

if foo():
    bar = "Baz"
else:
    bar = "Quux"

That is to say, I try hard to avoid a situation where some code paths define variables but others don't. In my code, there is never a path which causes an ambiguity of the set of defined variables (In fact, I usually take it a step further and make sure that the types are the same regardless of code path). It may just be a matter of personal taste, but I find this pattern, though a little less obvious when I'm writing it, much easier to understand when I'm later reading it.

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

As the official documentation states:

When upgrading you may face the following:

java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

Hibernate typically requires JAXB that’s no longer provided by default. You can add the java.xml.bind module to restore this functionality with Java9 or Java10 (even if the module is deprecated).

As of Java11, the module is not available so your only option is to add the JAXB RI (you can do that as of Java9 in place of adding the java.xml.bind module:


Maven

<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
</dependency>

Gradle (build.gradle.kts):

implementation("org.glassfish.jaxb:jaxb-runtime")

Gradle (build.gradle)

implementation 'org.glassfish.jaxb:jaxb-runtime'

If you rather specify a specific version, take a look here: https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime

How to modify STYLE attribute of element with known ID using JQuery

$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});

<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific     runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>

Create an empty list in python with certain size

s1 = []
for i in range(11):
   s1.append(i)

print s1

To create a list, just use these brackets: "[]"

To add something to a list, use list.append()

iPhone/iOS JSON parsing tutorial

SBJSON *parser = [[SBJSON alloc] init];

NSString *url_str=[NSString stringWithFormat:@"Example APi Here"];

url_str = [url_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url_str]];

NSData *response = [NSURLConnection sendSynchronousRequest:request  returningResponse:nil error:nil];

NSString *json_string = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding]

NSDictionary *statuses = [parser2 objectWithString:json_string error:nil];

 NSArray *news_array=[[statuses3 objectForKey:@"sold_list"] valueForKey:@"list"];

    for(NSDictionary *news in news_array)
{

    @try {
        [title_arr addObject:[news valueForKey:@"gtitle"]];    //values Add to title array

    }
    @catch (NSException *exception) {

        [title_arr addObject:[NSString stringWithFormat:@""]];
    }

CSS3 background image transition

If animating opacity is not an option, you can also animate background-size.

For example, I used this CSS to set a backgound-image with a delay.

.before {
  background-size: 0;
}

.after {
  transition: background 0.1s step-end;
  background-image: $path-to-image;
  background-size: 20px 20px;
}

CodeIgniter Active Record - Get number of returned rows

function getCount(){
    return $this->db->get('table_name')->num_rows();
}

Is recursion ever faster than looping?

Most answers here forget the obvious culprit why recursion is often slower than iterative solutions. It's linked with the build up and tear down of stack frames but is not exactly that. It's generally a big difference in the storage of the auto variable for each recursion. In an iterative algorithm with a loop, the variables are often held in registers and even if they spill, they will reside in the Level 1 cache. In a recursive algorithm, all intermediary states of the variable are stored on the stack, meaning they will engender many more spills to memory. This means that even if it makes the same amount of operations, it will have a lot memory accesses in the hot loop and what makes it worse, these memory operations have a lousy reuse rate making the caches less effective.

TL;DR recursive algorithms have generally a worse cache behavior than iterative ones.

405 method not allowed Web API

Another possible issue which causes the same behavior is the default parameters in the routing. In my case the controller was located and instantiated correctly, but the POST was blocked because of default Get action specified:

config.Routes.MapHttpRoute(
    name: "GetAllRoute",
    routeTemplate: "api/{controller}.{ext}"/*,
    defaults: new { action = "Get" }*/ // this was causing the issue
);

What's the best way to join on the same table twice?

The first is good unless either Phone1 or (more likely) phone2 can be null. In that case you want to use a Left join instead of an inner join.

It is usually a bad sign when you have a table with two phone number fields. Usually this means your database design is flawed.

SQL how to increase or decrease one for a int column in one command

The single-step answer to the first question is to use something like:

update TBL set CLM = CLM + 1 where key = 'KEY'

That's very much a single-instruction way of doing it.

As for the second question, you shouldn't need to resort to DBMS-specific SQL gymnastics (like UPSERT) to get the result you want. There's a standard method to do update-or-insert that doesn't require a specific DBMS.

try:
    insert into TBL (key,val) values ('xyz',0)
catch:
    do nothing
update TBL set val = val + 1 where key = 'xyz'

That is, you try to do the creation first. If it's already there, ignore the error. Otherwise you create it with a 0 value.

Then do the update which will work correctly whether or not:

  • the row originally existed.
  • someone updated it between your insert and update.

It's not a single instruction and yet, surprisingly enough, it's how we've been doing it successfully for a long long time.

How to add Button over image using CSS?

I like TryingToImprove's answer. I've essentially taken his answer and simplified it down to the barebones css to accomplish the same thing. I think it's a lot easier to chew on.

HTML:

<div class="content">
    <img src="http://placehold.it/182x121"/> 
    <a href="#">Counter-Strike 1.6 Steam</a>
</div>        

CSS:

.content{    
    display:inline-block;
    position:relative;
}

.content a {
    position:absolute;
    bottom:5px;
    right:5px;
}

Working fiddle here.

Calculating powers of integers

No, there is not something as short as a**b

Here is a simple loop, if you want to avoid doubles:

long result = 1;
for (int i = 1; i <= b; i++) {
   result *= a;
}

If you want to use pow and convert the result in to integer, cast the result as follows:

int result = (int)Math.pow(a, b);

Setting maxlength of textbox with JavaScript or jQuery

The max length property is camel-cased: maxLength

jQuery doesn't come with a maxlength method by default. Also, your document ready function isn't technically correct:

$(document).ready(function () {
    $("#ms_num")[0].maxLength = 6;
    // OR:
    $("#ms_num").attr('maxlength', 6);
    // OR you can use prop if you are using jQuery 1.6+:
    $("#ms_num").prop('maxLength', 6);
});

Also, since you are using jQuery, you can rewrite your code like this (taking advantage of jQuery 1.6+):

$('input').each(function (index) {
    var element = $(this);
    if (index === 1) {
        element.prop('maxLength', 3);
    } else if (element.is(':radio') || element.is(':checkbox')) {
        element.prop('maxLength', 5);
    }
});

$(function() {
    $("#ms_num").prop('maxLength', 6);
});

Converting strings to floats in a DataFrame

NOTE: pd.convert_objects has now been deprecated. You should use pd.Series.astype(float) or pd.to_numeric as described in other answers.

This is available in 0.11. Forces conversion (or set's to nan) This will work even when astype will fail; its also series by series so it won't convert say a complete string column

In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))

In [11]: df
Out[11]: 
     A    B
0  1.0  1.0
1    1  foo

In [12]: df.dtypes
Out[12]: 
A    object
B    object
dtype: object

In [13]: df.convert_objects(convert_numeric=True)
Out[13]: 
   A   B
0  1   1
1  1 NaN

In [14]: df.convert_objects(convert_numeric=True).dtypes
Out[14]: 
A    float64
B    float64
dtype: object

Xcode is not currently available from the Software Update server

I solved this by going to the App Store and installing Xcode.

It was a pretty large 11GB install, so this is probably overkill. But, as a last resort, it seems to have solve my issues. In the middle of the installation (well around 10GB), Mac OS told me there was an update to Command Line Tools for Xcode. Performing this installation won't fix anything until Xcode is fully installed.

Once the install is done, it should start working (after you accept the license agreement).

Should I put #! (shebang) in Python scripts, and what form should it take?

If you have more than one version of Python and the script needs to run under a specific version, the she-bang can ensure the right one is used when the script is executed directly, for example:

#!/usr/bin/python2.7

Note the script could still be run via a complete Python command line, or via import, in which case the she-bang is ignored. But for scripts run directly, this is a decent reason to use the she-bang.

#!/usr/bin/env python is generally the better approach, but this helps with special cases.

Usually it would be better to establish a Python virtual environment, in which case the generic #!/usr/bin/env python would identify the correct instance of Python for the virtualenv.

max value of integer

The C language definition specifies minimum ranges for various data types. For int, this minimum range is -32767 to 32767, meaning an int must be at least 16 bits wide. An implementation is free to provide a wider int type with a correspondingly wider range. For example, on the SLES 10 development server I work on, the range is -2147483647 to 2137483647.

There are still some systems out there that use 16-bit int types (All The World Is Not A VAX x86), but there are plenty that use 32-bit int types, and maybe a few that use 64-bit.

The C language was designed to run on different architectures. Java was designed to run in a virtual machine that hides those architectural differences.

SUM OVER PARTITION BY

In my opinion, I think it's important to explain the why behind the need for a GROUP BY in your SQL when summing with OVER() clause and why you are getting repeated lines of data when you are expecting one row per BrandID.

Take this example: You need to aggregate the total sale price of each order line, per specific order category, between two dates, but you also need to retain individual order data in your final results. A SUM() on the SalesPrice column would not allow you to get the correct totals because it would require a GROUP BY, therefore squashing the details because you wouldn't be able to keep the individual order lines in the select statement.

Many times we see a #temp table, @table variable, or CTE filled with the sum of our data and grouped up so we can join to it again later to get a column of the sums we need. This can add processing time and extra lines of code. Instead, use OVER(PARTITION BY ()) like this:

SELECT
  OrderLine, 
  OrderDateTime, 
  SalePrice, 
  OrderCategory,
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

Notice we are not grouping and we have individual order lines column selected. The PARTITION BY in the last column will return us a sales price total for each row of data in each category. What the last column essentially says is, we want the sum of the sale price (SUM(SalePrice)) over a partition of my results and by a specified category (OVER(PARTITION BY CategoryHere)).

If we remove the other columns from our select statement, and leave our final SUM() column, like this:

SELECT
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

The results will still repeat this sum for each row in our original result set. The reason is this method does not require a GROUP BY. If you don't need to retain individual line data, then simply SUM() without the use of OVER() and group up your data appropriately. Again, if you need an additional column with specific totals, you can use the OVER(PARTITION BY ()) method described above without additional selects to join back to.

The above is purely for explaining WHY he is getting repeated lines of the same number and to help understand what this clause provides. This method can be used in many ways and I highly encourage further reading from the documentation here:

Over Clause

JSON.stringify output to div in pretty print way

Please use a <pre> tag

demo : http://jsfiddle.net/K83cK/

_x000D_
_x000D_
var data = {_x000D_
  "data": {_x000D_
    "x": "1",_x000D_
    "y": "1",_x000D_
    "url": "http://url.com"_x000D_
  },_x000D_
  "event": "start",_x000D_
  "show": 1,_x000D_
  "id": 50_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
_x000D_
<pre id="json"></pre>
_x000D_
_x000D_
_x000D_