Programs & Examples On #Dht

A Hash Table is a data structure used to store data in the form of Key=>Value pairs. A Distributed Hash Table (DHT) is basically a hash table distributed across a network of computers(nodes). A DHT uses a Routing Protocol to determine which node to store a piece of data on.

How does DHT in torrents work?

What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.

The original information bootstraps the later use of the DHT.

How do I create and read a value from cookie?

The chrome team has proposed a new way of managing cookies asynchronous with the Cookie Storage API (available in Google Chrome starting from version 87): https://wicg.github.io/cookie-store/

Use it already today with a polyfill for the other browsers: https://github.com/mkay581/cookie-store

// load polyfill
import 'cookie-store';

// set a cookie
await cookieStore.set('name', 'value');
// get a cookie
const savedValue = await cookieStore.get('name');

Difference between objectForKey and valueForKey?

As said, the objectForKey: datatype is :(id)aKey whereas the valueForKey: datatype is :(NSString *)key.

For example:

 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];

 NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);  
    //This will work fine and prints (    123    )  

 NSLog(@"valueForKey  : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]); 
    //it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'"   ---- This will crash on runtime. 

So, valueForKey: will take only a string value and is a KVC method, whereas objectForKey: will take any type of object.

The value in objectForKey will be accessed by the same kind of object.

Where does Chrome store extensions?

It is a bit late, but you can find it (windows 10 chrome 83)

%USERPROFILE%\AppData\Local\Google\Chrome\User Data\<your profile>\Extensions

Chrome now store it per profile. If you only have one profile, it's in a folder called Default

Regex replace uppercase with lowercase letters

Try this

  • Find: ([A-Z])([A-Z]+)\b
  • Replace: $1\L$2

Make sure case sensitivity is on (Alt + C)

Count distinct value pairs in multiple columns in SQL

Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:

SELECT count(DISTINCT concat(id, name, address)) FROM mytable;

Iterating over and deleting from Hashtable in Java

So you know the key, value pair that you want to delete in advance? It's just much clearer to do this, then:

 table.delete(key);
 for (K key: table.keySet()) {
    // do whatever you need to do with the rest of the keys
 }

How can I permanently enable line numbers in IntelliJ?

IntelliJ 14.X Onwards

From version 14.0 onwards, the path to the setting dialog is slightly different, a General submenu has been added between Editor and Appearance as shown below

enter image description here

IntelliJ 8.1.2 - 13.X

From IntelliJ 8.1.2 onwards, this option is in File | Settings1. Within the IDE Settings section of that dialog, you'll find it under Editor | Appearance.

  1. On a Mac, these are named IntelliJ IDEA | Preferences...

enter image description here

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

You have to make sure the application is uninstalled.

In your phone, try going to settings/applications and show the list of all your installed applications, then make sure the application is uninstalled for all users (in my case I had uninstalled the application but still for others).

I want to calculate the distance between two points in Java

This may be OLD, but here is the best answer:

    float dist = (float) Math.sqrt(
            Math.pow(x1 - x2, 2) +
            Math.pow(y1 - y2, 2) );

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

As I mentioned in this answer, if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

Note that HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

As others have noted, the two also differ when using IPv6:

$_SERVER['HTTP_HOST'] == '[::1]'
$_SERVER['SERVER_NAME'] == '::1'

Check if an array is empty or exists

For me sure some of the high rated answers "work" when I put them into jsfiddle, but when I have a dynamically generated amount of array list a lot of this code in the answers just doesn't work for ME.

This is what IS working for me.

var from = [];

if(typeof from[0] !== undefined) {
  //...
}

Notice, NO quotes around undefined and I'm not bothering with the length.

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

How to install PyQt4 in anaconda?

Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:

conda install pyqt=4

This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example

conda install pyqt=4.11

would install the latest (or last) release of version 4.11.

Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.

How to display a list using ViewBag

I had the problem that I wanted to use my ViewBag to send a list of elements through a RenderPartial as the object, and to this you have to do the cast first, I had to cast the ViewBag in the controller and in the View too.

In the Controller:

ViewBag.visitList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)                                                                 
visitaRepo.ObtenerLista().Where(m => m.Id_Contacto == id).ToList()

In the View:

List<CLIENTES_VIP_DB.VISITAS.VISITA> VisitaList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)ViewBag.visitList ;

Python dict how to create key or append an element to key?

You can use defaultdict in collections.

An example from doc:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

Setting Icon for wpf application (VS 08)

After getting a XamlParseException with message: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' with the given solutions, setting the icon programmatically worked for me. This is how I did it:

  1. Put the icon in a folder <icon_path> in the project directory
  2. Mimic the folder path <icon_path> in the solution
  3. Add a new item (your icon) in the solution folder you created
  4. Add the following code in the WPF window's code behind:

Icon = new BitmapImage(new Uri("<icon_path>", UriKind.Relative));

Please inform me if you have any difficulties implementing this solution so I can help.

Search all tables, all columns for a specific value SQL Server

I published one here: FullParam SQL Blog

/* Reto Egeter, fullparam.wordpress.com */

DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))

WHILE @TableName IS NOT NULL
BEGIN
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
    )
    IF @TableName IS NOT NULL
    BEGIN
        DECLARE @sql VARCHAR(MAX)
        SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''' + @TableName + ''', 2)
                AND TABLE_NAME  = PARSENAME(''' + @TableName + ''', 1)
                AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
                AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END  + ',COLUMN_NAME)'
        INSERT INTO @ColumnNameTable
        EXEC (@sql)
        WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
        BEGIN
            PRINT @ColumnName
            SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
            SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),''' 
            WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
            ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + ''' 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
            INSERT INTO #Results
            EXEC(@sql)
            IF @@ROWCOUNT > 0 IF @FullRowResult = 1 
            BEGIN
                SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
                    ' FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
                EXEC(@sql)
            END
            DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
        END 
    END
END
SET NOCOUNT OFF

SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType

Pure CSS scroll animation

You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010

How to kill a child process after a given timeout in Bash?

# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) &

or to get the exit codes as well:

# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) & waiter=$!
# wait on our worker process and return the exitcode
exitcode=$(wait $pid && echo $?)
# kill the waiter subshell, if it still runs
kill -9 $waiter 2>/dev/null
# 0 if we killed the waiter, cause that means the process finished before the waiter
finished_gracefully=$?

Find a value anywhere in a database

Another way using JOIN and CURSOR:

USE My_Database;

-- Store results in a local temp table so that.  I'm using a
-- local temp table so that I can access it in SP_EXECUTESQL.
create table #tmp (
    tbl nvarchar(max),
    col nvarchar(max),
    val nvarchar(max)   
);

declare @tbl nvarchar(max);
declare @col nvarchar(max);
declare @q nvarchar(max);
declare @search nvarchar(max) = 'my search key';

-- Create a cursor on all columns in the database
declare c cursor for
SELECT tbls.TABLE_NAME, cols.COLUMN_NAME  FROM INFORMATION_SCHEMA.TABLES AS tbls
JOIN INFORMATION_SCHEMA.COLUMNS AS cols
ON tbls.TABLE_NAME = cols.TABLE_NAME

-- For each table and column pair, see if the search value exists.
open c
fetch next from c into @tbl, @col
while @@FETCH_STATUS = 0
begin
    -- Look for the search key in current table column and if found add it to the results.
    SET @q = 'INSERT INTO #tmp SELECT ''' + @tbl + ''', ''' + @col + ''', ' + @col + ' FROM ' + @tbl + ' WHERE ' + @col + ' LIKE ''%' + @search + '%'''
    EXEC SP_EXECUTESQL @q
    fetch next from c into @tbl, @col
end
close c
deallocate c

-- Get results
select * from #tmp

-- Remove local temp table.
drop table #tmp

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Use a library instead

We don't have to reinvent the wheel. Just use a library to save the time and headache.

js-base64

https://github.com/dankogai/js-base64 is good and I confirm it supports unicode very well.

Base64.encode('dankogai');  // ZGFua29nYWk=
Base64.encode('???');    // 5bCP6aO85by+
Base64.encodeURI('???'); // 5bCP6aO85by-

Base64.decode('ZGFua29nYWk=');  // dankogai
Base64.decode('5bCP6aO85by+');  // ???
// note .decodeURI() is unnecessary since it accepts both flavors
Base64.decode('5bCP6aO85by-');  // ???

How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

    public interface IFileProxy {
        void Delete(string path);
    }

    public class FileProxy : IFileProxy {
        public void Delete(string path) {
            System.IO.File.Delete(path);
        }
    }

    public class MyClass {

        private IFileProxy _fileProxy;

        public MyClass(IFileProxy fileProxy) {
            _fileProxy = fileProxy;
        }

        public void DoSomethingAndDeleteFile(string path) {
            // Do Something with file
            // ...
            // Delete
            System.IO.File.Delete(path);
        }

        public void DoSomethingAndDeleteFileUsingProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            _fileProxy.Delete(path);

        }
    }

The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

   public static class FileServices {

        static FileServices() {
            Reset();
        }

        internal static IFileProxy FileProxy { private get; set; }

        public static void Reset(){
           FileProxy = new FileProxy();
        }

        public static void Delete(string path) {
            FileProxy.Delete(path);
        }

    }

Our method now becomes

    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            FileServices.Delete(path);

    }

For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

How to send a JSON object using html form data

Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.

$.ajax({
  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});

How to identify platform/compiler from preprocessor macros?

If you're writing C++, I can't recommend using the Boost libraries strongly enough.

The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.

#include <boost/predef.h>

// ...

#if BOOST_OS_WINDOWS

#elif BOOST_OS_LINUX

#elif BOOST_OS_MACOS

#endif

How to use Global Variables in C#?

A useful feature for this is using static

As others have said, you have to create a class for your globals:

public static class Globals {
    public const float PI = 3.14;
}

But you can import it like this in order to no longer write the class name in front of its static properties:

using static Globals;
[...]
Console.WriteLine("Pi is " + PI);

How to run a shell script in OS X by double-clicking?

Have you tried using the .command filename extension?

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

Looping through rows in a DataView

//You can convert DataView to Table. using DataView.ToTable();

foreach (DataRow drGroup in dtGroups.Rows)
{
    dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";

    if (dtForms.DefaultView.Count > 0)
    {
        foreach (DataRow drForm in dtForms.DefaultView.ToTable().Rows)
        {
            drNew = dtNew.NewRow();

            drNew["FormId"] = drForm["FormId"];
            drNew["FormCaption"] = drForm["FormCaption"];
            drNew["GroupName"] = drGroup["GroupName"];
            dtNew.Rows.Add(drNew);
        }
    }
}

// Or You Can Use

// 2.

dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";

DataTable DTFormFilter = dtForms.DefaultView.ToTable();

foreach (DataRow drFormFilter in DTFormFilter.Rows)
{ 
                            //Your logic goes here
}

javascript set cookie with expire time

Below are code snippets to create and delete a cookie. The cookie is set for 1 day.

// 1 Day = 24 Hrs = 24*60*60 = 86400.
  1. By using max-age:

    • Creating the cookie:

    document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";
    
    • Deleting the cookie:

    document.cookie = "cookieName=; max-age=- (any digit); path=/;";
    
  2. By using expires:

    • Syntax for creating the cookie for one day:

    var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
    document.cookie = "cookieName=cookieValue; expires=" + expires + 86400) + ";path=/;"
    

using scp in terminal

Simple :::

scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy

scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy

SQL query, if value is null then return 1

SELECT orderhed.ordernum, orderhed.orderdate, currrate.currencycode,  

case(currrate.currentrate) when null then 1 else currrate.currentrate end

FROM orderhed LEFT OUTER JOIN currrate ON orderhed.company = currrate.company AND orderhed.orderdate = currrate.effectivedate  

New line in Sql Query

-- Access: 
SELECT CHR(13) & CHR(10) 

-- SQL Server: 
SELECT CHAR(13) + CHAR(10)

sqlalchemy IS NOT NULL select

Starting in version 0.7.9 you can use the filter operator .isnot instead of comparing constraints, like this:

query.filter(User.name.isnot(None))

This method is only necessary if pep8 is a concern.

source: sqlalchemy documentation

How to suppress Pandas Future warning ?

@bdiamante's answer may only partially help you. If you still get a message after you've suppressed warnings, it's because the pandas library itself is printing the message. There's not much you can do about it unless you edit the Pandas source code yourself. Maybe there's an option internally to suppress them, or a way to override things, but I couldn't find one.


For those who need to know why...

