Programs & Examples On #Restore

Use this tag on any questions related to data restore (in contrast to data recovery).

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

When restoring a backup, how do I disconnect all active connections?

Restarting SQL server will disconnect users. Easiest way I've found - good also if you want to take the server offline.

But for some very wierd reason the 'Take Offline' option doesn't do this reliably and can hang or confuse the management console. Restarting then taking offline works

Sometimes this is an option - if for instance you've stopped a webserver that is the source of the connections.

How to take backup of a single table in a MySQL database?

just use mysqldump -u root database table or if using with password mysqldump -u root -p pass database table

What is the correct way to restore a deleted file from SVN?

With Tortoise SVN:

If you haven't committed your changes yet, you can do a revert on the parent folder where you deleted the file or directory.

If you have already committed the deleted file, then you can use the repository browser, change to the revision where the file still existed and then use the command Copy to... from the context menu. Enter the path to your working copy as the target and the deleted file will be copied from the repository to your working copy.

How to restore to a different database in sql server?

Actually, there is no need to restore the database in native SQL Server terms, since you "want to fiddle with some data" and "browse through the data of that .bak file"

You can use ApexSQL Restore – a SQL Server tool that attaches both native and natively compressed SQL database backups and transaction log backups as live databases, accessible via SQL Server Management Studio, Visual Studio or any other third-party tool. It allows attaching single or multiple full, differential and transaction log backups

Moreover, I think that you can do the job while the tool is in fully functional trial mode (14 days)

Disclaimer: I work as a Product Support Engineer at ApexSQL

SQL Server Restore Error - Access is Denied

I had the same problem but I used sql server 2008 r2, you must check in options and verify the paths where sql going to save the files .mdf and .ldf you must select the path of your sql server installation. I solved my problem with this, I hope it helps you.

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

SQL Server: Database stuck in "Restoring" state

I had a similar issue with restoring using SQL Management Studio. I tried to restore a backup of the database to a new one with a different name. At first this failed and after fixing the new database's file names it was successfully performed - in any case the issue I'm describing re-occurred even if I got this right from the first time. So, after the restoration, the original database remained with a (Restoring...) next to its name. Considering the answers of the forum above (Bhusan's) I tried running in the query editor on the side the following:

RESTORE DATABASE "[NAME_OF_DATABASE_STUCK_IN_RESTORING_STATE]"

which fixed the issue. I was having trouble at first because of the database name which contained special characters. I resolved this by adding double quotes around - single quotes wouldn't work giving an "Incorrect syntax near ..." error.

This was the minimal solution I've tried to resolve this issue (stuck database in restoring state) and I hope it can be applied to more cases.

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

Cannot open backup device 'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup\ C:\HostingSpaces\dbname_jun14_2010_new.bak'

The error is quite self-explanatory. The file C:\program files\...\Backup \c:\Hosting...\ is incorrectly formatted. This is quite obvious if you inspect the file name. Perhaps ommit the extra space in your backup statement?

BACKUP DATABASE go4sharepoint_1384_8481 
TO DISK='C:\HostingSpaces\dbname_jun14_2010_new.bak' with FORMAT

Note there is no space between ' and C:

Can I restore a single table from a full mysql mysqldump file?

You can import single table using terminal line as given below. Here import single user table into specific database.

mysql -u root -p -D my_database_name < var/www/html/myproject/tbl_user.sql

Restore a postgres backup file using the command line?

Backup:  $ pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

Restore: $ psql -U {user-name} -d {desintation_db} -f {dumpfilename.sql}

Restoring MySQL database from physical files

I have the same problem but was not able to successfully recover the database, based on the instructions above.

I was only able to recover mysql database folders from my Ubuntu OS. My problem is how to recover my database with those unreadable mysql data folders. So I switched back to win7 OS for development environment.

*NOTE I have an existing database server running in win7 and I only need few database files to retrieve from the recovered files. To successfully recover the database files from Ubuntu OS I need to freshly install mysql database server (same version from Ubuntu OS in my win7 OS) to recover everything in that old database server.

  1. Make another new mysql database server same version from the recovered files.

  2. Stop the mysql server

  3. copy the recovered folder and paste in the (C:\ProgramData\MySQL\MySQL Server 5.5\data) mysql database is stored.

  4. copy the ibdata1 file located in linux mysql installed folder and paste it in (C:\ProgramData\MySQL\MySQL Server 5.5\data). Just overwrite the existing or make backup before replacing.

  5. start the mysql server and check if you have successfully recovered the database files.

  6. To use the recovered database in my currently used mysql server simply export the recovered database and import it my existing mysql server.

Hope these will help, because nothing else worked for me.

"No backupset selected to be restored" SQL Server 2012

I had the same issue with SQL Server 2014 (Management Studio could not see the folder in which the backup file resided, when attempting to locate it for a Restore operation). This thread held the answer that solved my problem. Quote:

The SQL Server service account can be found by Start->Control Panel->Administrative Tools->Services. Double-click on the SQL Server service->Log On tab. You'll either be using the "Local System account" or "This account" to define a specific account. If you are using the Local System account, you won't be able to reference backups that are not local to the server. If, instead, you have defined the account to use, this is the account that needs to have access to the backup file location. Your ability to access the backups using your personal logon is irrelevant; it is the SQL Server account that is used, even though you are initiating the backup. Your IT people should be able to determine what rights are granted to each account.

Hope that helps someone.

How to upload a file to directory in S3 bucket using boto

I used this and it is very simple to implement

import tinys3

conn = tinys3.Connection('S3_ACCESS_KEY','S3_SECRET_KEY',tls=True)

f = open('some_file.zip','rb')
conn.upload('some_file.zip',f,'my_bucket')

https://www.smore.com/labs/tinys3/

Replacing few values in a pandas dataframe column with another value

The easiest way is to use the replace method on the column. The arguments are a list of the things you want to replace (here ['ABC', 'AB']) and what you want to replace them with (the string 'A' in this case):

>>> df['BrandName'].replace(['ABC', 'AB'], 'A')
0    A
1    B
2    A
3    D
4    A

This creates a new Series of values so you need to assign this new column to the correct column name:

df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')

How to "inverse match" with regex?

What language are you using? The capabilities and syntax of the regex implementation matter for this.

You could use look-ahead. Using python as an example

import re

not_andrea = re.compile('(?!Andrea)\w{6}', re.IGNORECASE)

To break that down:

(?!Andrea) means 'match if the next 6 characters are not "Andrea"'; if so then

\w means a "word character" - alphanumeric characters. This is equivalent to the class [a-zA-Z0-9_]

\w{6} means exactly 6 word characters.

re.IGNORECASE means that you will exclude "Andrea", "andrea", "ANDREA" ...

Another way is to use your program logic - use all lines not matching Andrea and put them through a second regex to check for 6 characters. Or first check for at least 6 word characters, and then check that it does not match Andrea.

Export/import jobs in Jenkins

Probably use jenkins command line is another option, see https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI

  • create-job: Creates a new job by reading stdin as a configuration XML file.
  • get-job: Dumps the job definition XML to stdout

So you can do

java -jar jenkins-cli.jar -s http://server get-job myjob > myjob.xml
java -jar jenkins-cli.jar -s http://server create-job newmyjob < myjob.xml

It works fine for me and I am used to store in inside my version control system

How do I get JSON data from RESTful service using Python?

If you desire to use Python 3, you can use the following:

import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
    result = json.loads(response.readall().decode('utf-8'))

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

first-child and last-child with IE8

If your table is only 2 columns across, you can easily reach the second td with the adjacent sibling selector, which IE8 does support along with :first-child:

.editor td:first-child
{
    width: 150px; 
}

.editor td:first-child + td input,
.editor td:first-child + td textarea
{
    width: 500px;
    padding: 3px 5px 5px 5px;
    border: 1px solid #CCC; 
}

Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td, as suggested by James Allardice.

jQuery click not working for dynamically created items

I faced this problem a few days ago - the solution for me was to use .bind() to bind the required function to the dynamically created link.

var catLink = $('<a href="#" id="' + i + '" class="lnkCat">' + category.category + '</a>');
catLink.bind("click", function(){
 $.categories.getSubCategories(this);
});

getSubCategories : function(obj) {
 //do something
}

I hope this helps.

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

Scrolling a flexbox with overflowing content

You can use a position: absolute inside a position: relative

https://codepen.io/Iquixe/pen/RwRzGrM

Mysql - How to quit/exit from stored procedure

This works for me :

 CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
IN bus_fun_temp_id int  , OUT o_message VARCHAR (50) ,
            OUT o_number INT )
 BEGIN

DECLARE  v_pkg_name  varchar(50) ;

DECLARE  v_pkg_temp_id  int(10)  ; 

DECLARE  v_workflow_count INT(10);

-- checking if workflow created for package
select count(*)  INTO v_workflow_count from workflow w where w.package_id = 
package_id ;

this_proc:BEGIN   -- this_proc block start here 

 IF  v_workflow_count = 0 THEN
   select 'no work flow ' as 'workflow_status' ;
    SET o_message ='Work flow is not created for this package.';
    SET  o_number = -2 ;
      LEAVE this_proc;
 END IF;

select 'work flow  created ' as 'workflow_status' ;
-- To  send some message
SET o_message ='SUCCESSFUL';
SET  o_number = 1 ;

  END ;-- this_proc block end here 

END

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

Checking if a variable is an integer

You can use the is_a? method

>> 1.is_a? Integer
=> true
>> "[email protected]".is_a? Integer
=> false
>> nil.is_a? Integer
=> false

Developing C# on Linux

Now Microsoft is migrating to open-source - see CoreFX (GitHub).

keyCode values for numeric keypad?

For the people that want a CTRL+C, CTRL-V solution, here you go:

    /**
     * Retrieves the number that was pressed on the keyboard.
     *
     * @param {Event} event The keypress event containing the keyCode.
     * @returns {number|null} a number between 0-9 that was pressed. Returns null if there was no numeric key pressed.
     */
    function getNumberFromKeyEvent(event) {
        if (event.keyCode >= 96 && event.keyCode <= 105) {
            return event.keyCode - 96;
        } else if (event.keyCode >= 48 && event.keyCode <= 57) {
            return event.keyCode - 48;
        }
        return null;
    }

It uses the logic of the first answer.

PHP DOMDocument loadHTML not encoding UTF-8 correctly

Use it for correct result

$dom = new DOMDocument();
$dom->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . $profile);
echo $dom->saveHTML();
echo $profile;

This operation

mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8');

It is bad way, because special symbols like &lt ; , &gt ; can be in $profile, and they will not convert twice after mb_convert_encoding. It is the hole for XSS and incorrect HTML.

Server unable to read htaccess file, denying access to be safe

In linux,

find project_directory_name_here -type d -exec chmod 755 {} \;
find project_directory_name_here -type f -exec chmod 644 {} \;

It will replace all files and folder permission of project_directory_name_here and its inside stuff.

CSS force new line

or you can use:

a {
    display: inline-block;
  }

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Hiding table data using <div style="display:none">

Give all the rows you want to hide a class name that you can use for hiding. Use javascript to add/remove this class from the different rows.

<table>
<tr><th>Test Table</th><tr>
<tr class="toHide"><td>123456789</td><tr>
<tr class="toHide"><td>123456789</td><tr>
<tr class="toHide"><td>123456789</td><tr>
</table>

CSS:

.toHide
{
 display: none;
}

position: fixed doesn't work on iPad and iPhone

now apple support that

overflow:hidden;
-webkit-overflow-scrolling:touch;

Angular - ui-router get previous state

I use resolve to save the current state data before moving to the new state:

angular.module('MyModule')
.config(['$stateProvider', function ($stateProvider) {
    $stateProvider
        .state('mystate', {
            templateUrl: 'mytemplate.html',
            controller: ["PreviousState", function (PreviousState) {
                if (PreviousState.Name == "mystate") {
                    // ...
                }
            }],
            resolve: {
                PreviousState: ["$state", function ($state) {
                    var currentStateData = {
                        Name: $state.current.name,
                        Params: $state.params,
                        URL: $state.href($state.current.name, $state.params)
                    };
                    return currentStateData;
                }]
            }
        });
}]);

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Yes, it's possible, the syntax is curl [protocol://]<host>[:port], for example:

curl example.com:1234

If you're using Bash, you can also use pseudo-device /dev files to open a TCP connection, e.g.:

exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.

See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).

Python slice first and last element in list

first, last = some_list[0], some_list[-1]

Match at every second occurrence

There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a that match up to the second "a".

The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.

EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!

Change header text of columns in a GridView

I Think this Works:

 testGV.HeaderRow.Cells[0].Text="Date"

CSS - Syntax to select a class within an id

#navigation .navigationLevel2 li
{
    color: #f00;
}

jQuery-- Populate select from json

I would do something like this:

$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

JSON structure would be appreciated. At first you can experiment with find('element') - it depends on JSON.

Fastest method to escape HTML tags as HTML entities?

Martijn's method as a prototype function:

String.prototype.escape = function() {
    var tagsToReplace = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;'
    };
    return this.replace(/[&<>]/g, function(tag) {
        return tagsToReplace[tag] || tag;
    });
};

var a = "<abc>";
var b = a.escape(); // "&lt;abc&gt;"

How do I uniquely identify computers visiting my web site?

The suggestions to use cookies aside, the only comprehensive set of identifying attributes available to interrogate are contained in the HTTP request header. So it is possible to use some subset of these to create a pseudo-unique identifier for a user agent (i.e., browser). Further, most of this information is possibly already being logged in the so-called "access log" of your web server software by default and, if not, can be easily configured to do so. Then, a utlity could be developed that simply scans the content of this log, creating fingerprints of each request comprised of, say, the IP address and User Agent string, etc. The more data available, even including the contents of specific cookies, adds to the quality of the uniqueness of this fingerprint. Though, as many others have stated already, the HTTP protocol doesn't make this 100% foolproof - at best it can only be a fairly good indicator.

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

I have the same error than you.

npm uninstall webpack --save-dev

&

npm install [email protected] --save-dev

solve it!.

Classes residing in App_Code is not accessible

Go to the page from where you want to access the App_code class, and then add the namespace of the app_code class. You need to provide a using statement, as follows:

using WebApplication3.App_Code;

After that, you will need to go to the app_code class property and set the 'Build Action' to 'Compile'.

How to check if a subclass is an instance of a class at runtime?

Maybe I'm missing something, but wouldn't this suffice:

if (view instanceof B) {
    // this view is an instance of B
}

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:

File                             Thread Safe         VC Bulid
php_sqlsrv_53_nts_vc6.dll           No                  VC6
php_sqlsrv_53_nts_vc9.dll           No                  VC9
php_sqlsrv_53_ts_vc6.dll            Yes                 VC6
php_sqlsrv_53_ts_vc9.dll            Yes                 VC9

You can see the Thread Safety status in phpinfo().

Add the correct file to your ext directory and the following line to your php.ini:

extension=php_sqlsrv_53_*_vc*.dll

Use the filename of the file you used.

As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*

Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.

In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2

To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.

Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.

Why Doesn't C# Allow Static Methods to Implement an Interface?

My (simplified) technical reason is that static methods are not in the vtable, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.

For the political reason, I'll quote Eric Lippert (who is a compiler wonk, and holds a Bachelor of Mathematics, Computer science and Applied Mathematics from University of Waterloo (source: LinkedIn):

...the core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.

Note that Lippert does leave room for a so-called type method:

That is, a method associated with a type (like a static), which does not take a non-nullable “this” argument (unlike an instance or virtual), but one where the method called would depend on the constructed type of T (unlike a static, which must be determinable at compile time).

but is yet to be convinced of its usefulness.

How can I require at least one checkbox be checked before a form can be submitted?

Here's an example using jquery and your html.

<html>
<head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
$(document).ready(function () {
    $('#checkBtn').click(function() {
      checked = $("input[type=checkbox]:checked").length;

      if(!checked) {
        alert("You must check at least one checkbox.");
        return false;
      }

    });
});

</script>

<p>Box Set 1</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>
<p>Box Set 2</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 5" required><label>Box 5</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 6" required><label>Box 6</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 7" required><label>Box 7</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 8" required><label>Box 8</label></li>
</ul>
<p>Box Set 3</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 9" required><label>Box 9</label></li>
</ul>
<p>Box Set 4</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 10" required><label>Box 10</label></li>
</ul>

<input type="button" value="Test Required" id="checkBtn">

</body>
</html>

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

For another instance of Glibc, download gcc 4.7.2, for instance from this github repo (although an official source would be better) and extract it to some folder, then update LD_LIBRARY_PATH with the path where you have extracted glib.

export LD_LIBRARY_PATH=$glibpath/glib-2.49.4-kgesagxmtbemim2denf65on4iixy3miy/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/libffi-3.2.1-wk2luzhfdpbievnqqtu24pi774esyqye/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/pcre-8.39-itdbuzevbtzqeqrvna47wstwczud67wx/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/gettext-0.19.8.1-aoweyaoufujdlobl7dphb2gdrhuhikil/lib:$LD_LIBRARY_PATH

This should keep you safe from bricking your CentOS*.

*Disclaimer: I just completed the thought it looks like the OP was trying to express, but I don't fully agree.

android ellipsize multiline textview

I have had the same Problem. I fixed it by just deleting android:ellipsize="marquee"

Cmake doesn't find Boost

There is more help available by reading the FindBoost.cmake file itself. It is located in your 'Modules' directory.

A good start is to set(Boost_DEBUG 1) - this will spit out a good deal of information about where boost is looking, what it's looking for, and may help explain why it can't find it.

It can also help you to figure out if it is picking up on your BOOST_ROOT properly.

FindBoost.cmake also sometimes has problems if the exact version of boost is not listed in the Available Versions variables. You can find more about this by reading FindBoost.cmake.

Lastly, FindBoost.cmake has had some bugs in the past. One thing you might try is to take a newer version of FindBoost.cmake out of the latest version of CMake, and stick it into your project folder alongside CMakeLists.txt - then even if you have an old version of boost, it will use the new version of FindBoost.cmake that is in your project's folder.

Good luck.

How to only find files in a given directory, and ignore subdirectories using bash

find /dev -maxdepth 1 -name 'abc-*'

Does not work for me. It return nothing. If I just do '.' it gives me all the files in directory below the one I'm working in on.

find /dev -maxdepth 1 -name "*.root" -type 'f' -size +100k -ls

Return nothing with '.' instead I get list of all 'big' files in my directory as well as the rootfiles/ directory where I store old ones.

Continuing. This works.

find ./ -maxdepth 1 -name "*.root" -type 'f' -size +100k -ls
564751   71 -rw-r--r--   1 snyder   bfactory   115739 May 21 12:39 ./R24eTightPiPi771052-55.root
565197  105 -rw-r--r--   1 snyder   bfactory   150719 May 21 14:27 ./R24eTightPiPi771106-2.root
565023   94 -rw-r--r--   1 snyder   bfactory   134180 May 21 12:59 ./R24eTightPiPi77999-109.root
719678   82 -rw-r--r--   1 snyder   bfactory   121149 May 21 12:42 ./R24eTightPiPi771098-10.root
564029  140 -rw-r--r--   1 snyder   bfactory   170181 May 21 14:14 ./combo77v.root

Apparently /dev means directory of interest. But ./ is needed, not just .. The need for the / was not obvious even after I figured out what /dev meant more or less.

I couldn't respond as a comment because I have no 'reputation'.

Angular2 QuickStart npm start is not working correctly

Go to https://github.com/npm/npm/issues/14075 address. And try juaniliska's answer. Maybe help you.

npm config get registry

npm cache clean

npm install

jQuery bind to Paste Event, how to get the content of the paste

$(document).ready(function() {
    $("#editor").bind('paste', function (e){
        $(e.target).keyup(getInput);
    });

    function getInput(e){
        var inputText = $(e.target).html(); /*$(e.target).val();*/
        alert(inputText);
        $(e.target).unbind('keyup');
    }
});

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

1.redirect return the request to the browser from server,then resend the request to the server from browser.

2.forward send the request to another servlet (servlet to servlet).