Suppose that you want to ensure a clean working environment. At the top of your script, you put pd.reset_option('all'). With Pandas 0.23.4, you get the following:

>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)

C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning: html.bord
er has been deprecated, use display.html.border instead
(currently both are identical)

  warnings.warn(d.msg, FutureWarning)

: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning:
: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

  warnings.warn(d.msg, FutureWarning)

>>>

Following the @bdiamante's advice, you use the warnings library. Now, true to it's word, the warnings have been removed. However, several pesky messages remain:

>>> import warnings
>>> warnings.simplefilter(action='ignore', category=FutureWarning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)


: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

>>>

In fact, disabling all warnings produces the same output:

>>> import warnings
>>> warnings.simplefilter(action='ignore', category=Warning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)


: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

>>>

In the standard library sense, these aren't true warnings. Pandas implements its own warnings system. Running grep -rn on the warning messages shows that the pandas warning system is implemented in core/config_init.py:

$ grep -rn "html.border has been deprecated"
core/config_init.py:207:html.border has been deprecated, use display.html.border instead

Further chasing shows that I don't have time for this. And you probably don't either. Hopefully this saves you from falling down the rabbit hole or perhaps inspires someone to figure out how to truly suppress these messages!

How do you check if a certain index exists in a table?

You can do it using a straight forward select like this:

SELECT * 
FROM sys.indexes 
WHERE name='YourIndexName' AND object_id = OBJECT_ID('Schema.YourTableName')

What is the difference between json.load() and json.loads() functions

Documentation is quite clear: https://docs.python.org/2/library/json.html

json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.

So load is for a file, loads for a string

How to create a oracle sql script spool file

In order to execute a spool file in plsql Go to File->New->command window -> paste your code-> execute. Got to the directory and u will find the file.

Generate an integer sequence in MySQL

Counter from 1 to 1000:

  • no need to create a table
  • time to execute ~ 0.0014 sec
  • can be converted into a view
    select tt.row from
    (
    SELECT cast( concat(t.0,t2.0,t3.0) + 1 As UNSIGNED) as 'row' FROM 
    (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t,
    (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2, 
    (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3
    ) tt
    order by tt.row

Credits: answer, comment by Seth McCauley below the answer.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

Add 'NgbModalModule' in imports and your component name in entryComponents App.module.ts as shown below enter image description here

Retrieve only the queried element in an object array in MongoDB collection

Along with $project it will be more appropriate other wise matching elements will be clubbed together with other elements in document.

db.test.aggregate(
  { "$unwind" : "$shapes" },
  { "$match" : { "shapes.color": "red" } },
  { 
    "$project": {
      "_id":1,
      "item":1
    }
  }
)

Environment variables in Mac OS X

If you want to change environment variables permanently on macOS, set them in /etc/paths. Note, this file is read-only by default, so you'll have to chmod for write permissions.

.NET - How do I retrieve specific items out of a Dataset?

You can do like...

If you want to access using ColumnName

Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0]["column4Name"].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0]["column5Name"].ToString());

OR, if you want to access using Index

Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0][4].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0][5].ToString());

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

How do I write data to csv file in columns and rows from a list in python?

Have a go with these code:

>>> import pyexcel as pe
>>> sheet = pe.Sheet(data)
>>> data=[[1, 2], [2, 3], [4, 5]]
>>> sheet
Sheet Name: pyexcel
+---+---+
| 1 | 2 |
+---+---+
| 2 | 3 |
+---+---+
| 4 | 5 |
+---+---+
>>> sheet.save_as("one.csv")
>>> b = [[126, 125, 123, 122, 123, 125, 128, 127, 128, 129, 130, 130, 128, 126, 124, 126, 126, 128, 129, 130, 130, 130, 130, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 134, 134, 134, 134, 134, 134, 134, 134, 133, 134, 135, 134, 133, 133, 134, 135, 136], [135, 135, 136, 137, 137, 136, 134, 135, 135, 135, 134, 134, 133, 133, 133, 134, 134, 134, 133, 133, 132, 132, 132, 135, 135, 133, 133, 133, 133, 135, 135, 131, 135, 136, 134, 133, 136, 137, 136, 133, 134, 135, 136, 136, 135, 134, 133, 133, 134, 135, 136, 136, 136, 135, 134, 135, 138, 138, 135, 135, 138, 138, 135, 139], [137, 135, 136, 138, 139, 137, 135, 142, 139, 137, 139, 138, 136, 137, 141, 138, 138, 139, 139, 139, 139, 138, 138, 138, 138, 137, 137, 137, 137, 138, 138, 136, 137, 137, 137, 137, 137, 137, 138, 148, 144, 140, 138, 137, 138, 138, 138, 137, 137, 137, 137, 137, 138, 139, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141], [141, 141, 141, 141, 141, 141, 141, 139, 139, 139, 140, 140, 141, 141, 141, 140, 140, 140, 140, 140, 141, 142, 143, 138, 138, 138, 139, 139, 140, 140, 140, 141, 140, 139, 139, 141, 141, 140, 139, 145, 137, 137, 145, 145, 137, 137, 144, 141, 139, 146, 134, 145, 140, 149, 144, 145, 142, 140, 141, 144, 145, 142, 139, 140]]
>>> s2 = pe.Sheet(b)
>>> s2
Sheet Name: pyexcel
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 126 | 125 | 123 | 122 | 123 | 125 | 128 | 127 | 128 | 129 | 130 | 130 | 128 | 126 | 124 | 126 | 126 | 128 | 129 | 130 | 130 | 130 | 130 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 133 | 134 | 135 | 134 | 133 | 133 | 134 | 135 | 136 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 135 | 135 | 136 | 137 | 137 | 136 | 134 | 135 | 135 | 135 | 134 | 134 | 133 | 133 | 133 | 134 | 134 | 134 | 133 | 133 | 132 | 132 | 132 | 135 | 135 | 133 | 133 | 133 | 133 | 135 | 135 | 131 | 135 | 136 | 134 | 133 | 136 | 137 | 136 | 133 | 134 | 135 | 136 | 136 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | 136 | 136 | 135 | 134 | 135 | 138 | 138 | 135 | 135 | 138 | 138 | 135 | 139 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 137 | 135 | 136 | 138 | 139 | 137 | 135 | 142 | 139 | 137 | 139 | 138 | 136 | 137 | 141 | 138 | 138 | 139 | 139 | 139 | 139 | 138 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 138 | 138 | 136 | 137 | 137 | 137 | 137 | 137 | 137 | 138 | 148 | 144 | 140 | 138 | 137 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 137 | 138 | 139 | 140 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 141 | 141 | 141 | 141 | 141 | 141 | 141 | 139 | 139 | 139 | 140 | 140 | 141 | 141 | 141 | 140 | 140 | 140 | 140 | 140 | 141 | 142 | 143 | 138 | 138 | 138 | 139 | 139 | 140 | 140 | 140 | 141 | 140 | 139 | 139 | 141 | 141 | 140 | 139 | 145 | 137 | 137 | 145 | 145 | 137 | 137 | 144 | 141 | 139 | 146 | 134 | 145 | 140 | 149 | 144 | 145 | 142 | 140 | 141 | 144 | 145 | 142 | 139 | 140 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
>>> s2[0,0]
126
>>> s2.save_as("two.csv")

HTTPS connections over proxy servers

Here is my complete Java code that supports both HTTP and HTTPS requests using SOCKS proxy.

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;

/**
 * How to send a HTTP or HTTPS request via SOCKS proxy.
 */
public class ClientExecuteSOCKS {

    public static void main(String[] args) throws Exception {
        Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new MyHTTPConnectionSocketFactory())
            .register("https", new MyHTTPSConnectionSocketFactory(SSLContexts.createSystemDefault
                ()))
            .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
        try (CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(cm)
            .build()) {
            InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
            HttpClientContext context = HttpClientContext.create();
            context.setAttribute("socks.address", socksaddr);

            HttpHost target = new HttpHost("www.example.com/", 80, "http");
            HttpGet request = new HttpGet("/");

            System.out.println("Executing request " + request + " to " + target + " via SOCKS " +
                "proxy " + socksaddr);
            try (CloseableHttpResponse response = httpclient.execute(target, request, context)) {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity(), StandardCharsets
                    .UTF_8));
            }
        }
    }

    static class MyHTTPConnectionSocketFactory extends PlainConnectionSocketFactory {
        @Override
        public Socket createSocket(final HttpContext context) throws IOException {
            InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
            return new Socket(proxy);
        }
    }

    static class MyHTTPSConnectionSocketFactory extends SSLConnectionSocketFactory {
        public MyHTTPSConnectionSocketFactory(final SSLContext sslContext) {
            super(sslContext);
        }

        @Override
        public Socket createSocket(final HttpContext context) throws IOException {
            InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
            return new Socket(proxy);
        }
    }
}

Eclipse java debugging: source not found

Info: This is a possible solution, when you use maven (pom.xml) with couple of projects.

If you are working with maven, make sure what version you are taking inside the according pom.xml (e. g. 1.0.1-SNAPSHOT ). It might be possible that your code is up-to-date, but your pom.xml dependencies are still taking the old JAR's/Snapshots (with the old code).

Finding the problem:

  • Try to debug the according file.
  • Therefore, set a breakpoint in the relevant code area.
  • When "source not found" appears, make sure to bind in the right project (where the .java file can be found).
  • The compile .class file opens up in the IDE editor.
  • Click "Link with Editor" to find the according JAR/Snapshot.
  • Now make sure that this JAR is the most recent one. Possibly there is a newer one. In that case, write the most recent version number in the pom.xml.
  • Then do a maven update and build (e. g. "mvn clean install -U") in the right project directory.

CodeIgniter 404 Page Not Found, but why?

we have to give the controller name in lower cases in server side

$this->class = strtolower(__CLASS__);

How can I find the dimensions of a matrix in Python?

The correct answer is the following:

import numpy 
numpy.shape(a)

In Angular, how to add Validator to FormControl after control is created?

You simply pass the FormControl an array of validators.

Here's an example showing how you can add validators to an existing FormControl:

this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);

Note, this will reset any existing validators you added when you created the FormControl.

Having issues with a MySQL Join that needs to meet multiple conditions

also this should work (not tested):

SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc

If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

CREATE TABLE LIKE A1 as A2

You can use below query to create table and insert distinct values into this table:

Select Distinct Column1, Column2, Column3 into New_Users from Old_Users

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.

EDIT

Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 

EDIT

It seems you have no-semicolons whatsoever.

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

SQLRecoverableException: I/O Exception: Connection reset

This simply means that something in the backend ( DBMS ) decided to stop working due to unavailability of resources etc. It has nothing to do with your code or the number of inserts. You can read more about similar problems here:

This may not answer your question, but you will get an idea of why it might be happening. You could further discuss with your DBA and see if there is something specific in your case.

Pandas groupby: How to get a union of strings

Named aggregations with pandas >= 0.25.0

Since pandas version 0.25.0 we have named aggregations where we can groupby, aggregate and at the same time assign new names to our columns. This way we won't get the MultiIndex columns, and the column names make more sense given the data they contain:


aggregate and get a list of strings

grp = df.groupby('A').agg(B_sum=('B','sum'),
                          C=('C', list)).reset_index()

print(grp)
   A     B_sum               C
0  1  1.615586  [This, string]
1  2  0.421821         [is, !]
2  3  0.463468             [a]
3  4  0.643961        [random]

aggregate and join the strings

grp = df.groupby('A').agg(B_sum=('B','sum'),
                          C=('C', ', '.join)).reset_index()

print(grp)
   A     B_sum             C
0  1  1.615586  This, string
1  2  0.421821         is, !
2  3  0.463468             a
3  4  0.643961        random

Execution failed app:processDebugResources Android Studio

For me it was that I forgot to install the 32bit dependencies:

sudo apt-get install -y lib32gcc1 libc6-i386 lib32z1 lib32stdc++6
sudo apt-get install -y lib32ncurses5 lib32gomp1 lib32z1-dev lib32bz2-dev

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

How to access first element of JSON object array?

the event property seems to be string first you have to parse it to json :

 var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
 var event = JSON.parse(req.mandrill_events);
 var ts =  event[0].ts

Python 3 Building an array of bytes

what about simply constructing your frame from a standard list ?

frame = bytes([0xA2,0x01,0x02,0x03,0x04])

the bytes() constructor can build a byte frame from an iterable containing int values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()...

Get custom product attributes in Woocommerce

Although @airdrumz solutions works, you will get lots of errors about you doing it wrong by accessing ID directly, this is not good for future compatibility.

But it lead me to inspect the object and create this OOP approach:

function myplug_get_prod_attrs() {
    // Enqueue scripts happens very early, global $product has not been created yet, neither has the post/loop
    global $product;
    $wc_attr_objs = $product->get_attributes();
    $prod_attrs = [];
    foreach ($wc_attr_objs as $wc_attr => $wc_term_objs) {
        $prod_attrs[$wc_attr] = [];
        $wc_terms = $wc_term_objs->get_terms();
        foreach ($wc_terms as $wc_term) {
            array_push($prod_attrs[$wc_attr], $wc_term->slug);
        }
    }
    return $prod_attrs;
}

Bonus, if you are performing the above early before the global $product item is created (e.g. during enqueue scripts), you can make it yourself with:

    $product = wc_get_product(get_queried_object_id());

Start/Stop and Restart Jenkins service on Windows

Small hints for routine work.

Create a bat file, name it and use for exact run/stop/restart Jenkins service

#!/bin/bash
# go to Jenkins folder
cd C:\Program Files (x86)\Jenkins

#to stop:
jenkins.exe stop

#to start:
#jenkins.exe start

#to restart:
#jenkins.exe restart

A generic list of anonymous class

You can do this in your code.

var list = new[] { new { Id = 1, Name = "Foo" } }.ToList();
list.Add(new { Id = 2, Name = "Bar" });

ImportError: No module named pip

Tested below for Linux: You can directly download pip from https://pypi.org/simple/pip/ untar and use directly with your latest python.

tar -xvf  pip-0.2.tar.gz
cd pip-0.2

Check for the contents.

anant$ ls
docs  pip.egg-info  pip-log.txt  pip.py  PKG-INFO  regen-docs  scripts  setup.cfg  setup.py  tests

Execute directly:

anant$ python pip.py --help
Usage: pip.py COMMAND [OPTIONS]

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -E DIR, --environment=DIR
                        virtualenv environment to run pip in (either give the
                        interpreter or the environment base directory)
  -v, --verbose         Give more output
  -q, --quiet           Give less output
  --log=FILENAME        Log file where a complete (maximum verbosity) record
                        will be kept
  --proxy=PROXY         Specify a proxy in the form
                        user:[email protected]:port. Note that the
                        user:password@ is optional and required only if you
                        are behind an authenticated proxy.  If you provide
                        [email protected]:port then you will be prompted for a
                        password.
  --timeout=SECONDS     Set the socket timeout (default 15 seconds)

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

Using .text() to retrieve only text not nested in child tags

just put it in a <p> or <font> and grab that $('#listItem font').text()

First thing that came to mind

<li id="listItem">
    <font>This is some text</font>
    <span id="firstSpan">First span text</span>
    <span id="secondSpan">Second span text</span>
</li>

Reading a plain text file in Java

Cactoos give you a declarative one-liner:

new TextOf(new File("a.txt")).asString();

CASE in WHERE, SQL Server

Try this:

WHERE a.Country = (CASE WHEN @Country > 0 THEN @Country ELSE a.Country END)

How to make a form close when pressing the escape key?

Paste this code into the "On Key Down" Property of your form, also make sure you set "Key Preview" Property to "Yes".

If KeyCode = vbKeyEscape Then DoCmd.Close acForm, "YOUR FORM NAME"

Prevent text selection after double click

Old thread, but I came up with a solution that I believe is cleaner since it does not disable every even bound to the object, and only prevent random and unwanted text selections on the page. It is straightforward, and works well for me. Here is an example; I want to prevent text-selection when I click several time on the object with the class "arrow-right":

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH !

auto create database in Entity Framework Core

If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  LoggerFactory loggerFactory,
    ApplicationDbContext context)
 {
      context.Database.Migrate();
      ...

How do I get the base URL with PHP?

In my case I needed the base URL similar to the RewriteBasecontained in the .htaccess file.

Unfortunately simply retrieving the RewriteBase from the .htaccess file is impossible with PHP. But it is possible to set an environment variable in the .htaccess file and then retrieve that variable in PHP. Just check these bits of code out:

.htaccess

SetEnv BASE_PATH /

index.php

Now I use this in the base tag of the template (in the head section of the page):

<base href="<?php echo ! empty( getenv( 'BASE_PATH' ) ) ? getenv( 'BASE_PATH' ) : '/'; ?>"/>

So if the variable was not empty, we use it. Otherwise fallback to / as default base path.

Based on the environment the base url will always be correct. I use / as the base url on local and production websites. But /foldername/ for on the staging environment.

They all had their own .htaccess in the first place because the RewriteBase was different. So this solution works for me.

What is the difference between \r and \n?

\r is used to point to the start of a line and can replace the text from there, e.g.

main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}

Produces this output:

hai

\n is for new line.

JavaScript displaying a float to 2 decimal places

Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:

var num = response_from_a_function_or_something();

var fixedNum = parseFloat(num).toFixed( 2 );

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

How do I delete NuGet packages that are not referenced by any project in my solution?

If you have removed package using Uninstall-Package utility and deleted the desired package from package directory under solution (and you are still getting error), just open up the *.csproj file in code editor and remove the tag manually. Like for instance, I wanted to get rid of Nuget package Xamarin.Forms.Alias and I removed these lines from *.csproj file.

Removing nuget package from msbuild script

And finally, don't forget to reload your project once prompted in Visual Studio (after changing project file). I tried it on Visual Studio 2015, but it should work on Visual Studio 2010 and onward too.

Hope this helps.

When does Java's Thread.sleep throw InterruptedException?

The InterruptedException is usually thrown when a sleep is interrupted.

Proper use of the IDisposable interface

The most justifiable use case for disposal of managed resources, is preparation for the GC to reclaim resources that would otherwise never be collected.

A prime example is circular references.

Whilst it's best practice to use patterns that avoid circular references, if you do end up with (for example) a 'child' object that has a reference back to its 'parent', this can stop GC collection of the parent if you just abandon the reference and rely on GC - plus if you have implemented a finalizer, it'll never be called.

The only way round this is to manually break the circular references by setting the Parent references to null on the children.

Implementing IDisposable on parent and children is the best way to do this. When Dispose is called on the Parent, call Dispose on all Children, and in the child Dispose method, set the Parent references to null.

REST, HTTP DELETE and parameters

In addition to Alex's answer:

Note that http://server/resource/id?force_delete=true identifies a different resource than http://server/resource/id. For example, it is a huge difference whether you delete /customers/?status=old or /customers/.

Open youtube video in Fancybox jquery

$("a.more").click(function() {
                 $.fancybox({
                  'padding'             : 0,
                  'autoScale'   : false,
                  'transitionIn'        : 'none',
                  'transitionOut'       : 'none',
                  'title'               : this.title,
                  'width'               : 680,
                  'height'              : 495,
                  'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                  'type'                : 'swf',    // <--add a comma here
                  'swf'                 : {'allowfullscreen':'true'} // <-- flashvars here
                  });
                 return false;

            }); 

Error: "Could Not Find Installable ISAM"

Try putting single quotes around the data source:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb';

The problem tends to be white space which does have meaning to the parser.

If you had other attributes (e.g., Extended Properties), their values may also have to be enclosed in single quotes:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb'; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';

You could equally well use double quotes; however, you'll probably have to escape them, and I find that more of a Pain In The Algorithm than using singles.

Why am I getting this redefinition of class error?

You define the class gameObject in both your .cpp file and your .h file.
That is creating a redefinition error.

You should define the class, ONCE, in ONE place. (convention says the definition is in the .h, and all the implementation is in the .cpp)

Please help us understand better, what part of the error message did you have trouble with?

The first part of the error says the class has been redefined in gameObject.cpp
The second part of the error says the previous definition is in gameObject.h.

How much clearer could the message be?

Change image source with JavaScript

function changeImage(a) so there is no such thing as a.src => just use a.

demo here

Get the item doubleclick event of listview

The sender is of type ListView not ListViewItem.

    private void listViewTriggers_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        ListView triggerView = sender as ListView;
        if (triggerView != null)
        {
            btnEditTrigger_Click(null, null);
        }
    }

Pie chart with jQuery

Flot

Limitations: lines, points, filled areas, bars, pie and combinations of these

From an interaction perspective, Flot by far will get you as close as possible to Flash graphing as you can get with jQuery. Whilst the graph output is pretty slick, and great looking, you can also interact with data points. What I mean by this is you can have the ability to hover over a data point and get visual feedback on the value of that point in the graph.

The trunk version of flot supports pie charts.

Flot Zoom capability.

On top of this, you also have the ability to select a chunk of the graph to get data back for a particular “zone”. As a secondary feature to this “zoning”, you can also select an area on a graph and zoom in to see the data points a little more closely. Very cool.


Sparklines

Limitations: Pie, Line, Bar, Combination

Sparklines is my favourite mini graphing tool out there. Really great for dashboard style graphs (think Google Analytics dashboard next time you login). Because they’re so tiny, they can be included in line (as in the example above). Another nice idea which can be used in all graphing plugins is the self-refresh capabilities. Their Mouse-Speed demo shows you the power of live charting at its best.


Query Chart 0.21

Limitations: Area, Line, Bar and combinations of these

jQuery Chart 0.21 isn’t the nicest looking charting plugin out there it has to be said. It’s pretty basic in functionality when it comes to the charts it can handle, however it can be flexible if you can put in some time and effort into it.

Adding values into a chart is relatively simple:

.chartAdd({

    "label"  : "Leads",
    "type"   : "Line",
    "color"  : "#008800",
    "values" : ["100","124","222","44","123","23","99"]
});

jQchart

Limitations: Bar, Line

jQchart is an odd one, they’ve built in animation transistions and drag/drop functionality into the chart, however it’s a little clunky – and seemingly pointless. It does generate nice looking charts if you get the CSS setup right, but there are better out there.


TufteGraph

Limitations: Bar and Stacked Bar

Tuftegraph sells itself as “pretty bar graphs that you would show your mother”. It comes close, Flot is prettier, but Tufte does lend itself to be very lightweight. Although with that comes restrictions – there are few options to choose from, so you get what you’re given. Check it out for a quick win bar chart.

How to scroll table's "tbody" independent of "thead"?

thead {
  position: fixed;
  height: 10px; /* This is whatever height you want */
}
  tbody {
  position: fixed;
  margin-top: 10px; /* This has to match the height of thead */
  height: 300px; /* This is whatever height you want */
}

How to make a div 100% height of the browser window

Try the following CSS:

html {
    min-height: 100%;
    margin: 0;
    padding: 0;
}

body {
    height: 100%;
}

#right {
    min-height: 100%;
}

HTML Tags in Javascript Alert() method

This is not possible.

Instead, you should create a fake window in Javascript, using something like jQuery UI Dialog.

Error: Unexpected value 'undefined' imported by the module

I met this problem at the situation: - app-module --- app-routing // app router ----- imports: [RouterModule.forRoot(routes)] --- demo-module // sub-module ----- demo-routing ------- imports: [RouterModule.forRoot(routes)] // --> should be RouterModule.forChild!

because there is only a root.

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

If you are extending ActionBarActivity in your MainActivity, you will have to change the parent theme in values-v11 also.
So the style.xml in values-v11 will be -

 <!-- res/values-v11/themes.xml -->
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
    <style name="QueryTheme" parent="@style/Theme.AppCompat">
    <!-- Any customizations for your app running on devices with Theme.Holo here -->
    </style>
 </resources>

EDIT: I would recommend you stop using ActionBar and start using the AppBar layout included in the Android Design Support Library

Difference between 'struct' and 'typedef struct' in C++?

An important difference between a 'typedef struct' and a 'struct' in C++ is that inline member initialisation in 'typedef structs' will not work.

// the 'x' in this struct will NOT be initialised to zero
typedef struct { int x = 0; } Foo;

// the 'x' in this struct WILL be initialised to zero
struct Foo { int x = 0; };

what's the easiest way to put space between 2 side-by-side buttons in asp.net

create a divider class as follows:

.divider{
    width:5px;
    height:auto;
    display:inline-block;
}

Then attach this to a div between the two buttons

<div style="text-align: center"> 
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
    <div class="divider"/>
    <asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>

This is the best way as it avoids the box model, which can be a pain on older browsers, and doesn't add any extra characters that would be picked up by a screen reader, so it is better for readability.

It's good to have a number of these types of divs for certain scenarios (my most used one is vert5spacer, similar to this but puts a block div with height 5 and width auto for spacing out items in a form etc.