"ssl module in Python is not available" when installing package with pip3

I had the same issue trying to install python3.7 on an ubuntu14.04 machine. The issue was that I had some custom folders in my PKG_CONFIG_PATH and in my LD_LIBRARY_PATH, which prevented the python build process to find the system openssl libraries.

so try to clear them and see what happens:

export PKG_CONFIG_PATH=""
export LD_LIBRARY_PATH=""

json call with C#

just continuing what @Mulki made with his code

public string WebRequestinJson(string url, string postData)
{
    string ret = string.Empty;

    StreamWriter requestWriter;

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        webRequest.ContentType = "application/json";
        //POST the data.
        using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }
    }

    HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
    Stream resStream = resp.GetResponseStream();
    StreamReader reader = new StreamReader(resStream);
    ret = reader.ReadToEnd();

    return ret;
}

Android Studio Run/Debug configuration error: Module not specified

I struggled with this because I'm developing a library, and every now and then want to run it as an application.

From app/build.gradle, check that you have apply plugin: 'com.android.application' instead of apply plugin: 'com.android.library'.

You should also have this in app/build.gradle:

defaultConfig { applicationId "com.your_company.your_application" ... }

Finally run Gradle sync.

X-Frame-Options on apache

  1. You can add to .htaccess, httpd.conf or VirtualHost section
  2. Header set X-Frame-Options SAMEORIGIN this is the best option

Allow from URI is not supported by all browsers. Reference: X-Frame-Options on MDN

How to change package name of Android Project in Eclipse?

Press F2 and then rename it (or right click on the project and select Rename). It changes wherever that package is declared in your project. It's automatically renamed all over.

db.collection is not a function when using MongoClient v3.0

If someone is still trying how to resolve this error, I have done this like below.

const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mytestingdb';

const retrieveCustomers = (db, callback)=>{
    // Get the customers collection
    const collection = db.collection('customers');
    // Find some customers
    collection.find({}).toArray((err, customers) =>{
        if(err) throw err;
      console.log("Found the following records");
      console.log(customers)
      callback(customers);
    });
}

const retrieveCustomer = (db, callback)=>{
    // Get the customers collection
    const collection = db.collection('customers');
    // Find some customers
    collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
        if(err) throw err;
      console.log("Found the following records");
      console.log(customers)
      callback(customers);
    });
}

const insertCustomers = (db, callback)=> {
    // Get the customers collection
    const collection = db.collection('customers');
    const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
    // Insert some customers
    collection.insertMany(dataArray, (err, result)=> {
        if(err) throw err;
        console.log("Inserted 3 customers into the collection");
        callback(result);
    });
}

// Use connect method to connect to the server
MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
  console.log("Connected successfully to server");
  const db = client.db(dbName);
  insertCustomers(db, ()=> {
    retrieveCustomers(db, ()=> {
        retrieveCustomer(db, ()=> {
            client.close();
        });
    });
  });
});

What is the default font of Sublime Text?

On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:

  1. go to View menu and select Show Console
  2. Then enter this command: view.settings().get('font_face')

You will find your default font.

How to convert an Image to base64 string in java?

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");

Twitter Bootstrap dropdown menu

It actually requires inclusion of Twitter Bootstrap's dropdown.js

http://getbootstrap.com/2.3.2/components.html

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

How do I restart a service on a remote machine in Windows?

Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:

Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).

Right click on your computer name and choose "Connect to Remote Computer"

Put in the computer name and credentials and you have full access to many admin functions including the services control panel.

Wordpress plugin install: Could not create directory

wordpressProject is the project name.

/var/www/html/wordpressProject sudo chmod -R 777 wp-content

Thanks. It will work.

Getting Error "Form submission canceled because the form is not connected"

I was able to get rid of the message by using adding the attribute type="button" to the button element in vue.

How to remove a character at the end of each line in unix

alternative commands that does same job

tr -d ",$" < infile
awk 'gsub(",$","")' infile

JSON post to Spring Controller

You need to include the getters and setters for all the fields that have been defined in the model Test class --

public class Test implements Serializable {

    private static final long serialVersionUID = -1764970284520387975L;

    public String name;

    public Test() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Android - styling seek bar

output:

enter image description here

Change Progress Color:

int normalColor = ContextCompat.getColor(context, R.color.normal_color);
int selectedColor = ContextCompat.getColor(context, R.color.selected_color);
Drawable normalDrawable = new ColorDrawable(normalColor);
Drawable selectedDrawable = new ColorDrawable(selectedColor);
ClipDrawable clipDrawable = new ClipDrawable(selectedDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
Drawable[] layers = {normalDrawable, clipDrawable, clipDrawable};
LayerDrawable seekbarDrawable = new LayerDrawable(layers);
seekBar.setProgressDrawable(seekbarDrawable);

Change Thumb Color:

int thumbColor = ContextCompat.getColor(context, R.color.thumb_color);
Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_seekbar_thumb);
assert unwrappedDrawable != null;
Drawable wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(wrappedDrawable, thumbColor);
seekBar.setThumb(wrappedDrawable);

How to check if a file contains a specific string using Bash

In case you want to checkif the string matches the whole line and if it is a fixed string, You can do it this way

grep -Fxq [String] [filePath]

example

 searchString="Hello World"
 file="./test.log"
 if grep -Fxq "$searchString" $file
    then
            echo "String found in $file"
    else
            echo "String not found in $file"
 fi

From the man file:

-F, --fixed-strings

          Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of 

which is to be matched.
          (-F is specified by POSIX.)
-x, --line-regexp
          Select only those matches that exactly match the whole line.  (-x is specified by 

POSIX.)
-q, --quiet, --silent
          Quiet; do not write anything to standard output.  Exit immediately with zero 

status  if  any  match  is
          found,  even  if  an error was detected.  Also see the -s or --no-messages 

option.  (-q is specified by
          POSIX.)

How do I use method overloading in Python?

I write my answer in Python 2.7:

In Python, method overloading is not possible; if you really want access the same function with different features, I suggest you to go for method overriding.

class Base(): # Base class
    '''def add(self,a,b):
        s=a+b
        print s'''

    def add(self,a,b,c):
        self.a=a
        self.b=b
        self.c=c