how to calculate binary search complexity

Let me make it easy for all of you with an example.

For simplicity purpose, let's assume there are 32 elements in an array in the sorted order out of which we are searching for an element using binary search.

1 2 3 4 5 6 ... 32

Assume we are searching for 32. after the first iteration, we will be left with

17 18 19 20 .... 32

after the second iteration, we will be left with

25 26 27 28 .... 32

after the third iteration, we will be left with

29 30 31 32

after the fourth iteration, we will be left with

31 32

In the fifth iteration, we will find the value 32.

So, If we convert this into a mathematical equation, we will get

(32 X (1/25)) = 1

=> n X (2-k) = 1

=> (2k) = n

=> k log22 = log2n

=> k = log2n

Hence the proof.

open failed: EACCES (Permission denied)

Also I found solving for my way.

Before launch app i granted root to file-explorer and did not disable permission on write/read when exit from app.

My app can not use external memory while i did restrat device for resetting all permissions.

Android LinearLayout : Add border with shadow around a LinearLayout

As an alternative, you might use a 9 patch image as the background for your layout, allowing for more "natural" shadows:

enter image description here

Result:

enter image description here

Put the image in your /res/drawable folder.
Make sure the file extension is .9.png, not .png

By the way, this is a modified (reduced to the minimum square size) of an existing resource found in the API 19 sdk resources folder.
I left the red markers, since they don't seem to be harmful, as shown in the draw9patch tool.

[EDIT]

About 9 patches, in case you never had anything to do with them.

Simply add it as the background of your View.

The black-marked areas (left and top) will stretch (vertically, horizontally).
The black-marked areas (right, bottom) define the "content area" (where it's possible to add text or Views - you can call the unmarked regions "padding", if you like to).

Tutorial: http://radleymarx.com/blog/simple-guide-to-9-patch/

Angular HttpClient "Http failure during parsing"

I had the same problem and the cause was That at time of returning a string in your backend (spring) you might be returning as return "spring used"; But this isn't parsed right according to spring. Instead use return "\" spring used \""; -Peace out

Using AJAX to pass variable to PHP and retrieve those using AJAX again

you have to pass values with the single quotes

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: '145'}), //variables should be pass like this
            success: function(data){
                console.log(data);
                           }
        });  
        $.ajax({
    url:'ajax.php',
    data:"",
    dataType:'json',
    success:function(data1){
            var y1=data1;
            console.log(data1);
            }
        });

    });
});

try it it may work.......

python: How do I know what type of exception occurred?

Here's how I'm handling my exceptions. The idea is to do try solving the issue if that's easy, and later add a more desirable solution if possible. Don't solve the issue in the code that generates the exception, or that code loses track of the original algorithm, which should be written to-the-point. However, pass what data is needed to solve the issue, and return a lambda just in case you can't solve the problem outside of the code that generates it.

path = 'app.p'

def load():
    if os.path.exists(path):
        try:
            with open(path, 'rb') as file:
                data = file.read()
                inst = pickle.load(data)
        except Exception as e:
            inst = solve(e, 'load app data', easy=lambda: App(), path=path)()
    else:
        inst = App()
    inst.loadWidgets()

# e.g. A solver could search for app data if desc='load app data'
def solve(e, during, easy, **kwargs):
    class_name = e.__class__.__name__
    print(class_name + ': ' + str(e))
    print('\t during: ' + during)
    return easy

For now, since I don't want to think tangentially to my app's purpose, I haven't added any complicated solutions. But in the future, when I know more about possible solutions (since the app is designed more), I could add in a dictionary of solutions indexed by during.

In the example shown, one solution might be to look for app data stored somewhere else, say if the 'app.p' file got deleted by mistake.

For now, since writing the exception handler is not a smart idea (we don't know the best ways to solve it yet, because the app design will evolve), we simply return the easy fix which is to act like we're running the app for the first time (in this case).

Change a Nullable column to NOT NULL with Default Value

I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.

ALTER TABLE dbo.MyTable
ADD CONSTRAINT my_Con DEFAULT GETDATE() for created

UPDATE MyTable SET Created = GetDate() where Created IS NULL

ALTER TABLE dbo.MyTable 
ALTER COLUMN Created DATETIME NOT NULL 

How to check whether dynamically attached event listener exists or not?

There is no way to check whether dynamically attached event listeners exist or not.

The only way you can see if an event listener is attached is by attaching event listeners like this:

elem.onclick = function () { console.log (1) }

You can then test if an event listener was attached to onclick by returning !!elem.onclick (or something similar).

How can I convert ArrayList<Object> to ArrayList<String>?

If you want to do it the dirty way, try this.

@SuppressWarnings("unchecked")
public ArrayList<String> convert(ArrayList<Object> a) {
   return (ArrayList) a;
}

Advantage: here you save time by not iterating over all objects.

Disadvantage: may produce a hole in your foot.

What is the largest Safe UDP Packet Size on the Internet

The theoretical limit (on Windows) for the maximum size of a UDP packet is 65507 bytes. This is documented here:

The correct maximum UDP message size is 65507, as determined by the following formula: 0xffff - (sizeof(IP Header) + sizeof(UDP Header)) = 65535-(20+8) = 65507

That being said, most protocols limit to a much smaller size - usually either 512 or occasionally 8192. You can often go higher than 548 safely if you are on a reliable network - but if you're broadcasting across the internet at large, the larger you go, the more likely you'll be to run into packet transmission problems and loss.

Expanding tuples into arguments

Similar to @Dominykas's answer, this is a decorator that converts multiargument-accepting functions into tuple-accepting functions:

apply_tuple = lambda f: lambda args: f(*args)

Example 1:

def add(a, b):
    return a + b

three = apply_tuple(add)((1, 2))

Example 2:

@apply_tuple
def add(a, b):
    return a + b

three = add((1, 2))

How do you easily horizontally center a <div> using CSS?

Please use the below code and your div will be in the center.

.class-name {
    display:block;
    margin:0 auto;
}

node.js http 'get' request with query string parameters

I have been struggling with how to add query string parameters to my URL. I couldn't make it work until I realized that I needed to add ? at the end of my URL, otherwise it won't work. This is very important as it will save you hours of debugging, believe me: been there...done that.

Below, is a simple API Endpoint that calls the Open Weather API and passes APPID, lat and lon as query parameters and return weather data as a JSON object. Hope this helps.

//Load the request module
var request = require('request');

//Load the query String module
var querystring = require('querystring');

// Load OpenWeather Credentials
var OpenWeatherAppId = require('../config/third-party').openWeather;

router.post('/getCurrentWeather', function (req, res) {
    var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?'
    var queryObject = {
        APPID: OpenWeatherAppId.appId,
        lat: req.body.lat,
        lon: req.body.lon
    }
    console.log(queryObject)
    request({
        url:urlOpenWeatherCurrent,
        qs: queryObject
    }, function (error, response, body) {
        if (error) {
            console.log('error:', error); // Print the error if one occurred

        } else if(response && body) {
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            res.json({'body': body}); // Print JSON response.
        }
    })
})  

Or if you want to use the querystring module, make the following changes

var queryObject = querystring.stringify({
    APPID: OpenWeatherAppId.appId,
    lat: req.body.lat,
    lon: req.body.lon
});

request({
   url:urlOpenWeatherCurrent + queryObject
}, function (error, response, body) {...})

Disable future dates after today in Jquery Ui Datepicker

In my case, I have given this attribute to the input tag

data-date-start-date="0d" data-date-end-date="0d"

How is attr_accessible used in Rails 4?

We can use

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How to autowire RestTemplate using annotations

You can add the method below to your class for providing a default implementation of RestTemplate:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Installing and Running MongoDB on OSX

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

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

The easiest solution is to open the terminal and type

$ mongod --dbpath ~/data/db

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

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

/Users/johnny/data

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

$ mongo

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

dropping rows from dataframe based on a "not in" condition

You can use Series.isin:

df = df[~df.datecolumn.isin(a)]

While the error message suggests that all() or any() can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).

You can read more about this in the Gotchas.

Convert timestamp to readable date/time PHP

echo 'Le '.date('d/m/Y', 1234567890).' &agrave; '.date('H:i:s', 1234567890);

How to copy a file from one directory to another using PHP?

Hi guys wanted to also add on how to copy using a dynamic copying and pasting.

let say we don't know the actual folder the user will create but we know in that folder we need files to be copied to, to activate some function like delete, update, views etc.

you can use something like this... I used this code in one of the complex project which I am currently busy on. i just build it myself because all answers i got on the internet was giving me an error.

    $dirPath1 = "users/$uniqueID"; #creating main folder and where $uniqueID will be called by a database when a user login.
    $result = mkdir($dirPath1, 0755);
            $dirPath2 = "users/$uniqueID/profile"; #sub folder
            $result = mkdir($dirPath2, 0755);
                $dirPath3 = "users/$uniqueID/images"; #sub folder 
                $result = mkdir($dirPath3, 0755);
                    $dirPath4 = "users/$uniqueID/uploads";#sub folder
                    $result = mkdir($dirPath4, 0755);
                    @copy('blank/dashboard.php', 'users/'.$uniqueID.'/dashboard.php');#from blank folder to dynamic user created folder
                    @copy('blank/views.php', 'users/'.$uniqueID.'/views.php'); #from blank folder to dynamic user created folder
                    @copy('blank/upload.php', 'users/'.$uniqueID.'/upload.php'); #from blank folder to dynamic user created folder
                    @copy('blank/delete.php', 'users/'.$uniqueID.'/delete.php'); #from blank folder to dynamic user created folder

I think facebook or twitter uses something like this to build every new user dashboard dynamic....

favicon not working in IE

Care to share the URL? Many browsers cope with favicons in (e.g.) png format while IE had often troubles. - Also older versions of IE did not check the html source for the location of the favicon but just single-mindedly tried to get "/favicon.ico" from the webserver.

Change date format in a Java string

You can also use substring()

String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);

If you want a space in front of the date, use

String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

How can I split and parse a string in Python?

Python string parsing walkthrough

Split a string on space, get a list, show its type, print it out:

el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"

>>> mylist = mystring.split(" ")

>>> print type(mylist)
<type 'list'>

>>> print mylist
['What', 'does', 'the', 'fox', 'say?']

If you have two delimiters next to each other, empty string is assumed:

el@apollo:~/foo$ python
>>> mystring = "its  so   fluffy   im gonna    DIE!!!"

>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']

Split a string on underscore and grab the 5th item in the list:

el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."

>>> mystring.split("_")[4]
"Kowalski's"

Collapse multiple spaces into one

el@apollo:~/foo$ python
>>> mystring = 'collapse    these       spaces'

>>> mycollapsedstring = ' '.join(mystring.split())

>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']

When you pass no parameter to Python's split method, the documentation states: "runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace".

Hold onto your hats boys, parse on a regular expression:

el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']

The regular expression "[a-m]+" means the lowercase letters a through m that occur one or more times are matched as a delimiter. re is a library to be imported.

Or if you want to chomp the items one at a time:

el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"

>>> mytuple = mystring.partition(" ")

>>> print type(mytuple)
<type 'tuple'>

>>> print mytuple
('theres', ' ', 'coffee in that nebula')

>>> print mytuple[0]
theres

>>> print mytuple[2]
coffee in that nebula

How can I get the IP address from NIC in Python?

Find the IP address of the first eth/wlan entry in ifconfig that's RUNNING:

import itertools
import os
import re

def get_ip():
    f = os.popen('ifconfig')
    for iface in [' '.join(i) for i in iter(lambda: list(itertools.takewhile(lambda l: not l.isspace(),f)), [])]:
        if re.findall('^(eth|wlan)[0-9]',iface) and re.findall('RUNNING',iface):
            ip = re.findall('(?<=inet\saddr:)[0-9\.]+',iface)
            if ip:
                return ip[0]
    return False

set dropdown value by text using jquery

Here is an simple example:

$("#country_id").change(function(){
    if(this.value.toString() == ""){
        return;
    }
    alert("You just changed country to: " + $("#country_id option:selected").text() + " which carried the value for country_id as: " + this.value.toString());
});

Iterating over ResultSet and adding its value in an ArrayList

Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet to List, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator:

jOOQ 3.8 or less

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(r -> Arrays.stream(r.intoArray()))
   .collect(Collectors.toList());

jOOQ 3.9

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(Record::intoStream)
   .collect(Collectors.toList());

(Disclaimer, I work for the company behind jOOQ)

PHP Get all subdirectories of a given directory