        sum =a+b+c
        print sum

class Derived(Base): # Derived class
    def add(self,a,b): # overriding method
        sum=a+b
        print sum



add_fun_1=Base() #instance creation for Base class
add_fun_2=Derived()#instance creation for Derived class

add_fun_1.add(4,2,5) # function with 3 arguments
add_fun_2.add(4,2)   # function with 2 arguments

Oracle Differences between NVL and Coalesce

Actually I cannot agree to each statement.

"COALESCE expects all arguments to be of same datatype."

This is wrong, see below. Arguments can be different data types, that is also documented: If all occurrences of expr are numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type, then Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type.. Actually this is even in contradiction to common expression "COALESCE stops at first occurrence of a non-Null value", otherwise test case No. 4 should not raise an error.

Also according to test case No. 5 COALESCE does an implicit conversion of arguments.

DECLARE
    int_val INTEGER := 1;
    string_val VARCHAR2(10) := 'foo';
BEGIN

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '1. NVL(int_val,string_val) -> '|| NVL(int_val,string_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('1. NVL(int_val,string_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '2. NVL(string_val, int_val) -> '|| NVL(string_val, int_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('2. NVL(string_val, int_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '3. COALESCE(int_val,string_val) -> '|| COALESCE(int_val,string_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('3. COALESCE(int_val,string_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '4. COALESCE(string_val, int_val) -> '|| COALESCE(string_val, int_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('4. COALESCE(string_val, int_val) -> '||SQLERRM ); 
    END;

    DBMS_OUTPUT.PUT_LINE( '5. COALESCE(SYSDATE,SYSTIMESTAMP) -> '|| COALESCE(SYSDATE,SYSTIMESTAMP) );

END;
Output:

1. NVL(int_val,string_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
2. NVL(string_val, int_val) -> foo
3. COALESCE(int_val,string_val) -> 1
4. COALESCE(string_val, int_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
5. COALESCE(SYSDATE,SYSTIMESTAMP) -> 2016-11-30 09:55:55.000000 +1:0 --> This is a TIMESTAMP value, not a DATE value!

android.os.NetworkOnMainThreadException with android 4.2

This is the correct way:

public class JSONParser extends AsyncTask <String, Void, String>{

    static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}
@Override
protected String doInBackground(String... params) {


    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

            HttpResponse getResponse = httpClient.execute(httpPost);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();

        //HttpResponse httpResponse = httpClient.execute(httpPost);
        //HttpEntity httpEntity = httpResponse.getEntity();
        is = getResponseEntity.getContent();            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IO", e.getMessage().toString());
        e.printStackTrace();

    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;


}
protected void onPostExecute(String page)
{   
    //onPostExecute
}   
}

To call it (from main):

mJSONParser = new JSONParser();
mJSONParser.execute();

How do I detect if Python is running as a 64-bit application?

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize on Python 2.6, 2.7, Python 3.x.

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

How to check if an integer is within a range of numbers in PHP?

The expression:

 ($min <= $value) && ($value <= $max)

will be true if $value is between $min and $max, inclusively

See the PHP docs for more on comparison operators

How to set and reference a variable in a Jenkinsfile

A complete example for scripted pipepline:

       stage('Build'){
            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash build.sh'
            }
        }

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

How to replace NaNs by preceding values in pandas DataFrame?

In my case, we have time series from different devices but some devices could not send any value during some period. So we should create NA values for every device and time period and after that do fillna.

df = pd.DataFrame([["device1", 1, 'first val of device1'], ["device2", 2, 'first val of device2'], ["device3", 3, 'first val of device3']])
df.pivot(index=1, columns=0, values=2).fillna(method='ffill').unstack().reset_index(name='value')

Result:

        0   1   value
0   device1     1   first val of device1
1   device1     2   first val of device1
2   device1     3   first val of device1
3   device2     1   None
4   device2     2   first val of device2
5   device2     3   first val of device2
6   device3     1   None
7   device3     2   None
8   device3     3   first val of device3

json_decode to array

This is a late contribution, but there is a valid case for casting json_decode with (array).
Consider the following:

$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
    echo $v; // etc.
}

If $jsondata is ever returned as an empty string (as in my experience it often is), json_decode will return NULL, resulting in the error Warning: Invalid argument supplied for foreach() on line 3. You could add a line of if/then code or a ternary operator, but IMO it's cleaner to simply change line 2 to ...

$arr = (array) json_decode($jsondata,true);

... unless you are json_decodeing millions of large arrays at once, in which case as @TCB13 points out, performance could be negatively effected.

How to capture a list of specific type with mockito

If you're not afraid of old java-style (non type safe generic) semantics, this also works and is simple'ish:

ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(subject.method(argument.capture()); // run your code
List<SomeType> list = argument.getValue(); // first captured List, etc.

Invoke native date picker from web-app on iOS/Android

In HTML:

  <form id="my_form"><input id="my_field" type="date" /></form>

In JavaScript

_x000D_
_x000D_
   // test and transform if needed_x000D_
    if($('#my_field').attr('type') === 'text'){_x000D_
        $('#my_field').attr('type', 'text').attr('placeholder','aaaa-mm-dd');  _x000D_
    };_x000D_
_x000D_
    // check_x000D_
    if($('#my_form')[0].elements[0].value.search(/(19[0-9][0-9]|20[0-1][0-5])[- \-.](0[1-9]|1[012])[- \-.](0[1-9]|[12][0-9]|3[01])$/i) === 0){_x000D_
        $('#my_field').removeClass('bad');_x000D_
    } else {_x000D_
        $('#my_field').addClass('bad');_x000D_
    };
_x000D_
_x000D_
_x000D_

How do I import a .sql file in mysql database using PHP?

As we all know MySQL was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 ref so I have converted accepted answer to mysqli.

<?php
// Name of the file
$filename = 'db.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '123456';
// Database name
$mysql_database = 'mydb';

$connection = mysqli_connect($mysql_host,$mysql_username,$mysql_password,$mysql_database) or die(mysqli_error($connection));

// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
    continue;

// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
    // Perform the query
    mysqli_query($connection,$templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}
 echo "Tables imported successfully";
?>

How do I find the version of Apache running without access to the command line?

The method

Connect to port 80 on the host and send it

HEAD / HTTP/1.0

This needs to be followed by carriage-return + line-feed twice

You'll get back something like this

HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 12:39:43 GMT
Server: Apache/2.2.9 (Ubuntu) DAV/2 SVN/1.5.0 PHP/5.2.6-1ubuntu4 with Suhosin-Patch mod_perl/2.0.4 Perl/v5.10.0
Last-Modified: Thu, 02 Aug 2007 20:50:09 GMT
ETag: "438118-197-436bd96872240"
Accept-Ranges: bytes
Content-Length: 407
Connection: close
Content-Type: text/html; charset=UTF-8

You can then extract the apache version from the Server: header

Typical tools you can use

You could use the HEAD utility which comes with a full install of Perl's LWP library, e.g.

HEAD http://your.webserver.com/

Or, use the curl utility, e.g.

 curl --head http://your.webserver.com/

You could also use a browser extension which lets you view server headers, such as Live HTTP Headers or Firebug for Firefox, or Fiddler for IE

Stuck with Windows?

Finally. if you're on Windows, and have nothing else at your disposal, open a command prompt (Start Menu->Run, type "cmd" and press return), and then type this

telnet your.webserver.com 80

Then type (carefully, your characters won't be echoed back)

HEAD / HTTP/1.0

Press return twice and you'll see the server headers.

Other methods

As mentioned by cfeduke and Veynom, the server may be set to return limited information in the Server: header. Try and upload a PHP script to your host with this in it

<?php phpinfo() ?>

Request the page with a web browser and you should see the Apache version reported there.

You could also try and use PHPShell to have a poke around, try a command like

/usr/sbin/apache2 -V

ZIP file content type for HTTP request

.zip    application/zip, application/octet-stream

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

Since this is the first Google result for 'pandas new column from others', here's a simple example:

import pandas as pd

# make a simple dataframe
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
df
#    a  b
# 0  1  3
# 1  2  4

# create an unattached column with an index
df.apply(lambda row: row.a + row.b, axis=1)
# 0    4
# 1    6

# do same but attach it to the dataframe
df['c'] = df.apply(lambda row: row.a + row.b, axis=1)
df
#    a  b  c
# 0  1  3  4
# 1  2  4  6

If you get the SettingWithCopyWarning you can do it this way also:

fn = lambda row: row.a + row.b # define a function for the new column
col = df.apply(fn, axis=1) # get column data with an index
df = df.assign(c=col.values) # assign values to column 'c'

Source: https://stackoverflow.com/a/12555510/243392

And if your column name includes spaces you can use syntax like this:

df = df.assign(**{'some column name': col.values})

And here's the documentation for apply, and assign.

Secondary axis with twinx(): how to add to legend?

I'm not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

pi = np.pi

# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
        * np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')

# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

Can I pass a JavaScript variable to another browser window?

Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.

I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.

Replace multiple whitespaces with single whitespace in JavaScript string

Here's a non-regex solution (just for fun):

_x000D_
_x000D_
var s = ' a   b   word word. word, wordword word   ';

// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"

// or ES2015:
s = s.split(' ').filter(n => n).join(' '); 
console.log(s); // "a b word word. word, wordword word"
_x000D_
_x000D_
_x000D_

Can even substitute filter(n => n) with .filter(String)

It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.

How to keep the spaces at the end and/or at the beginning of a String?

There is possible to space with different widths:

<string name="space_demo">|&#x20;|&#x2009;|&#x200A;||</string>

| SPACE | THIN SPACE | HAIR SPACE | no space |

Visualisation:

enter image description here

What is the definition of "interface" in object oriented programming

In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.

In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).

As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.

How to display a date as iso 8601 format with PHP

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

How can I use onItemSelected in Android?

Another thing: When you have more than one spinner in your layout, you have to implement a switch selection in the onItemSlected() method to know which widget was clicked. Something like this:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    switch (parent.getId()){
        case R.id.sp_alarmSelection:
            //Do something
            Toast.makeText(this, "Alarm Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.sp_optionSelection:
            //Do another thing 
            Toast.makeText(this, "Option Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            break;
    }
}

Are HTTP cookies port specific?

In IE 8, cookies (verified only against localhost) are shared between ports. In FF 10, they are not.

I've posted this answer so that readers will have at least one concrete option for testing each scenario.

How to open an elevated cmd using command line for Windows?

I use nirsoft programs (eg nircmdc) and sysinternals (eg psexec) all the time. They are very helpful.

But if you don't want to, or can't, dl a 3rd party program, here's another way, pure Windows.

Short answer: you can while elevated create a scheduled task with elevated privileges which you can then invoke later while not elevated.

Middle-length answer: while elevated create task with (but I prefer task scheduler GUI):

schtasks /create /sc once /tn cmd_elev /tr cmd /rl highest /st 00:00

Then later, no elevation needed, invoke with

schtasks /run /tn cmd_elev

Long answer: There's a lot of fidgety details; see my blog entry "Start program WITHOUT UAC, useful at system start and in batch files (use task scheduler)"

How to map with index in Ruby?

I have always enjoyed the syntax of this style:

a = [1, 2, 3, 4]
a.each_with_index.map { |el, index| el + index }
# => [1, 3, 5, 7]

Invoking each_with_index gets you an enumerator you can easily map over with your index available.

C++ queue - simple example

std::queue<myclass*> that's it

How can a LEFT OUTER JOIN return more records than exist in the left table?

Each record from the left table will be returned as many times as there are matching records on the right table -- at least 1, but could easily be more than 1.

Uploading Files in ASP.net without using the FileUpload server control

You'll have to set the enctype attribute of the form to multipart/form-data; then you can access the uploaded file using the HttpRequest.Files collection.

Difference between a View's Padding and Margin

Padding is the space inside the border, between the border and the actual view's content. Note that padding goes completely around the content: there is padding on the top, bottom, right and left sides (which can be independent).

Margins are the spaces outside the border, between the border and the other elements next to this view. In the image, the margin is the grey area outside the entire object. Note that, like the padding, the margin goes completely around the content: there are margins on the top, bottom, right, and left sides.

An image says more than 1000 words (extracted from Margin Vs Padding - CSS Properties):

alt text

Where is body in a nodejs http.get response?

http.request docs contains example how to receive body of the response through handling data event:

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

http.get does the same thing as http.request except it calls req.end() automatically.

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/index.html'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  res.on("data", function(chunk) {
    console.log("BODY: " + chunk);
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

Sort objects in an array alphabetically on one property of the array

Shorter code with ES6

objArray.sort((a, b) => a.DepartmentName.toLowerCase().localeCompare(b.DepartmentName.toLowerCase()))

How to install grunt and how to build script with it

Some time we need to set PATH variable for WINDOWS

%USERPROFILE%\AppData\Roaming\npm

After that test with where grunt

Note: Do not forget to close the command prompt window and reopen it.

Unexpected token ILLEGAL in webkit

You can use online Minify, it removes these invisible characters efficiently but also changes your code. So be careful.

http://jscompress.com/

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

PHP: Get key from array?


$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

How to parse a JSON string to an array using Jackson

The other answer is correct, but for completeness, here are other ways:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

Is it possible to get element from HashMap by its position?

Use LinkedHashMap and use this function.

private LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();

Define like this and.

private Entry getEntry(int id){
        Iterator iterator = map.entrySet().iterator();
        int n = 0;
        while(iterator.hasNext()){
            Entry entry = (Entry) iterator.next();
            if(n == id){
                return entry;
            }
            n ++;
        }
        return null;
    }

The function can return the selected entry.

What is the difference between an int and an Integer in Java and C#?

01. Integer can be null. But int cannot be null.

Integer value1 = null; //OK

int value2 = null      //Error

02. Only can pass Wrapper Classes type values to any collection class.

(Wrapper Classes - Boolean,Character,Byte,Short,Integer,Long,Float,Double)

List<Integer> element = new ArrayList<>();
int valueInt = 10;
Integer  valueInteger = new Integer(value);
element.add(valueInteger);

But normally we add primitive values to collection class? Is point 02 correct?

List<Integer> element = new ArrayList<>();
element.add(5);

Yes 02 is correct, beacouse autoboxing.

Autoboxing is the automatic conversion that the java compiler makes between the primitive type and their corresponding wrapper class.

Then 5 convert as Integer value by autoboxing.

Cocoa Touch: How To Change UIView's Border Color And Thickness?

If you didn't want to edit the layer of a UIView, you could always embed the view within another view. The parent view would have its background color set to the border color. It would also be slightly larger, depending upon how wide you want the border to be.

Of course, this only works if your view isn't transparent and you only want a single border color. The OP wanted the border in the view itself, but this may be a viable alternative.

How add unique key to existing table (with non uniques rows)

Set Multiple Unique key into table

ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);

Adding a newline character within a cell (CSV)

I have the same issue, when I try to export the content of email to csv and still keep it break line when importing to excel.

I export the conent as this: ="Line 1"&CHAR(10)&"Line 2"

When I import it to excel(google), excel understand it as string. It still not break new line.

We need to trigger excel to treat it as formula by: Format -> Number | Scientific.

This is not the good way but it resolve my issue.

How to drop a unique constraint from table column?

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from 
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where 
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

Find multiple files and rename them in Linux

You can use find to find all matching files recursively:

$ find . -iname "*dbg*" -exec rename _dbg.txt .txt '{}' \;

EDIT: what the '{}' and \; are?

The -exec argument makes find execute rename for every matching file found. '{}' will be replaced with the path name of the file. The last token, \; is there only to mark the end of the exec expression.

All that is described nicely in the man page for find:

 -exec utility [argument ...] ;
         True if the program named utility returns a zero value as its
         exit status.  Optional arguments may be passed to the utility.
         The expression must be terminated by a semicolon (``;'').  If you
         invoke find from a shell you may need to quote the semicolon if
         the shell would otherwise treat it as a control operator.  If the
         string ``{}'' appears anywhere in the utility name or the argu-
         ments it is replaced by the pathname of the current file.
         Utility will be executed from the directory from which find was
         executed.  Utility and arguments are not subject to the further
         expansion of shell patterns and constructs.

Readably print out a python dict() sorted by key

You could transform this dict a little to ensure that (as dicts aren't kept sorted internally), e.g.

pprint([(key, mydict[key]) for key in sorted(mydict.keys())])

When should I use Memcache instead of Memcached?

Memcached client library was just recently released as stable. It is being used by digg ( was developed for digg by Andrei Zmievski, now no longer with digg) and implements much more of the memcached protocol than the older memcache client. The most important features that memcached has are:

  1. Cas tokens. This made my life much easier and is an easy preventive system for stale data. Whenever you pull something from the cache, you can receive with it a cas token (a double number). You can than use that token to save your updated object. If no one else updated the value while your thread was running, the swap will succeed. Otherwise a newer cas token was created and you are forced to reload the data and save it again with the new token.
  2. Read through callbacks are the best thing since sliced bread. It has simplified much of my code.
  3. getDelayed() is a nice feature that can reduce the time your script has to wait for the results to come back from the server.
  4. While the memcached server is supposed to be very stable, it is not the fastest. You can use binary protocol instead of ASCII with the newer client.
  5. Whenever you save complex data into memcached the client used to always do serialization of the value (which is slow), but now with memcached client you have the option of using igbinary. So far I haven't had the chance to test how much of a performance gain this can be.

All of this points were enough for me to switch to the newest client, and can tell you that it works like a charm. There is that external dependency on the libmemcached library, but have managed to install it nonetheless on Ubuntu and Mac OSX, so no problems there so far.

If you decide to update to the newer library, I suggest you update to the latest server version as well as it has some nice features as well. You will need to install libevent for it to compile, but on Ubuntu it wasn't much trouble.

I haven't seen any frameworks pick up the new memcached client thus far (although I don't keep track of them), but I presume Zend will get on board shortly.

UPDATE

Zend Framework 2 has an adapter for Memcached which can be found here

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST some data to www.abc.com/blog and with in milliseconds an other request will also go for the same resource i.e. www.abc.com/blog from the same user. So it'll give the 409 error.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Error : Index was outside the bounds of the array.

//if i input 9 it should go to 8?

You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).

comma separated string of selected values in mysql

Try this

SELECT CONCAT('"',GROUP_CONCAT(id),'"') FROM table_level 
where parent_id=4 group by parent_id;

Result will be

 "5,6,9,10,12,14,15,17,18,779"

C# how to create a Guid value?

If you want to create a "desired" Guid you can do

var tempGuid = Guid.Parse("<guidValue>");

where <guidValue> would be something like 1A3B944E-3632-467B-A53A-206305310BAE.

Relational Database Design Patterns?

Design patterns aren't trivially reusable solutions.

Design patterns are reusable, by definition. They're patterns you detect in other good solutions.

A pattern is not trivially reusable. You can implement your down design following the pattern however.

Relational design patters include things like:

  1. One-to-Many relationships (master-detail, parent-child) relationships using a foreign key.

  2. Many-to-Many relationships with a bridge table.

  3. Optional one-to-one relationships managed with NULLs in the FK column.

  4. Star-Schema: Dimension and Fact, OLAP design.

  5. Fully normalized OLTP design.

  6. Multiple indexed search columns in a dimension.

  7. "Lookup table" that contains PK, description and code value(s) used by one or more applications. Why have code? I don't know, but when they have to be used, this is a way to manage the codes.

  8. Uni-table. [Some call this an anti-pattern; it's a pattern, sometimes it's bad, sometimes it's good.] This is a table with lots of pre-joined stuff that violates second and third normal form.

  9. Array table. This is a table that violates first normal form by having an array or sequence of values in the columns.

  10. Mixed-use database. This is a database normalized for transaction processing but with lots of extra indexes for reporting and analysis. It's an anti-pattern -- don't do this. People do it anyway, so it's still a pattern.

Most folks who design databases can easily rattle off a half-dozen "It's another one of those"; these are design patterns that they use on a regular basis.

And this doesn't include administrative and operational patterns of use and management.

Python Pandas Error tokenizing data

I had a similar case as this and setting

train = pd.read_csv('input.csv' , encoding='latin1',engine='python') 

worked

Accessing Google Spreadsheets with C# using Google Data API

I'm pretty sure there'll be some C# SDKs / toolkits on Google Code for this. I found this one, but there may be others so it's worth having a browse around.

Cannot make file java.io.IOException: No such file or directory

File.isFile() is false if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.

The issue is that the intermediate directories don't exist. You want to call f.mkdirs() first.

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

This error can also occur in the normal situation when a database is starting or stopping. Normally on startup you can wait until the startup completes, then connect as usual. If the error persists, the service (on a Windows box) may be started without the database being started. This may be due to startup issues, or because the service is not configured to automatically start the database. In this case you will have to connect as sysdba and physically start the database using the "startup" command.

How to calculate date difference in JavaScript?

Expressions like "difference in days" are never as simple as they seem. If you have the following dates:

d1: 2011-10-15 23:59:00
d1: 2011-10-16 00:01:00

the difference in time is 2 minutes, should the "difference in days" be 1 or 0? Similar issues arise for any expression of the difference in months, years or whatever since years, months and days are of different lengths and different times (e.g. the day that daylight saving starts is 1 hour shorter than usual and two hours shorter than the day that it ends).

Here is a function for a difference in days that ignores the time, i.e. for the above dates it returns 1.

/*
   Get the number of days between two dates - not inclusive.

   "between" does not include the start date, so days
   between Thursday and Friday is one, Thursday to Saturday
   is two, and so on. Between Friday and the following Friday is 7.

   e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.

   If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
   use date prior to start date (i.e. 31/12/2010 to 30/1/2011).

   Only calculates whole days.

   Assumes d0 <= d1
*/
function getDaysBetweenDates(d0, d1) {

  var msPerDay = 8.64e7;

  // Copy dates so don't mess them up
  var x0 = new Date(d0);
  var x1 = new Date(d1);

  // Set to noon - avoid DST errors
  x0.setHours(12,0,0);
  x1.setHours(12,0,0);

  // Round to remove daylight saving errors
  return Math.round( (x1 - x0) / msPerDay );
}

This can be more concise:

_x000D_
_x000D_
/*  Return number of days between d0 and d1._x000D_
**  Returns positive if d0 < d1, otherwise negative._x000D_
**_x000D_
**  e.g. between 2000-02-28 and 2001-02-28 there are 366 days_x000D_
**       between 2015-12-28 and 2015-12-29 there is 1 day_x000D_
**       between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day_x000D_
**       between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days_x000D_
**        _x000D_
**  @param {Date} d0  - start date_x000D_
**  @param {Date} d1  - end date_x000D_
**  @returns {number} - whole number of days between d0 and d1_x000D_
**_x000D_
*/_x000D_
function daysDifference(d0, d1) {_x000D_
  var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12);_x000D_
  return Math.round(diff/8.64e7);_x000D_
}_x000D_
_x000D_
// Simple formatter_x000D_
function formatDate(date){_x000D_
  return [date.getFullYear(),('0'+(date.getMonth()+1)).slice(-2),('0'+date.getDate()).slice(-2)].join('-');_x000D_
}_x000D_
_x000D_
// Examples_x000D_
[[new Date(2000,1,28), new Date(2001,1,28)],  // Leap year_x000D_
 [new Date(2001,1,28), new Date(2002,1,28)],  // Not leap year_x000D_
 [new Date(2017,0,1),  new Date(2017,1,1)] _x000D_
].forEach(function(dates) {_x000D_
  document.write('From ' + formatDate(dates[0]) + ' to ' + formatDate(dates[1]) +_x000D_
                 ' is ' + daysDifference(dates[0],dates[1]) + ' days<br>');_x000D_
});
_x000D_
_x000D_
_x000D_

Scrolling a div with jQuery

jCarousel is a Jquery Plugin , it have same functionality already implemented , which might want to archive. it's nice and easy. here is the link

and complete documentation can be found here

Download file of any type in Asp.Net MVC using FileResult?

The MVC framework supports this natively. The System.Web.MVC.Controller.File controller provides methods to return a file by name/stream/array.

For example using a virtual path to the file you could do the following.

return File(virtualFilePath, System.Net.Mime.MediaTypeNames.Application.Octet,  Path.GetFileName(virtualFilePath));

What is the difference between atan and atan2 in C++?

In atan2, the output is: -pi < atan2(y,x) <pi
and in atan, the output is: -pi/2 < atan(y/x) < pi/2 //it dose NOT consider the quarter.
If you want to get the orientation between 0 and 2*pi (like the high-school math), we need to use the atan2 and for negative values add the 2*pi to get the final result between 0 and 2*pi.
Here is the Java source code to explain it clearly:

System.out.println(Math.atan2(1,1)); //pi/4 in the 1st quarter
System.out.println(Math.atan2(1,-1)); //(pi/4)+(pi/2)=3*(pi/4) in the 2nd quarter

System.out.println(Math.atan2(-1,-1 ));//-3*(pi/4) and it is less than 0.
System.out.println(Math.atan2(-1,-1)+2*Math.PI); //5(pi/4) in the 3rd quarter

System.out.println(Math.atan2(-1,1 ));//-pi/4 and it is less than 0.
System.out.println(Math.atan2(-1,1)+2*Math.PI); //7*(pi/4) in the 4th quarter

System.out.println(Math.atan(1 ));//pi/4
System.out.println(Math.atan(-1 ));//-pi/4

Selenium Webdriver: Entering text into text field

It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:

  1. either check for the valid string-input in the text-box.
  2. or set a loop against that text box to enter the value until you post the form/request.
String barcode="0000000047166";

WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

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

string root = HttpContext.Current.Server.MapPath("~/App_Data");

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

I don't see a reference to this:

SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");

above format is also useful.

http://www.java2s.com/Tutorials/Java/Date/Date_Format/Format_date_in_yyyyMMddHHmmssSSS_format_in_Java.htm

MySQL Select Date Equal to Today

This query will use index if you have it for signup_date field

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
    FROM users 
    WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)

How to completely uninstall Android Studio on Mac?

You may also delete gradle file, if you don't use gradle any where else:

rm -Rfv ~/.gradle/

because .gradle folder contains cached artifacts that are no longer needed.

ArrayBuffer to base64 encoded string

function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

but, non-native implementations are faster e.g. https://gist.github.com/958841 see http://jsperf.com/encoding-xhr-image-data/6

How to Implement DOM Data Binding in JavaScript

There is a very simple barebones implementation of 2-way data-binding in this link "Easy Two-Way Data Binding in JavaScript"

The previous link along with ideas from knockoutjs, backbone.js and agility.js, led to this light-weight and fast MVVM framework, ModelView.js based on jQuery which plays nicely with jQuery and of which i am the humble (or maybe not so humble) author.

Reproducing sample code below (from blog post link):

Sample code for DataBinder

function DataBinder( object_id ) {
  // Use a jQuery object as simple PubSub
  var pubSub = jQuery({});

  // We expect a `data` element specifying the binding
  // in the form: data-bind-<object_id>="<property_name>"
  var data_attr = "bind-" + object_id,
      message = object_id + ":change";

  // Listen to change events on elements with the data-binding attribute and proxy
  // them to the PubSub, so that the change is "broadcasted" to all connected objects
  jQuery( document ).on( "change", "[data-" + data_attr + "]", function( evt ) {
    var $input = jQuery( this );

    pubSub.trigger( message, [ $input.data( data_attr ), $input.val() ] );
  });

  // PubSub propagates changes to all bound elements, setting value of
  // input tags or HTML content of other tags
  pubSub.on( message, function( evt, prop_name, new_val ) {
    jQuery( "[data-" + data_attr + "=" + prop_name + "]" ).each( function() {
      var $bound = jQuery( this );

      if ( $bound.is("input, textarea, select") ) {
        $bound.val( new_val );
      } else {
        $bound.html( new_val );
      }
    });
  });

  return pubSub;
}

For what concerns the JavaScript object, a minimal implementation of a User model for the sake of this experiment could be the following:

function User( uid ) {
  var binder = new DataBinder( uid ),

      user = {
        attributes: {},

        // The attribute setter publish changes using the DataBinder PubSub
        set: function( attr_name, val ) {
          this.attributes[ attr_name ] = val;
          binder.trigger( uid + ":change", [ attr_name, val, this ] );
        },

        get: function( attr_name ) {
          return this.attributes[ attr_name ];
        },

        _binder: binder
      };

  // Subscribe to the PubSub
  binder.on( uid + ":change", function( evt, attr_name, new_val, initiator ) {
    if ( initiator !== user ) {
      user.set( attr_name, new_val );
    }
  });

  return user;
}

Now, whenever we want to bind a model’s property to a piece of UI we just have to set an appropriate data attribute on the corresponding HTML element:

// javascript
var user = new User( 123 );
user.set( "name", "Wolfgang" );

<!-- html -->
<input type="number" data-bind-123="name" />

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

gridview data export to excel in asp.net

Something else to check is make sure viewstate is on (I just solved this yesterday). If you don't have viewstate on, the gridview will be blank until you load it again.

Check if an element has event listener on it. No jQuery

Nowadays (2016) in Chrome Dev Tools console, you can quickly execute this function below to show all event listeners that have been attached to an element.

getEventListeners(document.querySelector('your-element-selector'));

How can I convert a .py to .exe for Python?

Python 3.6 is supported by PyInstaller.

Open a cmd window in your Python folder (open a command window and use cd or while holding shift, right click it on Windows Explorer and choose 'Open command window here'). Then just enter

pip install pyinstaller

And that's it.

The simplest way to use it is by entering on your command prompt

pyinstaller file_name.py

For more details on how to use it, take a look at this question.

Difference between except: and except Exception as e: in Python

Another way to look at this. Check out the details of the exception:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

There are lots of "things" to access using the 'as e' syntax.

This code was solely meant to show the details of this instance.

Build error: You must add a reference to System.Runtime

I had this problem in some solutions on VS 2015 (not MVC though), and even in the same solution on one workstation but not on another. The errors started appeared after changing .NET version to 4.6 and referencing PCL.

The solution is simple: Close the solution and delete the hidden .vs folder in the same folder as the solution.

Adding the missing references as suggested in other answers also solves the problem, but the error remains solved even after you remove the references again.

As for TeamCity, I cannot say since my configuration never had a problem. But make sure that you reset the working catalog as a part of your debugging effort.

How to list files in an android directory?

Updated working method

My minSdkversion is 21, so I'm using ContextCompat.checkSelfPermission() method to grant permissions apart from also adding the <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> in manifest. Thus, to get rid of the NullPointerException in spite of having files in your targeted directory, grant permissions as follows:-

MainActivity.java


public class MainActivity extends AppCompatActivity {
    /*Other variables & constants here*/  
    private final int READ_EXTERNAL_STORAGE=100;

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

        // ignore the button code

        Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openWebView();
            }
        });
    

         /*---------------------------- GRANT PERMISSIONS START-------------------------*/
        // Main part to grant permission. Handle other cases of permission denied
       //   yourself.
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},READ_EXTERNAL_STORAGE);

         /*---------------------------- GRANT PERMISSIONS OVER-------------------------*/
   }

And the function that list all the files (in MainActivity.java), thanks to @Yury:-
public void getDownloadedFile() {
        String path = Environment.getExternalStorageDirectory().toString()+"/Download/";
        Log.d("Files", "Path: " + path);
        File directory = new File(path);
        File[] files = directory.listFiles();
        if(directory.canRead() && files!=null) {
            Log.d("Files", "Size: " + files.length);
            for(File file: files)
                Log.d("FILE",file.getName());
        }
        else
            Log.d("Null?", "it is null");
    }

How do I convert ticks to minutes?

A single tick represents one hundred nanoseconds or one ten-millionth of a second. FROM MSDN.

So 28 000 000 000 * 1/10 000 000 = 2 800 sec. 2 800 sec /60 = 46.6666min

Or you can do it programmaticly with TimeSpan:

    static void Main()
    {
        TimeSpan ts = TimeSpan.FromTicks(28000000000);
        double minutesFromTs = ts.TotalMinutes;
        Console.WriteLine(minutesFromTs);
        Console.Read();
    }

Both give me 46 min and not 480 min...

How to return a file (FileContentResult) in ASP.NET WebAPI

Instead of returning StreamContent as the Content, I can make it work with ByteArrayContent.

[HttpGet]
public HttpResponseMessage Generate()
{
    var stream = new MemoryStream();
    // processing the stream.

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.ToArray())
    };
    result.Content.Headers.ContentDisposition =
        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "CertificationCard.pdf"
    };
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");

    return result;
}

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