The following recursive function returns an array with the full list of sub directories

function getSubDirectories($dir)
{
    $subDir = array();
    $directories = array_filter(glob($dir), 'is_dir');
    $subDir = array_merge($subDir, $directories);
    foreach ($directories as $directory) $subDir = array_merge($subDir, getSubDirectories($directory.'/*'));
    return $subDir;
}

Source: https://www.lucidar.me/en/web-dev/how-to-get-subdirectories-in-php/

What is path of JDK on Mac ?

/System/Library/Frameworks/JavaVM.framework/

Also see Java 7 path on mountain lion

c# dictionary How to add multiple values for single key?

Here are many variations of the one answer :) My is another one and it uses extension mechanism as comfortable way to execute (handy):

public static void AddToList<T, U>(this IDictionary<T, List<U>> dict, T key, U elementToList)
{

    List<U> list;

    bool exists = dict.TryGetValue(key, out list);

    if (exists)
    {
        dict[key].Add(elementToList);
    }
    else
    {
        dict[key] = new List<U>();
        dict[key].Add(elementToList);
    }

}

Then you use it as follows:

Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();

dict.AddToList(4, "test1");
dict.AddToList(4, "test2");
dict.AddToList(4, "test3");

dict.AddToList(5, "test4");

JavaScript push to array

var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push (  {"cool":"34.39","also cool":"45459"} );

Your variable is a javascript object {} not an array [].

You could do:

var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";

and

var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };

Later, you add those objects to your array: array.push (o, o2);

Also JSON is simply a string representation of a javascript object, thus:

var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again

Tomcat won't stop or restart

I faced the same problem as mentioned below.

PID file found but no matching process was found. Stop aborted.

Solution is to find the free space of the linux machine by using the following command

df -h

The above command shows my home directory was 100% used. Then identified which files to be removed by using the following command

du -h .

After removing, it was able to perform IO operation on the linux machine and the tomcat was able to start.

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

I had this error after I restarted the system (after a long time. Normally I just make it sleep). Found out that once I mounted the drives (by clicking and opening it) where project folder is located, and relaunching eclipse, solved the issue for me.

PS: I'm an ubuntu user.

Android - default value in editText

We wish there is a default value attribute in each view of android views or group view in future versions of SDK. but to overcome that, simply before submission, check if the view is empty equal true, then assign a default value

example:

   /* add 0 as default numeric value to a price field when skipped by a user,
                    in order to avoid parsing error of empty or improper format value. */
                    if (Objects.requireNonNull(edPrice.getText()).toString().trim().isEmpty())
                    edPrice.setText("0");

Not equal <> != operator on NULL

I just don't see the functional and seamless reason for nulls not to be comparable to other values or other nulls, cause we can clearly compare it and say they are the same or not in our context. It's funny. Just because of some logical conclusions and consistency we need to bother constantly with it. It's not functional, make it more functional and leave it to philosophers and scientists to conclude if it's consistent or not and does it hold "universal logic". :) Someone may say that it's because of indexes or something else, I doubt that those things couldn't be made to support nulls same as values. It's same as comparing two empty glasses, one is vine glass and other is beer glass, we are not comparing the types of objects but values they contain, same as you could compare int and varchar, with null it's even easier, it's nothing and what two nothingness have in common, they are the same, clearly comparable by me and by everyone else that write sql, because we are constantly breaking that logic by comparing them in weird ways because of some ANSI standards. Why not use computer power to do it for us and I doubt it would slow things down if everything related is constructed with that in mind. "It's not null it's nothing", it's not apple it's apfel, come on... Functionally is your friend and there is also logic here. In the end only thing that matter is functionality and does using nulls in that way brings more or less functionality and ease of use. Is it more useful?

Consider this code:

SELECT CASE WHEN NOT (1 = null or (1 is null and null is null)) THEN 1 ELSE 0 end

How many of you knows what will this code return? With or without NOT it returns 0. To me that is not functional and it's confusing. In c# it's all as it should be, comparison operations return value, logically this too produces value, because if it didn't there is nothing to compare (except. nothing :) ). They just "said": anything compared to null "returns" 0 and that creates many workarounds and headaches.

This is the code that brought me here:

where a != b OR (a is null and b IS not null) OR (a IS not null and b IS null)

I just need to compare if two fields (in where) have different values, I could use function, but...

How to make return key on iPhone make keyboard disappear?

Your UITextFields should have a delegate object (UITextFieldDelegate). Use the following code in your delegate to make the keyboard disappear:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
}

Should work so far...

How to find the number of days between two dates

Get No of Days between two days

DECLARE @date1 DATE='2015-01-01',
 @date2 DATE='2019-01-01',
 @Total int=null

SET @Total=(SELECT DATEDIFF(DAY, @date1, @date2))
PRINT @Total

MySQL Workbench Dark Theme

FYI Dark theme is now in the Dev Version of MySQL Workbench

Update: From what I can tell it is Natively built into MySQL Workbench 8.0.15 for MAC OS X

The package I downloaded was mysql-workbench-community-8.0.15-macos-x86_64.dmg

https://dev.mysql.com/downloads/workbench/ enter image description here

How to compile and run C in sublime text 3?

{
 "cmd": ["gcc", "-Wall", "-ansi", "-pedantic-errors", "$file_name", "-o", 
 "${file_base_name}.exe", "&&", "start", "cmd", "/k" , "$file_base_name"],
 "selector": "source.c",
 "working_dir": "${file_path}",
 "shell": true
}

It takes input and show output on a command prompt.

Using ffmpeg to change framerate

To the best of my knowledge you can't do this with ffmpeg without re-encoding. I had a 24fps file I wanted at 25fps to match some other material I was working with. I used the command ffmpeg -i inputfile -r 25 outputfile which worked perfectly with a webm,matroska input and resulted in an h264, matroska output utilizing encoder: Lavc56.60.100

You can accomplish the same thing at 6fps but as you noted the duration will not change (which in most cases is a good thing as otherwise you will lose audio sync). If this doesn't fit your requirements I suggest that you try this answer although my experience has been that it still re-encodes the output file.

For the best frame accuracy you are still better off decoding to raw streams as previously suggested. I use a script for this as reproduced below:

#!/bin/bash
#This script will decompress all files in the current directory, video to huffyuv and audio to PCM
#unsigned 8-bit and place the output #in an avi container to ease frame accurate editing.
for f in *
do
ffmpeg -i "$f" -c:v huffyuv -c:a pcm_u8 "$f".avi
done

Clearly this script expects all files in the current directory to be media files but can easily be changed to restrict processing to a specific extension of your choosing. Be aware that your file size will increase by a rather large factor when you decompress into raw streams.

Regex to accept alphanumeric and some special character in Javascript?

use:

/^[ A-Za-z0-9_@./#&+-]*$/

You can also use the character class \w to replace A-Za-z0-9_

C++: constructor initializer for arrays

This seems to work, but I'm not convinced it's right:

#include <iostream>

struct Foo { int x; Foo(int x): x(x) { } };

struct Baz { 
     Foo foo[3];

    static int bar[3];
     // Hmm...
     Baz() : foo(bar) {}
};

int Baz::bar[3] = {4, 5, 6};

int main() {
    Baz z;
    std::cout << z.foo[1].x << "\n";
}

Output:

$ make arrayinit -B CXXFLAGS=-pedantic && ./arrayinit
g++ -pedantic    arrayinit.cpp   -o arrayinit
5

Caveat emptor.

Edit: nope, Comeau rejects it.

Another edit: This is kind of cheating, it just pushes the member-by-member array initialization to a different place. So it still requires Foo to have a default constructor, but if you don't have std::vector then you can implement for yourself the absolute bare minimum you need:

#include <iostream>

struct Foo { 
    int x; 
    Foo(int x): x(x) { }; 
    Foo(){}
};

// very stripped-down replacement for vector
struct Three { 
    Foo data[3]; 
    Three(int d0, int d1, int d2) {
        data[0] = d0;
        data[1] = d1;
        data[2] = d2;
    }
    Foo &operator[](int idx) { return data[idx]; }
    const Foo &operator[](int idx) const { return data[idx]; }
};

struct Baz { 
    Three foo;

    static Three bar;
    // construct foo using the copy ctor of Three with bar as parameter.
    Baz() : foo(bar) {}
    // or get rid of "bar" entirely and do this
    Baz(bool) : foo(4,5,6) {}
};

Three Baz::bar(4,5,6);

int main() {
    Baz z;
    std::cout << z.foo[1].x << "\n";
}

z.foo isn't actually an array, but it looks about as much like one as a vector does. Adding begin() and end() functions to Three is trivial.

Git Clone - Repository not found

As mentioned by others the error may occur if the url is wrong.

However, the error may also occur if the repo is a private repo and you do not have access or wrong credentials.

Instead of

git clone https://github.com/NAME/repo.git

try

git clone https://username:[email protected]/NAME/repo.git


You can also use

git clone https://[email protected]/NAME/repo.git

and git will prompt for the password (thanks to leanne for providing this hint in the comments).

Set up adb on Mac OS X

If you are using ZSH and have Android Studio 1.3: 1. Open .zshrc file (Located in your home directory, file is hidden so make sure you can see hidden files) 2. Add this line at the end: alias adb="/Users/kamil/Library/Android/sdk/platform-tools/adb" 3. Quit terminal 4. Open terminal and type in adb devices 5. If it worked it will give you list of all connected devices

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

@dotjoe It is cheaper to update and check @@rowcount, do an insert after then fact.

Exceptions are expensive && updates are more frequent

Suggestion: If you want to be uber performant in your DAL, make the front end pass in a unique ID for the row to be updated, if null insert.

The DALs should be CRUD, and not need to worry about being stateless.

If you make it stateless, With good indexes, you will not see a diff with the following SQL vs 1 statement. IF (select top 1 * form x where PK=@ID) Insert else update

Console output in a Qt GUI app?

I also played with this, discovering that redirecting output worked, but I never saw output to the console window, which is present for every windows application. This is my solution so far, until I find a Qt replacement for ShowWindow and GetConsoleWindow.

Run this from a command prompt without parameters - get the window. Run from command prompt with parameters (eg. cmd aaa bbb ccc) - you get the text output on the command prompt window - just as you would expect for any Windows console app.

Please excuse the lame example - it represents about 30 minutes of tinkering.

#include "mainwindow.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QApplication>
#include <QWidget>
#include <windows.h>

QT_USE_NAMESPACE

int main(int argc, char *argv[])
{
    if (argc > 1)   {
        // User has specified command-line arguments
        QCoreApplication a(argc, argv);
        QTextStream  out(stdout);
        int     i;

        ShowWindow (GetConsoleWindow(),SW_NORMAL);
        for (i=1; i<argc; i++)
             out << i << ':' << argv [i] << endl;
        out << endl << "Hello, World" << endl;
        out << "Application Directory Path:" << a.applicationDirPath() << endl;
        out << "Application File Path:" << a.applicationFilePath() << endl;
        MessageBox (0,(LPCWSTR)"Continue?",(LPCWSTR)"Silly Question",MB_YESNO);
        return 0;
    } else  {
        QApplication a(argc, argv);
        MainWindow w;

        w.setWindowTitle("Simple example");
        w.show();
        return a.exec();
    }
}

Allow only numeric value in textbox using Javascript

This code uses the event object's .keyCode property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.

HTML:

<form>
    <input type="text" id="txt" />
</form>

JS:

(function(a) {
    a.onkeypress = function(e) {
        if (e.keyCode >= 49 && e.keyCode <= 57) {}
        else {
            if (e.keyCode >= 97 && e.keyCode <= 122) {
                alert('Error');
                // return false;
            } else return false;
        }
    };
})($('txt'));

function $(id) {
    return document.getElementById(id);
}

For a result: http://jsfiddle.net/uUc22/

Mind you that the .keyCode result for .onkeypress, .onkeydown, and .onkeyup differ from each other.

Get request URL in JSP which is forwarded by Servlet

To avoid using scriplets in the jsp, follow the advice of "divideByZero", and use ${pageContext.request.requestURI} This is a better way to go.

Url.Action parameters?

you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :

var qs = HttpUtility.ParseQueryString(""); 
qs.Add("name", "John")
qs.Add("contact", "calgary");
qs.Add("contact", "vancouver")

<a href="<%: Url.Action("GetByList", "Listing")%>?<%:qs%>">
    <span>People</span>
</a>

Getting rid of bullet points from <ul>

for inline style sheet try this code

<ul style="list-style-type: none;">
    <li>Try This</li>
    </ul>

Swift Error: Editor placeholder in source file

Error is straight forward and its because of wrong placeholders you have used in function call. Inside init you are not passing any parameters to your function. It should be this way

destination = Node("some key", neighbors: [edge1 , edge2], visited: true, lat: 23.45, long: 45.67) // fill up with your dummy values

Or you can just initialise with default method

destination = Node()

UPDATE

Add empty initialiser in your Node class

init() {

}

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

You are trying to insert a record with a value in the foreign key column that doesn't exist in the foreign table.

For example: If you have Books and Authors tables where Books has a foreign key constraint on the Authors table and you try to insert a book record for which there is no author record.

Filename timestamp in Windows CMD batch script getting truncated

Here's a batch script I made to return a timestamp. An optional first argument may be provided to be used as a field delimiter. For example:

c:\sys\tmp>timestamp.bat
20160404_144741
c:\sys\tmp>timestamp.bat -
2016-04-04_14-45-25
c:\sys\tmp>timestamp.bat :
2016:04:04_14:45:29

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: put your desired field delimiter here.
:: for example, setting DELIMITER to a hyphen will separate fields like so:
:: yyyy-MM-dd_hh-mm-ss
::
:: setting DELIMITER to nothing will output like so:
:: yyyyMMdd_hhmmss
::
SET DELIMITER=%1

SET DATESTRING=%date:~-4,4%%DELIMITER%%date:~-7,2%%DELIMITER%%date:~-10,2%
SET TIMESTRING=%TIME%
::TRIM OFF the LAST 3 characters of TIMESTRING, which is the decimal point and hundredths of a second
set TIMESTRING=%TIMESTRING:~0,-3%

:: Replace colons from TIMESTRING with DELIMITER
SET TIMESTRING=%TIMESTRING::=!DELIMITER!%

:: if there is a preceeding space substitute with a zero
echo %DATESTRING%_%TIMESTRING: =0%

A KeyValuePair in Java

Hashtable<String, Object>

It is better than java.util.Properties which is by fact an extension of Hashtable<Object, Object>.

How to create an executable .exe file from a .m file

If you have MATLAB Compiler installed, there's a GUI option for compiling. Try entering

deploytool

in the command line. Mathworks does a pretty good job documenting how to use it in this video tutorial: http://www.mathworks.com/products/demos/compiler/deploytool/index.html

Also, if you want to include user input such as choosing a file or directory, look into

uigetfile % or uigetdir if you need every file in a directory

for use in conjunction with

guide

URL string format for connecting to Oracle database with JDBC

The correct format for url can be one of the following formats:

jdbc:oracle:thin:@<hostName>:<portNumber>:<sid>;  (if you have sid)
jdbc:oracle:thin:@//<hostName>:<portNumber>/serviceName; (if you have oracle service name)

And don't put any space there. Try to use 1521 as port number. sid (database name) must be the same as the one which is in environment variables (if you are using windows).

Select arrow style change

Style the label with CSS and use pointer events :

<label>
<select>
   <option value="0">Zero</option>
   <option value="1">One</option>
</select>
</label>

and the relative CSS is

label:after {
    content:'\25BC';
    display:inline-block;
    color:#000;
    background-color:#fff;
    margin-left:-17px;   /* remove the damn :after space */
    pointer-events:none; /* let the click pass trough */
}

I just used a down arrow here, but you can set a block with a background image. Here is a ugly fiddle sample: https://jsfiddle.net/1rofzz89/

What does collation mean?

Collation means assigning some order to the characters in an Alphabet, say, ASCII or Unicode etc.

Suppose you have 3 characters in your alphabet - {A,B,C}. You can define some example collations for it by assigning integral values to the characters

  1. Example 1 = {A=1,B=2,C=3}
  2. Example 2 = {C=1,B=2,A=3}
  3. Example 3 = {B=1,C=2,A=3}

As a matter of fact, you can define n! collations on an Alphabet of size n. Given such an order, different sorting routines likes LSD/MSD string sorts make use of it for sorting strings.

How do I update pip itself from inside my virtual environment?

for windows,

  • go to command prompt
  • and use this command
  • python -m pip install –upgrade pip
  • Dont forget to restart the editor,to avoid any error
  • you can check the version of the pip by
  • pip --version
  • if you want to install any particular version of pip , for example version 18.1 then use this command,
  • python -m pip install pip==18.1

Indent starting from the second line of a paragraph with CSS

If you style as list

  • you can "text-align: initial" and the subsequent lines will all indent. I realize this may not suit your needs, but I was checking to see if there was another solution before I change my markup..

    I guess putting the second line in would also work, but requires human thinking for the content to flow properly, and, of course, hard line breaks (which don't bother me, per se).

  • Real mouse position in canvas

    Refer this question: The mouseEvent.offsetX I am getting is much larger than actual canvas size .I have given a function there which will exactly suit in your situation

    nullable object must have a value

    When using LINQ extension methods (e.g. Select, Where), the lambda function might be converted to SQL that might not behave identically to your C# code. For instance, C#'s short-circuit evaluated && and || are converted to SQL's eager AND and OR. This can cause problems when you're checking for null in your lambda.

    Example:

    MyEnum? type = null;
    Entities.Table.Where(a => type == null || 
        a.type == (int)type).ToArray();  // Exception: Nullable object must have a value
    

    How do I clear the dropdownlist values on button click event using jQuery?

    If you want to reset the selected options

    $('select option:selected').removeAttr('selected');
    

    If you actually want to remove the options (although I don't think you mean this).

    $('select').empty();
    

    Substitute select for the most appropriate selector in your case (this may be by id or by CSS class). Using as is will reset all <select> elements on the page

    How to make a loop in x86 assembly language?

    I was looking for same answer & found this info from wiki useful: Loop Instructions

    The loop instruction decrements ECX and jumps to the address specified by arg unless decrementing ECX caused its value to become zero. For example:

     mov ecx, 5
     start_loop:
     ; the code here would be executed 5 times
     loop start_loop
    

    loop does not set any flags.

    loopx arg

    These loop instructions decrement ECX and jump to the address specified by arg if their condition is satisfied (that is, a specific flag is set), unless decrementing ECX caused its value to become zero.

    • loope loop if equal

    • loopne loop if not equal

    • loopnz loop if not zero

    • loopz loop if zero

    Source: X86 Assembly, Control Flow

    What's the difference between an id and a class?

    Class is used for multiple elements which have common attributes.Example if you want same color and font for both p and body tag use class attribute or in a division itself.

    Id on the other hand is used for highlighting a single element attributes and used exclusively for a particular element only.For example we have an h1 tag with some attributes we would not want them to repeat in any other elements throughout the page.

    It should be noted that if we use class and id both in an element,*id ovverides the class attributes.*Simply because id is exclusively for a single element

    Refer the below example

    <html>
    <head>
    <style>
        #html_id{
            color:aqua;
            background-color: black;
    
        }
        .html_class{
            color:burlywood;
            background-color: brown;
        }
    </style>
    
       </head>
        <body>
    <p  class="html_class">Lorem ipsum dolor sit amet consectetur adipisicing 
       elit. 
        Perspiciatis a dicta qui unde veritatis cupiditate ullam quibusdam! 
         Mollitia enim, 
        nulla totam deserunt ex nihil quod, eaque, sed facilis quos iste.</p>
        </body>
       </html>
    

    We generate the output

    Output

    Using number_format method in Laravel

    Here's another way of doing it, add in app\Providers\AppServiceProvider.php

    use Illuminate\Support\Str;
    
    ...
    
    public function boot()
    {
        // add Str::currency macro
        Str::macro('currency', function ($price)
        {
            return number_format($price, 2, '.', '\'');
        });
    }
    

    Then use Str::currency() in the blade templates or directly in the Expense model.

    @foreach ($Expenses as $Expense)
        <tr>
            <td>{{{ $Expense->type }}}</td>
            <td>{{{ $Expense->narration }}}</td>
            <td>{{{ Str::currency($Expense->price) }}}</td>
            <td>{{{ $Expense->quantity }}}</td>
            <td>{{{ Str::currency($Expense->amount) }}}</td>                                                            
        </tr>
    @endforeach
    

    How do I share variables between different .c files?

    In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.

    In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.

    In those few rare cases when you need to share a variable between files, do like this:

    // file.h
    extern int my_var;
    
    // file.c
    #include "file.h"
    int my_var = something;
    
    // main.c
    #include "file.h"
    use(my_var);
    

    Never put any form of variable definition in a h-file.

    How to clone all remote branches in Git?

    This isn't too much complicated, very simple and straight forward steps are as follows;

    git fetch origin This will bring all the remote branches to your local.

    git branch -a This will show you all the remote branches.

    git checkout --track origin/<branch you want to checkout>

    Verify whether you are in the desired branch by the following command;

    git branch
    

    The output will like this;

    *your current branch 
    some branch2
    some branch3 
    

    Notice the * sign that denotes the current branch.

    What is the difference between parseInt() and Number()?

    If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0. Also multiply ("10" * 1) or not not (~~"10"). All of them are much faster of Number and parseInt. They even have "feature" returning 0 for not number argument. Here are Performance tests.

    Creating a fixed sidebar alongside a centered Bootstrap 3 grid

    As drew_w said, you can find a good example here.

    HTML

    <div id="wrapper">
        <div id="sidebar-wrapper">
            <ul class="sidebar-nav">
                <li class="sidebar-brand"><a href="#">Home</a></li>
                <li><a href="#">Another link</a></li>
                <li><a href="#">Next link</a></li>
                <li><a href="#">Last link</a></li>
            </ul>
        </div>
        <div id="page-content-wrapper">
            <div class="page-content">
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <!-- content of page -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    

    CSS

    #wrapper {
      padding-left: 250px;
      transition: all 0.4s ease 0s;
    }
    
    #sidebar-wrapper {
      margin-left: -250px;
      left: 250px;
      width: 250px;
      background: #CCC;
      position: fixed;
      height: 100%;
      overflow-y: auto;
      z-index: 1000;
      transition: all 0.4s ease 0s;
    }
    
    #page-content-wrapper {
      width: 100%;
    }
    
    .sidebar-nav {
      position: absolute;
      top: 0;
      width: 250px;
      list-style: none;
      margin: 0;
      padding: 0;
    }
    
    @media (max-width:767px) {
    
        #wrapper {
          padding-left: 0;
        }
    
        #sidebar-wrapper {
          left: 0;
        }
    
        #wrapper.active {
          position: relative;
          left: 250px;
        }
    
        #wrapper.active #sidebar-wrapper {
          left: 250px;
          width: 250px;
          transition: all 0.4s ease 0s;
        }
    
    }
    

    JSFIDDLE

    How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

    Update for latest SDK:

    Now @zeuter's answer is correct for Facebook SDK v4.7+:

    LoginManager.getInstance().logOut();

    Original answer:

    Please do not use SessionTracker. It is an internal (package private) class, and is not meant to be consumed as part of the public API. As such, its API may change at any time without any backwards compatibility guarantees. You should be able to get rid of all instances of SessionTracker in your code, and just use the active session instead.

    To answer your question, if you don't want to keep any session data, simply call closeAndClearTokenInformation when your app closes.

    Compiling a java program into an executable

    I use launch4j

    ANT Command:

    <target name="jar" depends="compile, buildDLLs, copy">
        <jar basedir="${java.bin.dir}" destfile="${build.dir}/Project.jar" manifest="META-INF/MANIFEST.MF" />
    </target>
    
    <target name="exe" depends="jar">
        <exec executable="cmd" dir="${launch4j.home}">
            <arg line="/c launch4jc.exe ${basedir}/${launch4j.dir}/L4J_ProjectConfig.xml" />
        </exec>
    </target>
    

    Adding a legend to PyPlot in Matplotlib in the simplest manner possible

    You can access the Axes instance (ax) with plt.gca(). In this case, you can use

    plt.gca().legend()
    

    You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

    import numpy as np
    import matplotlib.pyplot as plt
    x = np.linspace(-0.75,1,100)
    y0 = np.exp(2 + 3*x - 7*x**3)
    y1 = 7-4*np.sin(4*x)
    plt.plot(x,y0,x,y1)
    plt.gca().legend(('y0','y1'))
    plt.show()
    

    pltGcaLegend

    However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

    ax = plt.gca()
    

    and then calling ax instead of plt.gca().

    python: Appending a dictionary to a list - I see a pointer like behavior

    You are correct in that your list contains a reference to the original dictionary.

    a.append(b.copy()) should do the trick.

    Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

    jquery AJAX and json format

    You need to parse the string you are sending from javascript object to the JSON object

    var json=$.parseJSON(data);

    How to get content body from a httpclient call?

    If you are not wanting to use async you can add .Result to force the code to execute synchronously:

    private string GetResponseString(string text)
    {
        var httpClient = new HttpClient();
    
        var parameters = new Dictionary<string, string>();
        parameters["text"] = text;
    
        var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
        var contents = response.Content.ReadAsStringAsync().Result;
    
        return contents;
     }  
    

    Node.js: for each … in not working

    Unfortunately node does not support for each ... in, even though it is specified in JavaScript 1.6. Chrome uses the same JavaScript engine and is reported as having a similar shortcoming.

    You'll have to settle for array.forEach(function(item) { /* etc etc */ }).

    EDIT: From Google's official V8 website:

    V8 implements ECMAScript as specified in ECMA-262.

    On the same MDN website where it says that for each ...in is in JavaScript 1.6, it says that it is not in any ECMA version - hence, presumably, its absence from Node.

    Using ListView : How to add a header view?

    I found out that inflating the header view as:

    inflater.inflate(R.layout.listheader, container, false);
    

    being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.

    So, my problem was solved solved by inflating the header view passing the list as container:

    ListView list = fragmentview.findViewById(R.id.listview);
    View headerView = inflater.inflate(R.layout.listheader, list, false);
    

    then

    list.addHeaderView(headerView, null, false);
    

    Kinda late answer but I hope this can help someone

    Text size and different android screen sizes

    @forcelain I think you need to check this Google IO Pdf for Design. In that pdf go to Page No:77 in which you will find how there suggesting for using dimens.xml for different devices of android for Example see Below structure :

    res/values/dimens.xml
    
    res/values-small/dimens.xml
    
    res/values-normal/dimens.xml
    
    res/values-large/dimens.xml
    
    res/values-xlarge/dimens.xml
    

    for Example you have used below dimens.xml in values.

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
       <dimen name="text_size">18sp</dimen>
    </resources>
    

    In other values folder you need to change values for your text size .

    Note: As indicated by @espinchi the small, normal, large and xlarge have been deprecated since Android 3.2 in favor of the following:

    Declaring Tablet Layouts for Android 3.2

    For the first generation of tablets running Android 3.0, the proper way to declare tablet layouts was to put them in a directory with the xlarge configuration qualifier (for example, res/layout-xlarge/). In order to accommodate other types of tablets and screen sizes—in particular, 7" tablets—Android 3.2 introduces a new way to specify resources for more discrete screen sizes. The new technique is based on the amount of space your layout needs (such as 600dp of width), rather than trying to make your layout fit the generalized size groups (such as large or xlarge).

    The reason designing for 7" tablets is tricky when using the generalized size groups is that a 7" tablet is technically in the same group as a 5" handset (the large group). While these two devices are seemingly close to each other in size, the amount of space for an application's UI is significantly different, as is the style of user interaction. Thus, a 7" and 5" screen should not always use the same layout. To make it possible for you to provide different layouts for these two kinds of screens, Android now allows you to specify your layout resources based on the width and/or height that's actually available for your application's layout, specified in dp units.

    For example, after you've designed the layout you want to use for tablet-style devices, you might determine that the layout stops working well when the screen is less than 600dp wide. This threshold thus becomes the minimum size that you require for your tablet layout. As such, you can now specify that these layout resources should be used only when there is at least 600dp of width available for your application's UI.

    You should either pick a width and design to it as your minimum size, or test what is the smallest width your layout supports once it's complete.

    Note: Remember that all the figures used with these new size APIs are density-independent pixel (dp) values and your layout dimensions should also always be defined using dp units, because what you care about is the amount of screen space available after the system accounts for screen density (as opposed to using raw pixel resolution). For more information about density-independent pixels, read Terms and concepts, earlier in this document. Using new size qualifiers

    The different resource configurations that you can specify based on the space available for your layout are summarized in table 2. These new qualifiers offer you more control over the specific screen sizes your application supports, compared to the traditional screen size groups (small, normal, large, and xlarge).

    Note: The sizes that you specify using these qualifiers are not the actual screen sizes. Rather, the sizes are for the width or height in dp units that are available to your activity's window. The Android system might use some of the screen for system UI (such as the system bar at the bottom of the screen or the status bar at the top), so some of the screen might not be available for your layout. Thus, the sizes you declare should be specifically about the sizes needed by your activity—the system accounts for any space used by system UI when declaring how much space it provides for your layout. Also beware that the Action Bar is considered a part of your application's window space, although your layout does not declare it, so it reduces the space available for your layout and you must account for it in your design.

    Table 2. New configuration qualifiers for screen size (introduced in Android 3.2). Screen configuration Qualifier values Description smallestWidth swdp

    Examples: sw600dp sw720dp

    The fundamental size of a screen, as indicated by the shortest dimension of the available screen area. Specifically, the device's smallestWidth is the shortest of the screen's available height and width (you may also think of it as the "smallest possible width" for the screen). You can use this qualifier to ensure that, regardless of the screen's current orientation, your application's has at least dps of width available for its UI.

    For example, if your layout requires that its smallest dimension of screen area be at least 600 dp at all times, then you can use this qualifier to create the layout resources, res/layout-sw600dp/. The system will use these resources only when the smallest dimension of available screen is at least 600dp, regardless of whether the 600dp side is the user-perceived height or width. The smallestWidth is a fixed screen size characteristic of the device; the device's smallestWidth does not change when the screen's orientation changes.

    The smallestWidth of a device takes into account screen decorations and system UI. For example, if the device has some persistent UI elements on the screen that account for space along the axis of the smallestWidth, the system declares the smallestWidth to be smaller than the actual screen size, because those are screen pixels not available for your UI.

    This is an alternative to the generalized screen size qualifiers (small, normal, large, xlarge) that allows you to define a discrete number for the effective size available for your UI. Using smallestWidth to determine the general screen size is useful because width is often the driving factor in designing a layout. A UI will often scroll vertically, but have fairly hard constraints on the minimum space it needs horizontally. The available width is also the key factor in determining whether to use a one-pane layout for handsets or multi-pane layout for tablets. Thus, you likely care most about what the smallest possible width will be on each device. Available screen width wdp

    Examples: w720dp w1024dp

    Specifies a minimum available width in dp units at which the resources should be used—defined by the value. The system's corresponding value for the width changes when the screen's orientation switches between landscape and portrait to reflect the current actual width that's available for your UI.

    This is often useful to determine whether to use a multi-pane layout, because even on a tablet device, you often won't want the same multi-pane layout for portrait orientation as you do for landscape. Thus, you can use this to specify the minimum width required for the layout, instead of using both the screen size and orientation qualifiers together. Available screen height hdp

    Examples: h720dp h1024dp etc.

    Specifies a minimum screen height in dp units at which the resources should be used—defined by the value. The system's corresponding value for the height changes when the screen's orientation switches between landscape and portrait to reflect the current actual height that's available for your UI.

    Using this to define the height required by your layout is useful in the same way as wdp is for defining the required width, instead of using both the screen size and orientation qualifiers. However, most apps won't need this qualifier, considering that UIs often scroll vertically and are thus more flexible with how much height is available, whereas the width is more rigid.

    While using these qualifiers might seem more complicated than using screen size groups, it should actually be simpler once you determine the requirements for your UI. When you design your UI, the main thing you probably care about is the actual size at which your application switches between a handset-style UI and a tablet-style UI that uses multiple panes. The exact point of this switch will depend on your particular design—maybe you need a 720dp width for your tablet layout, maybe 600dp is enough, or 480dp, or some number between these. Using these qualifiers in table 2, you are in control of the precise size at which your layout changes.

    For more discussion about these size configuration qualifiers, see the Providing Resources document. Configuration examples

    To help you target some of your designs for different types of devices, here are some numbers for typical screen widths:

    320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
    480dp: a tweener tablet like the Streak (480x800 mdpi).
    600dp: a 7” tablet (600x1024 mdpi).
    720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
    

    Using the size qualifiers from table 2, your application can switch between your different layout resources for handsets and tablets using any number you want for width and/or height. For example, if 600dp is the smallest available width supported by your tablet layout, you can provide these two sets of layouts:

    res/layout/main_activity.xml # For handsets res/layout-sw600dp/main_activity.xml # For tablets

    In this case, the smallest width of the available screen space must be 600dp in order for the tablet layout to be applied.

    For other cases in which you want to further customize your UI to differentiate between sizes such as 7” and 10” tablets, you can define additional smallest width layouts:

    res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger) res/layout-sw720dp/main_activity.xml

    For 10” tablets (720dp wide and bigger)

    Notice that the previous two sets of example resources use the "smallest width" qualifier, swdp, which specifies the smallest of the screen's two sides, regardless of the device's current orientation. Thus, using swdp is a simple way to specify the overall screen size available for your layout by ignoring the screen's orientation.

    However, in some cases, what might be important for your layout is exactly how much width or height is currently available. For example, if you have a two-pane layout with two fragments side by side, you might want to use it whenever the screen provides at least 600dp of width, whether the device is in landscape or portrait orientation. In this case, your resources might look like this:

    res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-w600dp/main_activity.xml # Multi-pane (any screen with 600dp available width or more)

    Notice that the second set is using the "available width" qualifier, wdp. This way, one device may actually use both layouts, depending on the orientation of the screen (if the available width is at least 600dp in one orientation and less than 600dp in the other orientation).

    If the available height is a concern for you, then you can do the same using the hdp qualifier. Or, even combine the wdp and hdp qualifiers if you need to be really specific.

    best way to create object

    Really depends on your requirement, although lately I have seen a trend for classes with at least one bare constructor defined.

    The upside of posting your parameters in via constructor is that you know those values can be relied on after instantiation. The downside is that you'll need to put more work in with any library that expects to be able to create objects with a bare constructor.

    My personal preference is to go with a bare constructor and set any properties as part of the declaration.

    Person p=new Person()
    {
       Name = "Han Solo",
       Age = 39
    };
    

    This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).

    pandas how to check dtype for all columns in a dataframe?

    The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

    For a single column:

    dataframe.column.dtype
    

    For all columns:

    dataframe.dtypes
    

    Example:

    import pandas as pd
    df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})
    
    df.A.dtype
    # dtype('int64')
    df.B.dtype
    # dtype('bool')
    df.C.dtype
    # dtype('O')
    
    df.dtypes
    #A     int64
    #B      bool
    #C    object
    #dtype: object
    

    What's the valid way to include an image with no src?

    I recommend dynamically adding the elements, and if using jQuery or other JavaScript library, it is quite simple:

    also look at prepend and append. Otherwise if you have an image tag like that, and you want to make it validate, then you might consider using a dummy image, such as a 1px transparent gif or png.

    Why does the Visual Studio editor show dots in blank spaces?

    Visual Studio is configured to show whitespace.

    Press Ctrl+R, Ctrl+W.

    If you are using C# keyboard mappings: (thanks Simeon)

    Press Ctrl+E, S.

    If you want to use the menu: (thanks angularsen)

    Edit > Advanced > View White Space
    

    What is the difference between UNION and UNION ALL?

    Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates.

    • UNION performs a DISTINCT on the result set, eliminating any duplicate rows.

    • UNION ALL does not remove duplicates, and it therefore faster than UNION.

    Note: While using this commands all selected columns need to be of the same data type.

    Example: If we have two tables, 1) Employee and 2) Customer

    1. Employee table data:

    enter image description here

    1. Customer table data:

    enter image description here

    1. UNION Example (It removes all duplicate records):

    enter image description here

    1. UNION ALL Example (It just concatenate records, not eliminate duplicates, so it is faster than UNION):

    enter image description here

    How to retrieve absolute path given relative

    realpath is probably best

    But ...

    The initial question was very confused to start with, with an example poorly related to the question as stated.

    The selected answer actually answers the example given, and not at all the question in the title. The first command is that answer (is it really ? I doubt), and could do as well without the '/'. And I fail to see what the second command is doing.

    Several issues are mixed :

    • changing a relative pathname into an absolute one, whatever it denotes, possibly nothing. (Typically, if you issue a command such as touch foo/bar, the pathname foo/bar must exist for you, and possibly be used in computation, before the file is actually created.)

    • there may be several absolute pathname that denote the same file (or potential file), notably because of symbolic links (symlinks) on the path, but possibly for other reasons (a device may be mounted twice as read-only). One may or may not want to resolve explicity such symlinks.

    • getting to the end of a chain of symbolic links to a non-symlink file or name. This may or may not yield an absolute path name, depending on how it is done. And one may, or may not want to resolve it into an absolute pathname.

    The command readlink foo without option gives an answer only if its argument foo is a symbolic link, and that answer is the value of that symlink. No other link is followed. The answer may be a relative path: whatever was the value of the symlink argument.

    However, readlink has options (-f -e or -m) that will work for all files, and give one absolute pathname (the one with no symlinks) to the file actually denoted by the argument.

    This works fine for anything that is not a symlink, though one might desire to use an absolute pathname without resolving the intermediate symlinks on the path. This is done by the command realpath -s foo

    In the case of a symlink argument, readlink with its options will again resolve all symlinks on the absolute path to the argument, but that will also include all symlinks that may be encountered by following the argument value. You may not want that if you desired an absolute path to the argument symlink itself, rather than to whatever it may link to. Again, if foo is a symlink, realpath -s foo will get an absolute path without resolving symlinks, including the one given as argument.

    Without the -s option, realpath does pretty much the same as readlink, except for simply reading the value of a link, as well as several other things. It is just not clear to me why readlink has its options, creating apparently an undesirable redundancy with realpath.

    Exploring the web does not say much more, except that there may be some variations across systems.

    Conclusion : realpath is the best command to use, with the most flexibility, at least for the use requested here.

    Assembly code vs Machine code vs Object code?

    The other answers gave a good description of the difference, but you asked for a visual also. Here is a diagram showing they journey from C code to an executable.

    How to pass text in a textbox to JavaScript function?

    You can get textbox value and Id by the following simple example in dotNet programming

    <html>
            <head>
             <script type="text/javascript">
                 function GetTextboxId_Value(textBox) 
                     {
                     alert(textBox.value);    // To get Text Box Value(Text)
                     alert(textBox.id);      // To get Text Box Id like txtSearch
                 }
             </script>     
            </head>
     <body>
     <input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" />  </body>
     </html>
    

    String.equals() with multiple conditions (and one action on result)

    Keep the acceptable values in a HashSet and check if your string exists using the contains method:

    Set<String> accept = new HashSet<String>(Arrays.asList(new String[] {"john", "mary", "peter"}));
    if (accept.contains(some_string)) {
        //...
    }
    

    How to enumerate an enum with String type?

    Another solution:

    enum Suit: String {
        case spades = "?"
        case hearts = "?"
        case diamonds = "?"
        case clubs = "?"
    
        static var count: Int {
            return 4   
        }
    
        init(index: Int) {
            switch index {
                case 0: self = .spades
                case 1: self = .hearts
                case 2: self = .diamonds
                default: self = .clubs
            }
        }
    }
    
    for i in 0..<Suit.count {
        print(Suit(index: i).rawValue)
    }
    

    Create auto-numbering on images/figures in MS Word

    I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).

    Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:

    1. Select all text in your document (easiest way is to press ctrl-a)
    2. Press F9, this command tells Word to update all fields in the selection.

    Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.

    Insert a line break in mailto body

    I would suggest you try the html tag <br>, in case your marketing application will recognize it.

    I use %0D%0A. This should work as long as the email is HTML formatted.

    <a href="mailto:[email protected]?subject=Subscribe&body=Lastame%20%3A%0D%0AFirstname%20%3A"><img alt="Subscribe" class="center" height="50" src="subscribe.png" style="width: 137px; height: 50px; color: #4da6f7; font-size: 20px; display: block;" width="137"></a>
    

    You will likely want to take out the %20 before Firstname, otherwise you will have a space as the first character on the next line.

    A note, when I tested this with your code, it worked (along with some extra spacing). Are you using a mail client that doesn't allow HTML formatting?

    Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

    I set up a simple 3-column range on Sheet1 with Country, City, and Language in columns A, B, and C. The following code autofilters the range and then pastes only one of the columns of autofiltered data to another sheet. You should be able to modify this for your purposes:

    Sub CopyPartOfFilteredRange()
        Dim src As Worksheet
        Dim tgt As Worksheet
        Dim filterRange As Range
        Dim copyRange As Range
        Dim lastRow As Long
    
        Set src = ThisWorkbook.Sheets("Sheet1")
        Set tgt = ThisWorkbook.Sheets("Sheet2")
    
        ' turn off any autofilters that are already set
        src.AutoFilterMode = False
    
        ' find the last row with data in column A
        lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row
    
        ' the range that we are auto-filtering (all columns)
        Set filterRange = src.Range("A1:C" & lastRow)
    
        ' the range we want to copy (only columns we want to copy)
        ' in this case we are copying country from column A
        ' we set the range to start in row 2 to prevent copying the header
        Set copyRange = src.Range("A2:A" & lastRow)
    
        ' filter range based on column B
        filterRange.AutoFilter field:=2, Criteria1:="Rio de Janeiro"
    
        ' copy the visible cells to our target range
        ' note that you can easily find the last populated row on this sheet
        ' if you don't want to over-write your previous results
        copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range("A1")
    
    End Sub
    

    Note that by using the syntax above to copy and paste, nothing is selected or activated (which you should always avoid in Excel VBA) and the clipboard is not used. As a result, Application.CutCopyMode = False is not necessary.

    .keyCode vs. .which

    Note: The answer below was written in 2010. Here many years later, both keyCode and which are deprecated in favor of key (for the logical key) and code (for the physical placement of the key). But note that IE doesn't support code, and its support for key is based on an older version of the spec so isn't quite correct. As I write this, the current Edge based on EdgeHTML and Chakra doesn't support code either, but Microsoft is rolling out its Blink- and V8- based replacement for Edge, which presumably does/will.


    Some browsers use keyCode, others use which.

    If you're using jQuery, you can reliably use which as jQuery standardizes things; More here.

    If you're not using jQuery, you can do this:

    var key = 'which' in e ? e.which : e.keyCode;
    

    Or alternatively:

    var key = e.which || e.keyCode || 0;
    

    ...which handles the possibility that e.which might be 0 (by restoring that 0 at the end, using JavaScript's curiously-powerful || operator).

    Cannot create SSPI context

    I had the same issue after changing the user which was running the MSSQLSERVER-Service

    To solve incorrect SPNs with SQL Server I used this tool

    http://www.microsoft.com/en-us/download/details.aspx?id=39046 - Microsoft® Kerberos Configuration Manager for SQL Server

    In my case it worked pretty well.

    How to use comparison and ' if not' in python?

    Why think? If not confuses you, switch your if and else clauses around to avoid the negation.

    i want to make sure that ( u0 <= u < u0+step ) before do sth.

    Just write that.

    if u0 <= u < u0+step:
        "do sth" # What language is "sth"?  No vowels.  An odd-looking word.
    else:
        u0 = u0+ step
    

    Why overthink it?

    If you need an empty if -- and can't work out the logic -- use pass.

     if some-condition-that's-too-complex-for-me-to-invert:
         pass
     else: 
         do real work here
    

    Easiest way to split a string on newlines in .NET?

    I just thought I would add my two-bits, because the other solutions on this question do not fall into the reusable code classification and are not convenient.

    The following block of code extends the string object so that it is available as a natural method when working with strings.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Collections;
    using System.Collections.ObjectModel;
    
    namespace System
    {
        public static class StringExtensions
        {
            public static string[] Split(this string s, string delimiter, StringSplitOptions options = StringSplitOptions.None)
            {
                return s.Split(new string[] { delimiter }, options);
            }
        }
    }
    

    You can now use the .Split() function from any string as follows:

    string[] result;
    
    // Pass a string, and the delimiter
    result = string.Split("My simple string", " ");
    
    // Split an existing string by delimiter only
    string foo = "my - string - i - want - split";
    result = foo.Split("-");
    
    // You can even pass the split options parameter. When omitted it is
    // set to StringSplitOptions.None
    result = foo.Split("-", StringSplitOptions.RemoveEmptyEntries);
    

    To split on a newline character, simply pass "\n" or "\r\n" as the delimiter parameter.

    Comment: It would be nice if Microsoft implemented this overload.

    How to shift a column in Pandas DataFrame

    Lets define the dataframe from your example by

    >>> df = pd.DataFrame([[206, 214], [226, 234], [245, 253], [265, 272], [283, 291]], 
        columns=[1, 2])
    >>> df
         1    2
    0  206  214
    1  226  234
    2  245  253
    3  265  272
    4  283  291
    

    Then you could manipulate the index of the second column by

    >>> df[2].index = df[2].index+1
    

    and finally re-combine the single columns

    >>> pd.concat([df[1], df[2]], axis=1)
           1      2
    0  206.0    NaN
    1  226.0  214.0
    2  245.0  234.0
    3  265.0  253.0
    4  283.0  272.0
    5    NaN  291.0
    

    Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.

    Edit: Generally shifting is possible by df[2].shift(1) as already posted however would that cut-off the carryover.

    Check if decimal value is null

    A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue

    How to have a default option in Angular.js select box

    I needed the default “Please Select” to be unselectable. I also needed to be able to conditionally set a default selected option.

    I achieved this the following simplistic way: JS code: // Flip these 2 to test selected default or no default with default “Please Select” text //$scope.defaultOption = 0; $scope.defaultOption = { key: '3', value: 'Option 3' };

    $scope.options = [
       { key: '1', value: 'Option 1' },
       { key: '2', value: 'Option 2' },
       { key: '3', value: 'Option 3' },
       { key: '4', value: 'Option 4' }
    ];
    
    getOptions();
    
    function getOptions(){
        if ($scope.defaultOption != 0)
        { $scope.options.selectedOption = $scope.defaultOption; }
    }
    

    HTML:

    <select name="OptionSelect" id="OptionSelect" ng-model="options.selectedOption" ng-options="item.value for item in options track by item.key">
    <option value="" disabled selected style="display: none;"> -- Please Select -- </option>
    </select>
    <h1>You selected: {{options.selectedOption.key}}</h1>         
    

    I hope this helps someone else that has similar requirements.

    The "Please Select" was accomplished through Joffrey Outtier's answer here.

    org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

    For me the only thing that works is to add to repositories

    maven {
            url "https://maven.google.com"
        }
    

    It should look like this:

    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
        }
    

    How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

    List<string> values =new list<string>();
    foreach(ListItem Item in ChkList.Item)
    {
        if(Item.Selected)
        values.Add(item.Value);
    }
    

    How do I fix 'Invalid character value for cast specification' on a date column in flat file?

    I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"

    Apparently the differences between these date formats are as follow:

    DT_DATE A date structure that consists of year, month, day, and hour.

    DT_DBDATE A date structure that consists of year, month, and day.

    DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction

    By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.

    Convert NVARCHAR to DATETIME in SQL Server 2008

    As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)

    |                     YOUR_DT |             SQL2008 |
    |-----------------------------|---------------------|
    |         2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
    |    2013-08-29 13:55:48 blah |              (null) |
    | 2013-08-29 13:55:48 rubbish |              (null) |
    
    SELECT
      [Your_Dt]
    , convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
    FROM your_table
    CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
                            THEN convert(datetime,[Your_Dt])
                            ELSE NULL
                         END
                ) AS ca1 (dt_converted)
    ;
    

    Notes:

    You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'

    For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison

    declare @your_dt as datetime2
    set @your_dt = '2013-08-29 13:55:48'
    
    select
      FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
    , convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008
    
    |             SQL2012 |             SQL2008 |
    |---------------------|---------------------|
    | 29-08-2013 13:55:48 | 29-08-2013 13:55:48 | 
    

    Unable to load DLL 'SQLite.Interop.dll'

    I had the same issue. Please follow these steps:

    1. Make sure you have installed System.Data.SQLite.Core package by SQLite Development Team from NuGet.
    2. Go to project solution and try to locate build folder inside packages folder
    3. Check your project framework and pick the desired SQLite.Interop.dll and place it in your debug/release folder

    Reference

    Cant get text of a DropDownList in code - can get value but not text

    AppendDataBoundItems="true" needs to be set.

    How to change the default message of the required field in the popover of form-control in bootstrap?

    You can use setCustomValidity function when oninvalid event occurs.

    Like below:-

    <input class="form-control" type="email" required="" 
        placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
    </input>
    

    Update:-

    To clear the message once you start entering use oninput="setCustomValidity('') attribute to clear the message.

    <input class="form-control" type="email"  required="" placeholder="username"
     oninvalid="this.setCustomValidity('Please Enter valid email')"
     oninput="setCustomValidity('')"></input>