row-level trigger vs statement-level trigger

The main difference between statement level trigger is below :

statement level trigger : based on name it works if any statement is executed. Does not depends on how many rows or any rows effected.It executes only once. Exp : if you want to update salary of every employee from department HR and at the end you want to know how many rows get effected means how many got salary increased then use statement level trigger. please note that trigger will execute even if zero rows get updated because it is statement level trigger is called if any statement has been executed. No matters if it is affecting any rows or not.

Row level trigger : executes each time when an row is affected. if zero rows affected.no row level trigger will execute.suppose if u want to delete one employye from emp table whose department is HR and u want as soon as employee deleted from emp table the count in dept table from HR section should be reduce by 1.then you should opt for row level trigger.

Configuring so that pip install can work from github

I had similar issue when I had to install from github repo, but did not want to install git , etc.

The simple way to do it is using zip archive of the package. Add /zipball/master to the repo URL:

    $ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
  Downloading master
  Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
  Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...

This way you will make pip work with github source repositories.

Checking if a SQL Server login already exists

As a minor addition to this thread, in general you want to avoid using the views that begin with sys.sys* as Microsoft is only including them for backwards compatibility. For your code, you should probably use sys.server_principals. This is assuming you are using SQL 2005 or greater.

RecyclerView: Inconsistency detected. Invalid item position

In my case I was trying to change my adapter contents on a background thread but called notify* on the main/ui thread.

That is not possible! The reason why notify is forced to main thread is that the recyclerview wants you to edit your backing adapter on the main thread, even on the same call stack.

To solve the problem make sure that every operation to your adapter as well as every notify... call is made on the ui/main thread!

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

Virtualhost For Wildcard Subdomain and Static Subdomain

Wildcards can only be used in the ServerAlias rather than the ServerName. Something which had me stumped.

For your use case, the following should suffice

<VirtualHost *:80>
    ServerAlias *.example.com
    VirtualDocumentRoot /var/www/%1/
</VirtualHost>

How to calculate the width of a text string of a specific font and font-size?

Oneliner in Swift 4.2

let size = text.size(withAttributes:[.font: UIFont.systemFont(ofSize:18.0)])

Accessing inventory host variable in Ansible playbook

You should be able to use the variable name directly

ansible_ssh_host

Or you can go through hostvars without having to specify the host literally by using the magic variable inventory_hostname

hostvars[inventory_hostname].ansible_ssh_host

How can I clear the terminal in Visual Studio Code?

To permanently delete the previous commands, use this

  1. Set-PSReadlineOption -HistoryNoDuplicates

  2. Remove-Item (Get-PSReadlineOption).HistorySavePath

  3. Alt-f7

jQuery .val change doesn't change input value

Use attr instead.
$('#link').attr('value', 'new value');

demo

Soft hyphen in HTML (<wbr> vs. &shy;)

I use &shy;, inserted manually where necessary.

I always find it a pity that people don’t use techniques because there is some—maybe old or strange—browser around which doesn’t handle them the way they were specified. I found that &shy; is working properly in both recent Internet Explorer and Firefox browsers, that should be enough. You may include a browser check telling people to use something mature or continue at their own risk if they come around with some strange browser.

Syllabification isn’t that easy and I cannot recommend leaving it to some Javascript. It’s a language specific topic and may need to be carefully revised by the deskman if you don’t want it to turn your text irritating. Some languages, such as German, form compound words and are likely to lead to decomposition problems. E.g. Spargelder (germ. saved money, pl.) may, by syllabification rules, be wrapped in two places (Spar-gel-der). However, wrapping it in the second position, turns the first part to show up as Spargel- (germ. asparagus), activating a completely misleading concept in the head of the reader and therefore shoud be avoided.

And what about the string Wachstube? It could either mean ‘guardroom’ (Wach-stu-be) or ‘tube of wax’ (Wachs-tu-be). You may probably find other examples in other languages as well. You should aim to provide an environment in which the deskman can be supported in creating a well-syllabified text, proof-reading every critical word.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

powershell is missing the terminator: "

Look closely at the two dashes in

unzipRelease –Src '$ReleaseFile' -Dst '$Destination'

This first one is not a normal dash but an en-dash (&ndash; in HTML). Replace that with the dash found before Dst.

Octave/Matlab: Adding new elements to a vector

As mentioned before, the use of x(end+1) = newElem has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.

However, what should not be forgotten is that x = [x newElem] will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]


All in all, if you want a solution that allows you to concatenate your existing vector x with newElem that may or may not be a scalar, this should do the trick:

 x(end+(1:numel(newElem)))=newElem

How can I list all cookies for the current page with Javascript?

No there isn't. You can only read information associated with the current domain.

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Convert date to another timezone in JavaScript

I don't know an easy method to convert a date object to any time zone, but if you want to convert it to the local time zone, you can just convert it with Date.prototype.getTime() to the corresponding number of milliseconds, and back again.

date = new Date('2016-05-24T13:07:20');
date = new Date(date.getTime());

For example, date.getHours() will now return 15 instead of 13 if you are, like me, in Austria (and it's summer).

I've read that the various datetime functions may exhibit non-standard behaviour in some browsers, so test this first. I can confirm that it works in Chrome.

Process all arguments except the first one (in a bash script)

http://wiki.bash-hackers.org/scripting/posparams

It explains the use of shift (if you want to discard the first N parameters) and then implementing Mass Usage

How to add composite primary key to table

If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

enter image description here

Why can't I shrink a transaction log file, even after backup?

Don't you need this

DBCC SHRINKFILE ('Wxlog0', 0)

Just be sure that you are aware of the dangers: see here: Do not truncate your ldf files!

And here Backup Log with Truncate_Only: Like a Bear Trap

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

Im using QtCreator with gdb.

Adding

QMAKE_CXXFLAGS += -O0
QMAKE_CXXFLAGS -= -O1
QMAKE_CXXFLAGS -= -O2
QMAKE_CXXFLAGS -= -O3

Works well for me

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

I used yet another trick to format date with 6-digit precision (microseconds):

System.out.println(
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.").format(microseconds/1000)
    +String.format("%06d", microseconds%1000000));

This technique can be extended further, to nanoseconds and up.

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

JavaScript hide/show element

Though this question has been answered many times before, I thought I would add to it with a more complete and solid answer for future users. The main answer does solve the problem, but I believe it may be better to know/understand the some of various ways to show/hide things.

.

Changing display using css()

This is the way I used to do it until I found some of these other ways.

Javascript:

$("#element_to_hide").css("display", "none");  // To hide
$("#element_to_hide").css("display", "");  // To unhide

Pros:

  • Hides and unhides. That's about it.

Cons:

  • If you use the "display" attribute for something else, you will have to hardcode the value of what it was prior to hiding. So if you had "inline", you would have to do $("#element_to_hid").css("display", "inline"); otherwise it will default back to "block" or whatever else that it will be forced into.
  • Lends itself to typos.

Example: https://jsfiddle.net/4chd6e5r/1/

.

Changing display using addClass()/removeClass()

While setting up the example for this one, I actually ran into some flaws on this method that make it very very unreliable.

Css/Javascript:

.hidden {display:none}
$("#element_to_hide").addClass("hidden");  // To hide
$("#element_to_hide").removeClass("hidden");  // To unhide

Pros:

  • It hides....sometimes. Refer to p1 on the example.
  • After unhiding, it will return back to using the previous display value....sometimes. Refer to p1 on the example.
  • If you want to grab all hidden objects, you just need to do $(".hidden").

Cons:

  • Does not hide if the display value was set directly on the html. Refer to p2 on the example.
  • Does not hide if the display is set in javascript using css(). Refer to p3 on the example.
  • Slightly more code because you have to define a css attribute.

Example: https://jsfiddle.net/476oha8t/8/

.

Changing display using toggle()

Javascript:

$("element_to_hide").toggle();  // To hide and to unhide

Pros:

  • Always works.
  • Allows you to not have to worry about which state it was prior to switching. The obvious use for this is for a....toggle button.
  • Short and simple.

Cons:

  • If you need to know which state it is switching to in order to do something not directly related, you will have to add more code (an if statement) to find out which state it is in.
  • Similar to the previous con, if you want to run a set of instructions that contains the toggle() for the purpose of hiding, but you don't know if it is already hidden, you have to add a check (an if statement) to find out first and if it is already hidden, then skip. Refer to p1 of the example.
  • Related to the previous 2 cons, using toggle() for something that is specifically hiding or specifically showing, can be confusing to others reading your code as they do not know which way they will toggle.

Example: https://jsfiddle.net/cxcawkyk/1/

.

Changing display using hide()/show()

Javascript:

$("#element_to_hide").hide();  // To hide
$("#element_to_hide").show();  // To show

Pros:

  • Always works.
  • After unhiding, it will return back to using the previous display value.
  • You will always know which state you are swapping to so you:
    1. don't need to add if statements to check visibility before changing states if the state matters.
    2. won't confuse others reading your code as to which state you are switching to if, if the state matters.
  • Intuitive.

Cons:

  • If you want to imitate a toggle, you will have to check the state first and then switch to the other state. Use toggle() instead for these. Refer to p2 of the example.

Example: https://jsfiddle.net/k0ukhmfL/

.

Overall, I would say the best to be hide()/show() unless you specifically need it to be a toggle. I hope you found this information to be helpful.

How to enable php7 module in apache?

First, disable the php5 module:

a2dismod php5

then, enable the php7 module:

a2enmod php7.0

Next, reload/restart the Apache service:

service apache2 restart

Update 2018-09-04

wrt the comment, you need to specify exact installed version.

How do CSS triangles work?

Taking it one step further, using css based on this I added arrows to my back and next buttons (yes I know its not 100% cross-browser, but slick none the less).

_x000D_
_x000D_
.triangle {_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border-left: 50px solid transparent;_x000D_
  border-right: 50px solid transparent;_x000D_
  border-bottom: 100px solid red;_x000D_
  margin:20px auto;_x000D_
}_x000D_
_x000D_
.triangle-down {_x000D_
  border-bottom:none;_x000D_
  border-top: 100px solid red;_x000D_
}_x000D_
_x000D_
.triangle-left {_x000D_
  border-left:none;_x000D_
  border-right: 100px solid red;_x000D_
  border-bottom: 50px solid transparent;_x000D_
  border-top: 50px solid transparent;_x000D_
}_x000D_
_x000D_
.triangle-right {_x000D_
  border-right:none;_x000D_
  border-left: 100px solid red;_x000D_
  border-bottom: 50px solid transparent;_x000D_
  border-top: 50px solid transparent;_x000D_
}_x000D_
_x000D_
.triangle-after:after {_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border-left: 5px solid transparent;_x000D_
  border-right: 5px solid transparent;_x000D_
  border-bottom: 5px solid red;_x000D_
  margin:0 5px;_x000D_
  content:"";_x000D_
  display:inline-block;_x000D_
}_x000D_
_x000D_
.triangle-after-right:after {_x000D_
  border-right:none;_x000D_
  border-left: 5px solid blue;_x000D_
  border-bottom: 5px solid transparent;_x000D_
  border-top: 5px solid transparent;_x000D_
_x000D_
}_x000D_
_x000D_
.triangle-before:before {_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border-left: 5px solid transparent;_x000D_
  border-right: 5px solid transparent;_x000D_
  border-bottom: 5px solid blue;_x000D_
  margin:0 5px;_x000D_
  content:"";_x000D_
  display:inline-block;_x000D_
}_x000D_
_x000D_
.triangle-before-left:before {_x000D_
  border-left:none;_x000D_
  border-right: 5px solid blue;_x000D_
  border-bottom: 5px solid transparent;_x000D_
  border-top: 5px solid transparent;_x000D_
_x000D_
}
_x000D_
<div class="triangle"></div>_x000D_
<div class="triangle triangle-down"></div>_x000D_
<div class="triangle triangle-left"></div>_x000D_
<div class="triangle triangle-right"></div>_x000D_
_x000D_
<a class="triangle-before triangle-before-left" href="#">Back</a>_x000D_
<a class="triangle-after triangle-after-right" href="#">Next</a>
_x000D_
_x000D_
_x000D_

Difference between two dates in Python

I tried a couple of codes, but end up using something as simple as (in Python 3):

from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])

If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.

If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):

df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date

And then run:

df['difference_in_days'] = abs(df['end_date'] - df['start_date'])

Get response from PHP file using AJAX

<?php echo 'apple'; ?> is pretty much literally all you need on the server.

as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have

success: function(data) {
   alert(data); // apple
}

What's the fastest way to do a bulk insert into Postgres?

PostgreSQL has a guide on how to best populate a database initially, and they suggest using the COPY command for bulk loading rows. The guide has some other good tips on how to speed up the process, like removing indexes and foreign keys before loading the data (and adding them back afterwards).

Why both no-cache and no-store should be used in HTTP response?

For chrome, no-cache is used to reload the page on a re-visit, but it still caches it if you go back in history (back button). To reload the page for history-back as well, use no-store. IE needs must-revalidate to work in all occasions.

So just to be sure to avoid all bugs and misinterpretations I always use

Cache-Control: no-store, no-cache, must-revalidate

if I want to make sure it reloads.

How to copy text programmatically in my Android app?

Here is some code to implement some copy and paste functions from EditText (thanks to Warpzit for version check). You can hook these to your button's onclick event.

public void copy(View v) {      
    int startSelection = txtNotes.getSelectionStart();
    int endSelection = txtNotes.getSelectionEnd();      
    if ((txtNotes.getText() != null) && (endSelection > startSelection ))
    {
        String selectedText = txtNotes.getText().toString().substring(startSelection, endSelection);                
        int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setText(selectedText);
        } else {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
            android.content.ClipData clip = android.content.ClipData.newPlainText("WordKeeper",selectedText);
            clipboard.setPrimaryClip(clip);
        }
    }
}   

public void paste(View v) {
    int sdk = android.os.Build.VERSION.SDK_INT;
    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard.getText() != null) {
            txtNotes.getText().insert(txtNotes.getSelectionStart(), clipboard.getText());
        }
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
        if (item.getText() != null) {
            txtNotes.getText().insert(txtNotes.getSelectionStart(), item.getText());
        }
    }
}

Delete all the records

For one table

truncate table [table name]

For all tables

EXEC sp_MSforeachtable @command1="truncate table ?"

Regular expression to match URLs in Java

((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\.[a-zA-Z]+

check here:- https://www.freeformatter.com/java-regex-tester.html#ad-output

It sorts out theses entries correctly

String literals and escape characters in postgresql

Really stupid question: Are you sure the string is being truncated, and not just broken at the linebreak you specify (and possibly not showing in your interface)? Ie, do you expect the field to show as

This will be inserted \n This will not be

or

This will be inserted

This will not be

Also, what interface are you using? Is it possible that something along the way is eating your backslashes?

Using `date` command to get previous, current and next month

If you happen to be using date in a MacOS environment, try this:

ST1:~ ejf$ date
Mon Feb 20 21:55:48 CST 2017
ST1:~ ejf$ date -v-1m +%m
01
ST1:~ ejf$ date -v+1m +%m
03

Also, I'd rather calculate the previous and next month on the first day of each month, this way you won't have issues with months ending the 30/31 or 28/29 (Feb/Feb leap year)

Make Frequency Histogram for Factor Variables

It seems like you want barplot(prop.table(table(animals))):

enter image description here

However, this is not a histogram.

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

How to get the clicked link's href with jquery?

this in your callback function refers to the clicked element.

   $(".addressClick").click(function () {
        var addressValue = $(this).attr("href");
        alert(addressValue );
    });

Read user input inside a loop

It looks like you read twice, the read inside the while loop is not needed. Also, you don't need to invoke the cat command:

while read input
do
    echo $input
done < filename

deny directory listing with htaccess

Agree that

Options -Indexes

should work if the main server is configured to allow option overrides, but if not, this will hide all files from the listing (so every directory appears empty):

IndexIgnore *

Form Submit jQuery does not work

The NUMBER ONE error is having ANYTHING with the reserved word submit as ID or NAME in your form.

If you plan to call .submit() on the form AND the form has submit as id or name on any form element, then you need to rename that form element, since the form’s submit method/handler is shadowed by the name/id attribute.


Several other things:

As mentioned, you need to submit the form using a simpler event than the jQuery one

BUT you also need to cancel the clicks on the links

Why, by the way, do you have two buttons? Since you use jQuery to submit the form, you will never know which of the two buttons were clicked unless you set a hidden field on click.

<form action="deletprofil.php" id="form_id" method="post">
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });

    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});    

Judging from your comments, I think you really want to do this:

<form action="deletprofil.php" id="form_id" method="post">
  <input type="hidden" id="whichdelete" name="whichdelete" value="" />
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="button" value="1" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="button" value="2" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          // trigger the submit event, not the event handler
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });
    $(".delete").on("click", function(e) {
        $("#whichdelete").val(this.value);
    });
    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});  

Create array of regex matches

From the Official Regex Java Trails:

        Pattern pattern = 
        Pattern.compile(console.readLine("%nEnter your regex: "));

        Matcher matcher = 
        pattern.matcher(console.readLine("Enter input string to search: "));

        boolean found = false;
        while (matcher.find()) {
            console.format("I found the text \"%s\" starting at " +
               "index %d and ending at index %d.%n",
                matcher.group(), matcher.start(), matcher.end());
            found = true;
        }

Use find and insert the resulting group at your array / List / whatever.

Getting user input

Use the following simple way to interactively get user data by a prompt as Arguments on what you want.

Version : Python 3.X

name = input('Enter Your Name: ')
print('Hello ', name)

MySQL Workbench Edit Table Data is read only

In MySQL Workbench you need an INDEX to edit, no need it to be PK (although adding a PK is a solution as well).

You can make a regular INDEX or compound INDEX. That's all MySQL WB needs to fix the Read only thing (I have v. 6.2 with MariaDB v. 10.1.4):

Just right click table, select "Alter table..." then go to "Indexes" tab. In the left pane put a custom name for your index, and in the middle pane checkmark one (make sure the vale will be unique) or more fields (just make sure the combination is unique)

What is the difference between $routeProvider and $stateProvider?

Both do the same work as they are used for routing purposes in SPA(Single Page Application).

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on the page that you wanted to render based on some conditions, $routeProvider fails. (to achieve that, we need to use directives like ng-include, ng-switch, ng-if, ng-show, which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part of the view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views in a template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manage nested state & views.

Pros

  • You can have multiple ui-view on single page
  • Various views can be nested in each other and maintained by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Another way you could do relative routing is by using only @ to change ui-view="some". This will replace the ui-view rather than checking if it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

How can I get a file's size in C++?

I ended up just making a short and sweet fsize function(note, no error checking)

int fsize(FILE *fp){
    int prev=ftell(fp);
    fseek(fp, 0L, SEEK_END);
    int sz=ftell(fp);
    fseek(fp,prev,SEEK_SET); //go back to where we were
    return sz;
}

It's kind of silly that the standard C library doesn't have such a function, but I can see why it'd be difficult as not every "file" has a size(for instance /dev/null)

How to create EditText accepts Alphabets only in android?

Try This

<EditText
  android:id="@+id/EditText1"
  android:text=""
  android:inputType="text|textNoSuggestions"
  android:textSize="18sp"
  android:layout_width="80dp"
  android:layout_height="43dp">
</EditText>

Other inputType can be found Here ..

Java replace all square brackets in a string

_x000D_
_x000D_
   Use this line:) String result = strCurBal.replaceAll("[(" what ever u need to remove ")]", "");_x000D_
_x000D_
    String strCurBal = "(+)3428";_x000D_
    Log.e("Agilanbu before omit ", strCurBal);_x000D_
    String result = strCurBal.replaceAll("[()]", ""); // () removing special characters from string_x000D_
    Log.e("Agilanbu after omit ", result);_x000D_
   _x000D_
    o/p :_x000D_
    Agilanbu before omit : (+)3428_x000D_
    Agilanbu after omit :  +3428_x000D_
_x000D_
    String finalVal = result.replaceAll("[+]", ""); // + removing special characters from string_x000D_
    Log.e("Agilanbu finalVal  ", finalVal);_x000D_
    o/p_x000D_
    Agilanbu finalVal : 3428_x000D_
            _x000D_
    String finalVal1 = result.replaceAll("[+]", "-"); // insert | append | replace the special characters from string_x000D_
    Log.e("Agilanbu finalVal  ", finalVal1);_x000D_
    o/p_x000D_
    Agilanbu finalVal : -3428  // replacing the + symbol to -
_x000D_
_x000D_
_x000D_

PHP: How to handle <![CDATA[ with SimpleXMLElement?

You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;

// or with parent element:

$foo = simplexml_load_string(
    '<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;

You might have better luck with LIBXML_NOCDATA:

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
    , null
    , LIBXML_NOCDATA
);

Invoking modal window in AngularJS Bootstrap UI using JavaScript

To make angular ui $modal work with bootstrap 3 you need to overwrite the styles

.modal {
    display: block;
}
.modal-body:before,
.modal-body:after {
    display: table;
    content: " ";
}
.modal-header:before,
.modal-header:after {
    display: table;
    content: " ";
}

(The last ones are necessary if you use custom directives) and encapsulate the html with

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      <h4 class="modal-title">Modal title</h4>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

How to use cURL to send Cookies?

If you have made that request in your application already, and see it logged in Google Dev Tools, you can use the copy cURL command from the context menu when right-clicking on the request in the network tab. Copy -> Copy as cURL. It will contain all headers, cookies, etc..

CSS: Control space between bullet and <li>

You can just give a padding-left to your <li> element.