Programs & Examples On #Cdb

Use this tag if you refer to "constant database", a library and data format created by Daniel J. Bernstein. Use [tag:windbg] if you're asking about Microsoft Console Debugger.

accessing a docker container from another container

It's easy. If you have two or more running container, complete next steps:

docker network create myNetwork
docker network connect myNetwork web1
docker network connect myNetwork web2

Now you connect from web1 to web2 container or the other way round.

Use the internal network IP addresses which you can find by running:

docker network inspect myNetwork

Note that only internal IP addresses and ports are accessible to the containers connected by the network bridge.

So for example assuming that web1 container was started with: docker run -p 80:8888 web1 (meaning that its server is running on port 8888 internally), and inspecting myNetwork shows that web1's IP is 172.0.0.2, you can connect from web2 to web1 using curl 172.0.0.2:8888).

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.

The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.

(The below code is 32-bit, but can be easily converted to 64-bit)

For example, the sequence function can be optimized to only 5 instructions:

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

The whole code looks like:

include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"

start:
        InitializeAll
        mov ecx, 999999
        xor edi, edi        ; max
        xor ebx, ebx        ; max i

    .main_loop:

        xor     esi, esi
        mov     eax, ecx

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

        cmp     edi, esi
        cmovb   edi, esi
        cmovb   ebx, ecx

        dec     ecx
        jnz     .main_loop

        OutputValue "Max sequence: ", edi, 10, -1
        OutputValue "Max index: ", ebx, 10, -1

        FinalizeAll
        stdcall TerminateAll, 0

In order to compile this code, FreshLib is needed.

In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3.

The output of both programs is the same: max sequence = 525 on i = 837799.

Docker compose, running containers in net:host

Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode when using the v2 YAML format.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Also you should know that you can force TLS v1.2 for Android 4.0 devices that don't have it enabled by default:

Put this code in onCreate() of your Application file:

try {
        ProviderInstaller.installIfNeeded(getApplicationContext());
        SSLContext sslContext;
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);
        sslContext.createSSLEngine();
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
            | NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

Django: OperationalError No Such Table

I got through the same error when I went on to the admin panel. You ought to run this instead-: python manage.py migrate --run-syncdb. Don't forget to include migrate, I ran:

python manage.py make migrations and then python manage.py migrate

Still when the error persisted I tried it with the above suggested command.

Failed to install Python Cryptography package with PIP and setup.py

How I solved "Failed cleaning build dir for cryptography"
(I came here from google to result for this error.)

note: using a virtualenv

TL;DR:

my file /etc/apt/sources.list wasn't correctly configured for my debian 8.

Explanations:

I wanted to install paramiko. paramiko needs cryptography.

I got these errors: first with pip install cryptography:

(...)
  ----------------------------------------
  Failed cleaning build dir for cryptography
Failed to build cryptography
(...)
    ----------------------------------------
Command "/home/myuser/pyenvs/testo/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-HXWKAO/cryptography/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-WjqY6V-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/myuser/pyenvs/testo/include/site/python2.7/cryptography" failed with error code 1 in /tmp/pip-build-HXWKAO/cryptography/

and then with sudo apt-get install build-essential :

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 build-essential : Depends: libc6-dev but it is not going to be installed > or
                            libc-dev
                   Depends: gcc (>= 4:4.4.3) but it is not going to be installed
                   Depends: g++ (>= 4:4.4.3) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

(Not exactly the same errors as OP but I'm here to help eventually)

Solving:

After testing almost every command from every posts I end up going on
https://wiki.debian.org/SourcesList
and copy pasted my adequate config in the file /etc/apt/sources.list

then:

sudo aptitude update

and then

sudo apt-get install build-essential libssl-dev libffi-dev python-dev

and then

pip install cryptography

hth

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

How to write JUnit test with Spring Autowire?

I think somewhere in your codebase are you @Autowiring the concrete class ServiceImpl where you should be autowiring it's interface (presumably MyService).

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

You should use the provider available in your machine.

  1. Goto Control Panel
  2. Goto Administrator Tools
  3. Goto Data Sources (ODBC)
  4. Click the "Drivers" tab.
  5. Do you see something called "SQL Server Native Client"?

enter image description here

See the attached screen shot. Here my provider will be SQLNCLI11.0

How do you specify a debugger program in Code::Blocks 12.11?

Click on settings in top tool bar;

Click on debugger;

In tree, highlight "gdb/cdb debugger" by clicking it

Click "create configuration"

Click default configuration, a dialogue will appear to the right for "executable path" with a button to the right.

Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe (it sort of finds itself).

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

C# Inserting Data from a form into an access Database

Password is a reserved word. Bracket that field name to avoid confusing the db engine.

INSERT into Login (Username, [Password])

Can't install via pip because of egg_info error

See this : What Python version can I use with Django?¶ https://docs.djangoproject.com/en/2.0/faq/install/

if you are using python27 you must to set django version :

try: $pip install django==1.9

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

VBA to copy a file from one directory to another

This method is even easier if you're ok with fewer options:

FileCopy source, destination

How to reset db in Django? I get a command 'reset' not found error

  1. Just manually delete you database. Ensure you create backup first (in my case db.sqlite3 is my database)

  2. Run this command manage.py migrate

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I've solved this issue in this environment:

$ pyenv --version
pyenv 1.2.9

$ python --version
Python 3.7.2

$ python -m django --version
2.1.7

./settings.py

DATABASES = {
    'default': {
        'NAME': 'my_db_name',
        'ENGINE': 'mysql.connector.django',   # 'django.db.backends.mysql'
        'USER': '<user>',
        'PASSWORD': '<pass>',
        'HOST': 'localhost',
        'PORT': 3306,
        'OPTIONS': {
            'autocommit': True,
        },
    }
}

If you use 'ENGINE': 'mysql.connector.django' , install driver executing:

$ pip install mysql-connector-python
Successfully installed mysql-connector-python-8.0.15 protobuf-3.7.0 six-1.12.0

Note that $ pip install mysql-pythondidn't work for me.

Note that if you use 'ENGINE': 'django.db.backends.mysql' , you should install driver executing:
$ pip install mysqlclient

Finally execute:
$ python manage.py migrate

If it's all right, python creates all these tables id database:

auth_group
auth_group_permissions
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
django_admin_log
django_content_type
django_migrations
django_session

Corrupted Access .accdb file: "Unrecognized Database Format"

After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

figure of imshow() is too small

I'm new to python too. Here is something that looks like will do what you want to

axes([0.08, 0.08, 0.94-0.08, 0.94-0.08]) #[left, bottom, width, height]
axis('scaled')`

I believe this decides the size of the canvas.

findAll() in yii

if you user $criteria, I recommend blow usage:

$criteria = new CDbCriteria();
$criteria->compare('email_id', 101);
$comments = EmailArchive::model()->findAll($criteria);

How to query a MS-Access Table from MS-Excel (2010) using VBA

All you need is a ADODB.Connection

Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset   ' Microsoft ActiveX Data Objects Library

Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"

Set rs = cnn.Execute(SQLQuery) ' Retrieve the data

DataAdapter.Fill(Dataset)

it works for me, just change: Provider=Microsoft.Jet.OLEDB.4.0 (VS2013)

OleDbConnection connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\\GENERAL\\OFMPTP_PD_SG.MDB");
DataSet DS = new DataSet();
connection.Open();

string query =
@"SELECT * from MONTHLYPROD";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection);
DBAdapter.Fill(DS);

Luis Montoya

What is the easiest way to clear a database from the CLI with manage.py in Django?

If you don't care about data:

Best way would be to drop the database and run syncdb again. Or you can run:

For Django >= 1.5

python manage.py flush

For Django < 1.5

python manage.py reset appname

(you can add --no-input to the end of the command for it to skip the interactive prompt.)

If you do care about data:

From the docs:

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

https://docs.djangoproject.com/en/dev/ref/django-admin/

Reference: FAQ - https://docs.djangoproject.com/en/dev/faq/models/#if-i-make-changes-to-a-model-how-do-i-update-the-database

People also recommend South ( http://south.aeracode.org/docs/about.html#key-features ), but I haven't tried it.

fatal: git-write-tree: error building trees

I used:

 git reset --hard

I lost some changes, but this is ok.

How to set up a PostgreSQL database in Django

If you are using Fedora 20, Django 1.6.5, postgresql 9.3.* and you need the psycopg2 module, do this:

yum install postgresql-devel
easy_install psycopg2

If you are like me, you may have trouble finding the well documented libpq-dev rpm... The above worked for me just now.

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

Force a screen update in Excel VBA

This worked for me:

ActiveWindow.SmallScroll down:=0

or more simply:

ActiveWindow.SmallScroll 0

How to use MySQLdb with Python and Django in OSX 10.6?

pip install mysql-python

raised an error:

EnvironmentError: mysql_config not found

sudo apt-get install python-mysqldb

fixed the problem.

How do I list all tables in all databases in SQL Server in a single result set?

I realize this is a very old thread, but it was very helpful when I had to put together some system documentation for several different servers that were hosting different versions of Sql Server. I ended up creating 4 stored procedures which I am posting here for the benefit of the community. We use Dynamics NAV so the two stored procedures with NAV in the name split the Nav company out of the table name. Enjoy...

4 of 4 - ListServerDatabaseNavTables - for Dynamics NAV

USE [YourDatabase]
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER proc [dbo].[ListServerDatabaseNavTables]
(
    @SearchDatabases varchar(max) = NULL,  
    @SearchSchema sysname = NULL,
    @SearchCompanies varchar(max) = NULL,
    @SearchTables varchar(max) = NULL,
    @ExcludeSystemDatabases bit = 1,
    @Sql varchar(max) OUTPUT
)
AS BEGIN

/**************************************************************************************************************************************
* Lists all of the database tables for a given server.
*   Parameters
*       SearchDatabases - Comma delimited list of database names for which to search - converted into series of Like statements
*                         Defaults to null  
*       SearchSchema - Schema name for which to search
*                      Defaults to null 
*       SearchCompanies - Comma delimited list of company names for which to search - converted into series of Like statements
*                         Defaults to null  
*       SearchTables - Comma delimited list of table names for which to search - converted into series of Like statements
*                      Defaults to null 
*       ExcludeSystemDatabases - 1 to exclude system databases, otherwise 0
*                          Defaults to 1
*       Sql - Output - the stored proc generated sql
*
*   Adapted from answer by KM answered May 21 '10 at 13:33
*   From: How do I list all tables in all databases in SQL Server in a single result set?
*   Link: https://stackoverflow.com/questions/2875768/how-do-i-list-all-tables-in-all-databases-in-sql-server-in-a-single-result-set
*
**************************************************************************************************************************************/

    SET NOCOUNT ON

    DECLARE @l_CompoundLikeStatement varchar(max) = ''
    DECLARE @l_TableName sysname
    DECLARE @l_CompanyName sysname
    DECLARE @l_DatabaseName sysname

    DECLARE @l_Index int

    DECLARE @l_UseAndText bit = 0

    DECLARE @AllTables table (ServerName sysname, DbName sysname, SchemaName sysname, CompanyName sysname, TableName sysname, NavTableName sysname)

    SET @Sql = 
        'select @@ServerName as ''ServerName'', ''?'' as ''DbName'', s.name as ''SchemaName'', ' + char(13) +
        '       case when charindex(''$'', t.name) = 0 then '''' else left(t.name, charindex(''$'', t.name) - 1) end as ''CompanyName'', ' + char(13) +
        '       case when charindex(''$'', t.name) = 0 then t.name else substring(t.name, charindex(''$'', t.name) + 1, 1000) end as ''TableName'', ' + char(13) +
        '       t.name as ''NavTableName'' ' + char(13) +
        'from [?].sys.tables t inner join ' + char(13) + 
        '     sys.schemas s on t.schema_id = s.schema_id '

    -- Comma delimited list of database names for which to search
    IF @SearchDatabases IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + 'where (' + char(13)
        WHILE LEN(LTRIM(RTRIM(@SearchDatabases))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchDatabases)
            IF @l_Index = 0 BEGIN
                SET @l_DatabaseName = LTRIM(RTRIM(@SearchDatabases))
            END ELSE BEGIN
                SET @l_DatabaseName = LTRIM(RTRIM(LEFT(@SearchDatabases, @l_Index - 1)))
            END

            SET @SearchDatabases = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchDatabases, @l_DatabaseName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' ''?'' like ''' + @l_DatabaseName + '%'' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ')'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @l_UseAndText = 1
    END

    -- Search schema
    IF @SearchSchema IS NOT NULL BEGIN
        SET @Sql = @Sql + char(13)
        SET @Sql = @Sql + CASE WHEN @l_UseAndText = 1 THEN '  and ' ELSE 'where ' END +
            's.name LIKE ''' + @SearchSchema + ''' COLLATE Latin1_General_CI_AS'
        SET @l_UseAndText = 1
    END

    -- Comma delimited list of company names for which to search
    IF @SearchCompanies IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + CASE WHEN @l_UseAndText = 1 THEN '  and (' ELSE 'where (' END + char(13) 
        WHILE LEN(LTRIM(RTRIM(@SearchCompanies))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchCompanies)
            IF @l_Index = 0 BEGIN
                SET @l_CompanyName = LTRIM(RTRIM(@SearchCompanies))
            END ELSE BEGIN
                SET @l_CompanyName = LTRIM(RTRIM(LEFT(@SearchCompanies, @l_Index - 1)))
            END

            SET @SearchCompanies = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchCompanies, @l_CompanyName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' t.name like ''' + @l_CompanyName + '%'' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ' )'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @l_UseAndText = 1
    END

    -- Comma delimited list of table names for which to search
    IF @SearchTables IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + CASE WHEN @l_UseAndText = 1 THEN '  and (' ELSE 'where (' END + char(13) 
        WHILE LEN(LTRIM(RTRIM(@SearchTables))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchTables)
            IF @l_Index = 0 BEGIN
                SET @l_TableName = LTRIM(RTRIM(@SearchTables))
            END ELSE BEGIN
                SET @l_TableName = LTRIM(RTRIM(LEFT(@SearchTables, @l_Index - 1)))
            END

            SET @SearchTables = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchTables, @l_TableName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' t.name like ''$' + @l_TableName + ''' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ' )'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @l_UseAndText = 1
    END

    IF @ExcludeSystemDatabases = 1 BEGIN
        SET @Sql = @Sql + char(13)
        SET @Sql = @Sql + case when @l_UseAndText = 1 THEN '  and ' ELSE 'where ' END +
            '''?'' not in (''master'' COLLATE Latin1_General_CI_AS, ''model'' COLLATE Latin1_General_CI_AS, ''msdb'' COLLATE Latin1_General_CI_AS, ''tempdb'' COLLATE Latin1_General_CI_AS)' 
    END

/*  PRINT @Sql  */

    INSERT INTO @AllTables 
    EXEC sp_msforeachdb @Sql

    SELECT * FROM @AllTables ORDER BY DbName COLLATE Latin1_General_CI_AS, CompanyName COLLATE Latin1_General_CI_AS, TableName COLLATE Latin1_General_CI_AS
END

How do I run a VBScript in 32-bit mode on a 64-bit machine?

If you have control over running the cscript executable then run the X:\windows\syswow64\cscript.exe version which is the 32bit implementation.

Convert String to Double - VB

Try looking at Double.TryParse() if you are using .NET 1.1/2.0/3.0/3.5/4.0/4.5

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Define css class in django Forms

You could also use Django Crispy Forms, it's a great tool to define forms in case you'd like to use some CSS framework like Bootstrap or Foundation. And it's easy to specify classes for your form fields there.

Your form class would like this then:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, Field
from crispy_forms.bootstrap import FormActions

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

    helper = FormHelper()
    helper.form_class = 'your-form-class'
    helper.layout = Layout(
        Field('name', css_class='name-class'),
        Field('age', css_class='age-class'),
        Field('django_hacker', css-class='hacker-class'),
        FormActions(
            Submit('save_changes', 'Save changes'),
        )
    )

Regular expression field validation in jQuery

My code :

$("input.numeric").keypress(function(e) { /* pour les champs qui ne prennent que du numeric en entrée */          
            var key = e.charCode || e.keyCode || 0;                     
            var keychar = String.fromCharCode(key);
            /*alert("keychar:"+keychar + " \n charCode:" + e.charCode + " \n key:" +key);*/
            if (  ((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode==0) /* backspace, end, begin, top, bottom, right, left, del, tab */
                    || (key >= 48 && key <= 57) ) { /* 0-9 */
                return;
            } else {
                e.preventDefault();
            }
        });

HTML Form: Select-Option vs Datalist-Option

To specifically answer a part of your question "Is there any situation in which it would be better to use one or the other?", consider a form with repeating sections. If the repeating section contains many select tags, then the options must be rendered for each select, for every row.

In such a case, I would consider using datalist with input, because the same datalist can be used for any number of inputs. This could potentially save a large amount of rendering time on the server, and would scale much better to any number of rows.

print variable and a string in python

'''

If the python version you installed is 3.6.1, you can print strings and a variable through
a single line of code.
For example the first string is "I have", the second string is "US
Dollars" and the variable, **card.price** is equal to 300, we can write
the code this way:

'''

print("I have", card.price, "US Dollars")

#The print() function outputs strings to the screen.  
#The comma lets you concatenate and print strings and variables together in a single line of code.

"query function not defined for Select2 undefined error"

Also got the same error when using ajax.

If you're using ajax to render forms with select2, the input_html class must be different from those NOT rendered using ajax. Not quite sure why it works this way though.

Removing unwanted table cell borders with CSS

Try assigning the style of border: 0px; border-collapse: collapse; to the table element.

Wait until an HTML5 video loads

you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.

_x000D_
_x000D_
<video preload="none">
_x000D_
_x000D_
_x000D_

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

For people that find this question by searching for the error message, you can also see this error if you make a mistake in your @JsonProperty annotations such that you annotate a List-typed property with the name of a single-valued field:

@JsonProperty("someSingleValuedField") // Oops, should have been "someMultiValuedField"
public List<String> getMyField() { // deserialization fails - single value into List
  return myField;
}

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

Styling an input type="file" button

Here we use a span to trigger input of type file and we simply customized that span, so we can add any styling using this way.

Note that we use input tag with visibility:hidden option and trigger it in the span.

_x000D_
_x000D_
.attachFileSpan{_x000D_
color:#2b6dad;_x000D_
cursor:pointer;_x000D_
}_x000D_
.attachFileSpan:hover{_x000D_
text-decoration: underline;_x000D_
}
_x000D_
<h3> Customized input of type file </h3>_x000D_
<input id="myInput" type="file" style="visibility:hidden"/>_x000D_
_x000D_
        <span title="attach file" class="attachFileSpan" onclick="document.getElementById('myInput').click()">_x000D_
        Attach file_x000D_
        </span>
_x000D_
_x000D_
_x000D_

Reference

How to delete a workspace in Eclipse?

Just go to the \eclipse-java-helios-SR2-win32\eclipse\configuration.settings directory and change or remove org.eclipse.ui.ide.prefs file.

'sprintf': double precision in C

From your question it seems like you are using C99, as you have used %lf for double.

To achieve the desired output replace:

sprintf(aa, "%lf", a);

with

sprintf(aa, "%0.7f", a);

The general syntax "%A.B" means to use B digits after decimal point. The meaning of the A is more complicated, but can be read about here.

PHP's array_map including keys

I always like the javascript variant of array map. The most simple version of it would be:

/**
 * @param  array    $array
 * @param  callable $callback
 * @return array
 */
function arrayMap(array $array, callable $callback)
{
    $newArray = [];

    foreach( $array as $key => $value )
    {
        $newArray[] = call_user_func($callback, $value, $key, $array);
    }

    return $newArray;
}

So now you can just pass it a callback function how to construct the values.

$testArray = [
    "first_key" => "first_value", 
    "second_key" => "second_value"
];

var_dump(
    arrayMap($testArray, function($value, $key) {
        return $key . ' loves ' . $value;
    });
);

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

How to disable RecyclerView scrolling?

Came across with a fragment that contains multiple RecycleView so I only need one scrollbar instead of one scrollbar in each RecycleView.

So I just put the ScrollView in the parent container that contains the 2 RecycleViews and use android:isScrollContainer="false" in the RecycleView

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="LinearLayoutManager"
    android:isScrollContainer="false" />

Show loading gif after clicking form submit using jQuery

The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:

$('#login_form').submit(function() {
    $('#gif').css('visibility', 'visible');
});

Also note that return true; is redundant in your logic, so it can be removed.

Find if variable is divisible by 2

You don't need jQuery. Just use JavaScript's Modulo operator.

How do I make CMake output into a 'bin' dir?

To add on to this:

If you're using CMAKE to generate a Visual Studio solution, and you want Visual Studio to output compiled files into /bin, Peter's answer needs to be modified a bit:

# set output directories for all builds (Debug, Release, etc.)
foreach( OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES} )
    string( TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIG )
    set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/lib )
    set( CMAKE_LIBRARY_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/lib )
    set( CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/bin )
endforeach( OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES )

Ternary operator ?: vs if...else

They are the same, however, the ternary operator can be used in places where it is difficult to use a if/else:

printf("Total: %d item%s", cnt, cnt != 1 ? "s" : "");

Doing that statement with an if/else, would generate a very different compiled code.


Update after 8 years...

Actually, I think this would be better:

printf(cnt == 1 ? "Total: %d item" : "Total: %d items", cnt);

(actually, I'm pretty sure you can replace the "%d" in the first string with "one")

Reverse a string in Java

StringBuilder s = new StringBuilder("racecar");
    for (int i = 0, j = s.length() - 1; i < (s.length()/2); i++, j--) {
        char temp = s.charAt(i);
        s.setCharAt(i, s.charAt(j));
        s.setCharAt(j, temp);
    }

    System.out.println(s.toString());

String Array object in Java

Your attempt at an athlete class seems to be dealing with a group of athletes, which is a design fault.

Define a class to represent a single athlete, with fields that represent the athlete's attributes:

public class Athlete {
    private final String name;
    private final String country;
    private List<Performance> performances = new ArrayList<Performance>();
    // other fields as required

    public Athlete (String name, String country) {
        this.name = name;
        this.country = country;
    }
    // getters omitted

    public List<Performance> getPerformances() {
        return performances;
    }

    public Performance perform(Dive dive) {
        // not sure what your intention is here, but something like this:
        Performance p = new Performance(dive, this);
        // add new performance to list
        performances.add(p);
        return p;
    }
}

Then your main method would use ti like this:

public class Assignment1 {
    public static void main(String[] args) {
        String[] name = {"Art", "Dan", "Jen"};
        String[] country = {"Canada", "Germant", "USA"};
        Dive[] dive = new Dive[]{new Dive("somersault"), new Dive("foo"), new Dive("bar")};
        for (int i = 0; i < name.length; i++) {
            Athlete athlete = new Athlete(name[i], country[i]);
            Performance performance = athlete.perform(dive[i]);   
            // do something with athlete and/or performance
        }
    }
}

Open fancybox from function

You don't have to add you own click event handler at all. Just initialize the element with fancybox:

$(function() {
    $('a[href="#modalMine"]').fancybox({
        'autoScale': true,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'speedIn': 500,
        'speedOut': 300,
        'autoDimensions': true,
        'centerOnScroll': true  // as MattBall already said, remove the comma
    });
});

Done. Fancybox already binds a click handler that opens the box. Have a look at the HowTo section.


Later if you want to open the box programmatically, raise the click event on that element:

$('a[href="#modalMine"]').click();

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

Very weird, but I got this error when I made a typo in the my.cnf file.
So it had nothing to do with the user directive not defined or not running as root-user.

My mistake was:

bind=192.168.1.2

instead of

bind-address=192.168.1.2

Are one-line 'if'/'for'-statements good Python style?

More generally, all of the following are valid syntactically:

if condition:
    do_something()


if condition: do_something()

if condition:
    do_something()
    do_something_else()

if condition: do_something(); do_something_else()

...etc.

CodeIgniter - Correct way to link to another page in a view

Best and easiest way is to use anchor tag in CodeIgniter like eg.

<?php 
    $this->load->helper('url'); 
    echo anchor('name_of_controller_file/function_name_if_any', 'Sign Out', array('class' => '', 'id' => '')); 
?>

Refer https://www.codeigniter.com/user_guide/helpers/url_helper.html for details

This will surely work.

What is "Advanced" SQL?

I think it's best highlighted with an example. If you feel you could write the following SQL statement quickly with little/no reference material, then I'd guess that you probably meet their Advanced SQL requirement:

DECLARE @date DATETIME
SELECT @date = '10/31/09'

SELECT
      t1.EmpName,
      t1.Region,
      t1.TourStartDate,
      t1.TourEndDate,
      t1.FOrdDate,
      FOrdType  = MAX(CASE WHEN o.OrderDate = t1.FOrdDate THEN o.OrderType  ELSE NULL END),
      FOrdTotal = MAX(CASE WHEN o.OrderDate = t1.FOrdDate THEN o.OrderTotal ELSE NULL END),
      t1.LOrdDate,
      LOrdType  = MAX(CASE WHEN o.OrderDate = t1.LOrdDate THEN o.OrderType  ELSE NULL END),
      LOrdTotal = MAX(CASE WHEN o.OrderDate = t1.LOrdDate THEN o.OrderTotal ELSE NULL END)
  FROM 
      (--Derived table t1 returns the tourdates, and the order dates
      SELECT
            e.EmpId,
            e.EmpName,
            et.Region,
            et.TourStartDate,
            et.TourEndDate,
            FOrdDate = MIN(o.OrderDate),
            LOrdDate = MAX(o.OrderDate)
        FROM #Employees e INNER JOIN #EmpTours et
          ON e.EmpId = et.EmpId INNER JOIN #Orders o
          ON e.EmpId = o.EmpId
       WHERE et.TourStartDate <= @date
         AND (et.TourEndDate > = @date OR et.TourEndDate IS NULL)
         AND o.OrderDate BETWEEN et.TourStartDate AND @date
       GROUP BY e.EmpId,e.EmpName,et.Region,et.TourStartDate,et.TourEndDate
      ) t1 INNER JOIN #Orders o
    ON t1.EmpId = o.EmpId
   AND (t1.FOrdDate = o.OrderDate OR t1.LOrdDate = o.OrderDate)
 GROUP BY t1.EmpName,t1.Region,t1.TourStartDate,t1.TourEndDate,t1.FOrdDate,t1.LOrdDate

(source of query)

And to be honest, that's a relatively simple query - just some inner joins and a subquery, along with a few common keywords (max, min, case).

Arduino IDE can't find ESP8266WiFi.h file

For those who are having trouble with fatal error: ESP8266WiFi.h: No such file or directory, you can install the package manually.

  1. Download the Arduino ESP8266 core from here https://github.com/esp8266/Arduino
  2. Go into library from the downloaded core and grab ESP8266WiFi.
  3. Drag that into your local Arduino/library folder. This can be found by going into preferences and looking at your Sketchbook location

You may still need to have the http://arduino.esp8266.com/stable/package_esp8266com_index.json package installed beforehand, however.

Edit: That wasn't the full issue, you need to make sure you have the correct ESP8266 Board selected before compiling.

Hope this helps others.

jQuery Form Validation before Ajax submit

function validateForm()
{
    var a=document.forms["Form"]["firstname"].value;
    var b=document.forms["Form"]["midname"].value;
    var c=document.forms["Form"]["lastname"].value;
    var d=document.forms["Form"]["tribe"].value;
    if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
    {
        alert("Please Fill All Required Field");
        return false;
    }
    else{

        $.ajax({
        type: 'post',
        url: 'add.php',
        data: $('form').serialize(),
        success: function () {
          alert('Patient added');
          document.getElementById("form").reset();
        }
      });

    }
}

  $(function () {

    $('form').on('submit', function (e) {
      e.preventDefault();

      validateForm();


    });
  });

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.

Try installing the required verison.

If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.

also remove the lines

 <fork>true</fork>
     <executable>${JAVA_1_7_HOME}/bin/javac</executable>

from the pom.xml

Add hover text without javascript like we hover on a user's reputation

Often i reach for the abbreviation html tag in this situation.

<abbr title="Hover">Text</abbr>

https://www.w3schools.com/tags/tag_abbr.asp

Passing ArrayList from servlet to JSP

<html>
    <%

        ArrayList<Actor> list = new ArrayList<Actor>();
        list = (ArrayList<Actor>) request.getAttribute("actors");
    %>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Actor</title>
</head>

<body>

    <h2>This is Actor Class</h2>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>
            <% for(int i = 0; i < list.size(); i++) {
                Actor actor = new Actor();
                actor = list.get(i);
                //out.println(actor.getId());
                //out.println(actor.getFirstname());
                //out.println(actor.getLastname());
            %>


            <tr>
                <td><%=actor.getId()%></td>
                <td><%=actor.getFirstname()%></td>
                <td><%=actor.getLastname()%></td>
               </tr>
            <%
            };
            %>
        </tbody>
    </table>

</body>

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Filter

app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

Usage

<ANY ng-bind-html="value | unsafe"></ANY>

curl POST format for CURLOPT_POSTFIELDS

for nested arrays you can use:

$data = [
  'name[0]' = 'value 1',
  'name[1]' = 'value 2',
  'name[2]' = 'value 3',
  'id' = 'value 4',
  ....
];

Laravel 5 - redirect to HTTPS

for laravel 5.4 use this format to get https redirect instead of .htaccess

namespace App\Providers;

use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        URL::forceScheme('https');
    }
}

How can my iphone app detect its own version number?

This is a good thing to handle with a revision control system. That way when you get a bug report from a user, you can check out that revision of code and (hopefully) reproduce the bug running the exact same code as the user.

The idea is that every time you do a build, you will run a script that gets the current revision number of your code and updates a file within your project (usually with some form of token replacement). You can then write an error handling routine that always includes the revision number in the error output, or you can display it on an "About" page.

Jackson: how to prevent field serialization

set variable as

@JsonIgnore

This allows variable to get skipped by json serializer

How to convert Javascript datetime to C# datetime?

You could use the toJSON() JavaScript method, it converts a JavaScript DateTime to what C# can recognise as a DateTime.

The JavaScript code looks like this

var date = new Date();
date.toJSON(); // this is the JavaScript date as a c# DateTime

Note: The result will be in UTC time

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

the problem might be that networkservice has no read rights

salution:

rightclick your upload folder -> poperty's -> security ->Edit -> add -> type :NETWORK SERVICE -> check box full control allow-> press ok or apply

HTML img scaling

css is enough :

width : desired_width;
height: auto;/*to preserve the aspect ratio of the image*/

Should I return EXIT_SUCCESS or 0 from main()?

EXIT_FAILURE, either in a return statement in main or as an argument to exit(), is the only portable way to indicate failure in a C or C++ program. exit(1) can actually signal successful termination on VMS, for example.

If you're going to be using EXIT_FAILURE when your program fails, then you might as well use EXIT_SUCCESS when it succeeds, just for the sake of symmetry.

On the other hand, if the program never signals failure, you can use either 0 or EXIT_SUCCESS. Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.)

Using 0 has the minor advantage that you don't need #include <stdlib.h> in C, or #include <cstdlib> in C++ (if you're using a return statement rather than calling exit()) -- but for a program of any significant size you're going to be including stdlib directly or indirectly anyway.

For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of main() does an implicit return 0; anyway, so you might not need to use either 0 or EXIT_SUCCESS explicitly. (But at least in C, I consider an explicit return 0; to be better style.)

(Somebody asked about OpenVMS. I haven't used it in a long time, but as I recall odd status values generally denote success while even values denote failure. The C implementation maps 0 to 1, so that return 0; indicates successful termination. Other values are passed unchanged, so return 1; also indicates successful termination. EXIT_FAILURE would have a non-zero even value.)

Bootstrap 3 Flush footer to bottom. not fixed

For a pure CSS solution, scroll after the 2nd <hr>. The first one is the initial answer (given back in 2016)


The major flaw of the solutions above is they have a fixed height for the footer.
And that just doesn't cut it in the real world, where people use a zillion number of devices and have this bad habit of rotating them when you least expect it and **Poof!** there goes your page content behind the footer!

In the real world, you need a function that calculates the height of the footer and dynamically adjusts the page content's padding-bottom to accommodate that height. And you need to run this tiny function on page load and resize events as well as on footer's DOMSubtreeModified (just in case your footer gets dynamically updated asynchronously or it contains animated elements that change size when interacted with).

Here's a proof of concept, using jQuery v3.0.0 and Bootstrap v4-alpha, but there is no reason why it shouldn't work on lower versions of each.

_x000D_
_x000D_
jQuery(document).ready(function($) {_x000D_
  $.fn.accomodateFooter = function() {_x000D_
    var footerHeight = $('footer').outerHeight();_x000D_
    $(this).css({_x000D_
      'padding-bottom': footerHeight + 'px'_x000D_
    });_x000D_
  }_x000D_
  $('footer').on('DOMSubtreeModified', function() {_x000D_
    $('body').accomodateFooter();_x000D_
  })_x000D_
  $(window).on('resize', function() {_x000D_
    $('body').accomodateFooter();_x000D_
  })_x000D_
  $('body').accomodateFooter();_x000D_
  window.addMoreContentToFooter = function() {_x000D_
    var f = $('footer');_x000D_
    f.append($('<p />', {_x000D_
        text: "Human give me attention meow flop over sun bathe licks your face wake up wander around the house making large amounts of noise jump on top of your human's bed and fall asleep again. Throwup on your pillow sun bathe. The dog smells bad jump around on couch, meow constantly until given food, so nap all day, yet hiss at vacuum cleaner."_x000D_
      }))_x000D_
      .append($('<hr />'));_x000D_
  }_x000D_
});
_x000D_
body {_x000D_
  min-height: 100vh;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background-color: rgba(0, 0, 0, .65);_x000D_
  color: white;_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 100%;_x000D_
  padding: 1.5rem;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
footer hr {_x000D_
  border-top: 1px solid rgba(0, 0, 0, .42);_x000D_
  border-bottom: 1px solid rgba(255, 255, 255, .21);_x000D_
}
_x000D_
<link href="http://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">_x000D_
<link href="http://v4-alpha.getbootstrap.com/examples/starter-template/starter-template.css" rel="stylesheet">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.2.0/js/tether.min.js"></script>_x000D_
<script src="http://v4-alpha.getbootstrap.com/dist/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="navbar-toggler-icon"></span>_x000D_
      </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarsExampleDefault">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link</a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link disabled" href="#">Disabled</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>_x000D_
        <div class="dropdown-menu" aria-labelledby="dropdown01">_x000D_
          <a class="dropdown-item" href="#">Action</a>_x000D_
          <a class="dropdown-item" href="#">Another action</a>_x000D_
          <a class="dropdown-item" href="#">Something else here</a>_x000D_
        </div>_x000D_
      </li>_x000D_
    </ul>_x000D_
    <form class="form-inline my-2 my-lg-0">_x000D_
      <input class="form-control mr-sm-2" type="text" placeholder="Search">_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
    </form>_x000D_
  </div>_x000D_
</nav>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="starter-template">_x000D_
    <h1>Feed that footer - not a game (yet!)</h1>_x000D_
    <p class="lead">You will notice the body bottom padding is growing to accomodate the height of the footer as you feed it (so the page contents do not get covered by it).</p><button class="btn btn-warning" onclick="window.addMoreContentToFooter()">Feed that footer</button>_x000D_
    <hr />_x000D_
    <blockquote class="lead"><strong>Note:</strong> I used jQuery <code>v3.0.0</code> and Bootstrap <code>v4-alpha</code> but there is no reason why it shouldn't work with lower versions of each.</blockquote>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<footer>I am a footer with dynamic content._x000D_
  <hr />_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Initially, I have posted this solution here but I realized it might help more people if posted under this question.

Note: I have purposefully wrapped the $([selector]).accomodateFooter() as a jQuery plugin, so it could be run on any DOM element, as in most layouts it is not the $('body')'s bottom-padding that needs adjusting, but some page wrapper element with position:relative (usually the immediate parent of the footer).


Later edit (3+ years after initial answer):

At this point I no longer consider acceptable using JavaScript for positioning a dynamic content footer at the bottom of the page. It can be achieved with CSS alone, using flexbox, lightning fast, cross-browser.

Here it is:

_x000D_
_x000D_
// Left this in so you could inject content into the footer and test it:_x000D_
// (but it's no longer sizing the footer)_x000D_
_x000D_
function addMoreContentToFooter() {_x000D_
  var f = $('footer');_x000D_
  f.append($('<p />', {_x000D_
      text: "Human give me attention meow flop over sun bathe licks your face wake up wander around the house making large amounts of noise jump on top of your human's bed and fall asleep again. Throwup on your pillow sun bathe. The dog smells bad jump around on couch, meow constantly until given food, so nap all day, yet hiss at vacuum cleaner."_x000D_
    }))_x000D_
    .append($('<hr />'));_x000D_
}
_x000D_
.wrapper {_x000D_
  min-height: 100vh;_x000D_
  padding-top: 54px;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
.wrapper>* {_x000D_
  flex-grow: 0;_x000D_
}_x000D_
_x000D_
.wrapper>main {_x000D_
  flex-grow: 1;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background-color: rgba(0, 0, 0, .65);_x000D_
  color: white;_x000D_
  width: 100%;_x000D_
  padding: 1.5rem;_x000D_
}_x000D_
_x000D_
footer hr {_x000D_
  border-top: 1px solid rgba(0, 0, 0, .42);_x000D_
  border-bottom: 1px solid rgba(255, 255, 255, .21);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="wrapper">_x000D_
  <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown_x000D_
        </a>_x000D_
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
          <a class="dropdown-item" href="#">Action</a>_x000D_
          <a class="dropdown-item" href="#">Another action</a>_x000D_
          <div class="dropdown-divider"></div>_x000D_
          <a class="dropdown-item" href="#">Something else here</a>_x000D_
        </div>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
    <form class="form-inline my-2 my-lg-0">_x000D_
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
    </form>_x000D_
  </div>_x000D_
</nav>_x000D_
  <main>_x000D_
    <div class="container">_x000D_
      <div class="starter-template">_x000D_
        <h1>Feed that footer - not a game (yet!)</h1>_x000D_
        <p class="lead">Footer won't ever cover the body contents, as its not fixed. It's simply placed at the bottom when the page should be shorter using `min-height:100vh` on container and using flexbox to push it down.</p><button class="btn btn-warning" onclick="addMoreContentToFooter()">Feed that footer</button>_x000D_
        <hr />_x000D_
        <blockquote class="lead">_x000D_
          <strong>Note:</strong> This example uses current latest versions of jQuery (<code>3.4.1.slim</code>) and Bootstrap (<code>4.4.1</code>) (unlike the one above)._x000D_
        </blockquote>_x000D_
      </div>_x000D_
    </div>_x000D_
  </main>_x000D_
  <footer>I am a footer with dynamic content._x000D_
    <hr />_x000D_
  </footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Uploading/Displaying Images in MVC 4

Have a look at the following

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

your controller should have action method which would accept HttpPostedFileBase;

 public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(
                                   Server.MapPath("~/images/profile"), pic); 
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image 
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream()) 
            {
                 file.InputStream.CopyTo(ms);
                 byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return RedirectToAction("actionname", "controller name");
    }

Update 1

In case you want to upload files using jQuery with asynchornously, then try this article.

the code to handle the server side (for multiple upload) is;

 try
    {
        HttpFileCollection hfc = HttpContext.Current.Request.Files;
        string path = "/content/files/contact/";

        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                string fileName = "";
                if (Request.Browser.Browser == "IE")
                {
                    fileName = Path.GetFileName(hpf.FileName);
                }
                else
                {
                    fileName = hpf.FileName;
                }
                string fullPathWithFileName = path + fileName;
                hpf.SaveAs(Server.MapPath(fullPathWithFileName));
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.

UPDATE 2

Alternatively, you can try Async File Uploads in MVC 4.

Disable button in jQuery

There are two things here, and the highest voted answer is technically correct as per the OPs question.

Briefly summarized as:

$("some sort of selector").prop("disabled", true | false);

However should you be using jQuery UI (I know the OP wasn't but some people arriving here might be) then while this will disable the buttons click event it wont make the button appear disabled as per the UI styling.

If you are using a jQuery UI styled button then it should be enabled / disabled via:

$("some sort of selector").button("enable" | "disable");

http://api.jqueryui.com/button/#method-disable

Python Pandas Replacing Header with Top Row

@ostrokach answer is best. Most likely you would want to keep that throughout any references to the dataframe, thus would benefit from inplace = True.
df.rename(columns=df.iloc[0], inplace = True) df.drop([0], inplace = True)

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

how to completely clear localstorage

localStorage.clear();

how to completely clear sessionstorage

sessionStorage.clear();

[...] Cookies ?

var cookies = document.cookie;

for (var i = 0; i < cookies.split(";").length; ++i)
{
    var myCookie = cookies[i];
    var pos = myCookie.indexOf("=");
    var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

is there any way to get the value back after clear these ?

No, there isn't. But you shouldn't rely on this if this is related to a security question.

How to run jenkins as a different user

The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.

However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub. What if there are multiple jenkins servers that need to access the same gitolite server?

(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)

So in this case you do need to run the Jenkins daemon as a different user.

There are two steps:

Step 1

The main thing is to update the JENKINS_USER environment variable. Here's a patch showing how to change the user to ptran.

BEGIN PATCH
--- etc/default/jenkins.old     2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
 PIDFILE=/var/run/jenkins/jenkins.pid

 # user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran

 # location of the jenkins war file
 JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old      2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins  2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@

 #DAEMON=$JENKINS_SH
 DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG -   -pidfile=$PIDFILE" 
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE" 

 SU=/bin/su
END PATCH

Step 2

Update ownership of jenkins directories:

chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins

Step 3

Restart jenkins

sudo service jenkins restart

python: creating list from string

input = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
output = []
for item in input:
    items = item.split(',')
    output.append([items[0], int(items[1]), int(items[2])])

How to upsert (update or insert) in SQL Server 2005

You can check if the row exists, and then INSERT or UPDATE, but this guarantees you will be performing two SQL operations instead of one:

  1. check if row exists
  2. insert or update row

A better solution is to always UPDATE first, and if no rows were updated, then do an INSERT, like so:

update table1 
set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
where id = 'val1'

if @@ROWCOUNT = 0
  insert into table1(id, name, itemname, itemcatName, itemQty)
  values('val1', 'val2', 'val3', 'val4', 'val5')

This will either take one SQL operations, or two SQL operations, depending on whether the row already exists.

But if performance is really an issue, then you need to figure out if the operations are more likely to be INSERT's or UPDATE's. If UPDATE's are more common, do the above. If INSERT's are more common, you can do that in reverse, but you have to add error handling.

BEGIN TRY
  insert into table1(id, name, itemname, itemcatName, itemQty)
  values('val1', 'val2', 'val3', 'val4', 'val5')
END TRY
BEGIN CATCH
  update table1 
  set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
  where id = 'val1'
END CATCH

To be really certain if you need to do an UPDATE or INSERT, you have to do two operations within a single TRANSACTION. Theoretically, right after the first UPDATE or INSERT (or even the EXISTS check), but before the next INSERT/UPDATE statement, the database could have changed, causing the second statement to fail anyway. This is exceedingly rare, and the overhead for transactions may not be worth it.

Alternately, you can use a single SQL operation called MERGE to perform either an INSERT or an UPDATE, but that's also probably overkill for this one-row operation.

Consider reading about SQL transaction statements, race conditions, SQL MERGE statement.

Object does not support item assignment error

Another way would be adding __getitem__, __setitem__ function

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

How to tell if tensorflow is using gpu acceleration from inside python shell?

For TF2.4+ listed as the "official" way on tensorflow website to check if TF is using GPU or Not

>>> import tensorflow as tf
>>> print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Num GPUs Available:  2

How to select all checkboxes with jQuery?

This code works fine with me

<script type="text/javascript">
$(document).ready(function(){ 
$("#select_all").change(function(){
  $(".checkbox_class").prop("checked", $(this).prop("checked"));
  });
});
</script>

you only need to add class checkbox_class to all checkbox

Easy and simple :D

JavaScript displaying a float to 2 decimal places

let a = 0.0500
a.toFixed(2);

//output
0.05

How to set the matplotlib figure default size in ipython notebook?

Worked liked a charm for me:

matplotlib.rcParams['figure.figsize'] = (20, 10)

Angular 4: How to include Bootstrap?

As i can see you already got lots of answer but you can try this method to .

Its best practice not to use jquery in angular, I prefer https://github.com/valor-software/ngx-bootstrap/blob/development/docs/getting-started/ng-cli.md method to install bootstrap without using bootstrap js component which depends on jquery.

npm install ngx-bootstrap bootstrap --save

or

ng add ngx-bootstrap   (Preferred)

Keep your code jquery free in angular

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

Label on the left side instead above an input field

You can use form-inline class for each form-group :)

<form>                      
    <div class="form-group form-inline">                            
        <label for="exampleInputEmail1">Email address</label>
            <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
    </div>
</form>

Resizing an image in an HTML5 canvas

I know this is an old thread but it might be useful for some people such as myself that months after are hitting this issue for the first time.

Here is some code that resizes the image every time you reload the image. I am aware this is not optimal at all, but I provide it as a proof of concept.

Also, sorry for using jQuery for simple selectors but I just feel too comfortable with the syntax.

_x000D_
_x000D_
$(document).on('ready', createImage);_x000D_
$(window).on('resize', createImage);_x000D_
_x000D_
var createImage = function(){_x000D_
  var canvas = document.getElementById('myCanvas');_x000D_
  canvas.width = window.innerWidth || $(window).width();_x000D_
  canvas.height = window.innerHeight || $(window).height();_x000D_
  var ctx = canvas.getContext('2d');_x000D_
  img = new Image();_x000D_
  img.addEventListener('load', function () {_x000D_
    ctx.drawImage(this, 0, 0, w, h);_x000D_
  });_x000D_
  img.src = 'http://www.ruinvalor.com/Telanor/images/original.jpg';_x000D_
};
_x000D_
html, body{_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background: #000;_x000D_
}_x000D_
canvas{_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  z-index: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
  <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <title>Canvas Resize</title>_x000D_
  </head>_x000D_
  <body>_x000D_
    <canvas id="myCanvas"></canvas>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

My createImage function is called once when the document is loaded and after that it is called every time the window receives a resize event.

I tested it in Chrome 6 and Firefox 3.6, both on the Mac. This "technique" eats processor as it if was ice cream in the summer, but it does the trick.

How to delete a folder and all contents using a bat file in windows?

@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"

Explanation:

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.

/Q      Quiet mode, do not ask if ok to remove a directory tree with /S

Vertical rulers in Visual Studio Code

Visual Studio Code: Version 1.14.2 (1.14.2)

  1. Press Shift + Command + P to open panel
    • For non-macOS users, press Ctrl+P
  2. Enter "settings.json" to open setting files.
  3. At default setting, you can see this:

    // Columns at which to show vertical rulers
    "editor.rulers": [],
    

    This means the empty array won't show the vertical rulers.

  4. At right window "user setting", add the following:

    "editor.rulers": [140]

Save the file, and you will see the rulers.

WCF error: The caller was not authenticated by the service

Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.

Override standard close (X) button in a Windows Form

as Jon B said, but you'll also want to check for the ApplicationExitCall and TaskManagerClosing CloseReason:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (  e.CloseReason == CloseReason.WindowsShutDown 
        ||e.CloseReason == CloseReason.ApplicationExitCall
        ||e.CloseReason == CloseReason.TaskManagerClosing) { 
       return; 
    }
    e.Cancel = true;
    //assuming you want the close-button to only hide the form, 
    //and are overriding the form's OnFormClosing method:
    this.Hide();
}

android listview item height

The trick for me was not setting the height -- but instead setting the minHeight. This must be applied to the root view of whatever layout your custom adapter is using to render each row.

How to make android listview scrollable?

By default ListView is scrollable. Do not put ScrollView to the ListView

How to get a certain element in a list, given the position?

std::list doesn't provide any function to get element given an index. You may try to get it by writing some code, which I wouldn't recommend, because that would be inefficient if you frequently need to do so.

What you need is : std::vector. Use it as:

std::vector<Object> objects;
objects.push_back(myObject);

Object const & x = objects[0];    //index isn't checked
Object const & y = objects.at(0); //index is checked 

Purpose of "%matplotlib inline"

It is not mandatory to write that. It worked fine for me without (%matplotlib) magic function. I am using Sypder compiler, one that comes with in Anaconda.

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Can you load the GUIDs into a scratch table then do a

... WHERE var IN SELECT guid FROM #scratchtable

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

How can I obtain the element-wise logical NOT of a pandas Series?

In support to the excellent answers here, and for future convenience, there may be a case where you want to flip the truth values in the columns and have other values remain the same (nan values for instance)

In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series[series.notna()] #remove nan values
 
In[3]: series # without nan                                            
Out[3]: 
0     True
2    False
dtype: object

# Out[4] expected to be inverse of Out[3], pandas applies bitwise complement 
# operator instead as in `lambda x : (-1*x)-1`

In[4]: ~series
Out[4]: 
0    -2
2    -1
dtype: object

as a simple non-vectorized solution you can just, 1. check types2. inverse bools

In[1]: series = pd.Series([True, np.nan, False, np.nan])

In[2]: series = series.apply(lambda x : not x if x is bool else x)
Out[2]: 
Out[2]: 
0     True
1      NaN
2    False
3      NaN
dtype: object

How to launch an Activity from another Application in Android

Here is my example of launching bar/QR code scanner from my app if someone finds it useful

Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");

try 
{
    startActivityForResult(intent, SCAN_REQUEST_CODE);
} 
catch (ActivityNotFoundException e) 
{
    //implement prompt dialog asking user to download the package
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
    downloadDialog.setTitle(stringTitle);
    downloadDialog.setMessage(stringMessage);
    downloadDialog.setPositiveButton("yes",
            new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialogInterface, int i) 
                {
                    Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    try
                    {
                        myActivity.this.startActivity(intent);
                    }
                    catch (ActivityNotFoundException e)
                    {
                        Dialogs.this.showAlert("ERROR", "Google Play Market not found!");
                    }
                }
            });
    downloadDialog.setNegativeButton("no",
            new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int i) 
                {
                    dialog.dismiss();
                }
            });
    downloadDialog.show();
}

How to add a recyclerView inside another recyclerView

I ran into similar problem a while back and what was happening in my case was the outer recycler view was working perfectly fine but the the adapter of inner/second recycler view had minor issues all the methods like constructor got initiated and even getCount() method was being called, although the final methods responsible to generate view ie..

1. onBindViewHolder() methods never got called. --> Problem 1.

2. When it got called finally it never show the list items/rows of recycler view. --> Problem 2.

Reason why this happened :: When you put a recycler view inside another recycler view, then height of the first/outer recycler view is not auto adjusted. It is defined when the first/outer view is created and then it remains fixed. At that point your second/inner recycler view has not yet loaded its items and thus its height is set as zero and never changes even when it gets data. Then when onBindViewHolder() in your second/inner recycler view is called, it gets items but it doesn't have the space to show them because its height is still zero. So the items in the second recycler view are never shown even when the onBindViewHolder() has added them to it.

Solution :: you have to create your custom LinearLayoutManager for the second recycler view and that is it. To create your own LinearLayoutManager: Create a Java class with the name CustomLinearLayoutManager and paste the code below into it. NO CHANGES REQUIRED

public class CustomLinearLayoutManager extends LinearLayoutManager {

    private static final String TAG = CustomLinearLayoutManager.class.getSimpleName();

    public CustomLinearLayoutManager(Context context) {
        super(context);

    }

    public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {

        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);


            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }
        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        try {
            View view = recycler.getViewForPosition(position);

            if (view != null) {
                RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();

                int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                        getPaddingLeft() + getPaddingRight(), p.width);

                int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                        getPaddingTop() + getPaddingBottom(), p.height);

                view.measure(childWidthSpec, childHeightSpec);
                measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
                measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                recycler.recycleView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

PostgreSQL Error: Relation already exists

In my case, I had a sequence with the same name.

What is causing "Unable to allocate memory for pool" in PHP?

on my system i had to insert apc.shm_size = 64M into /usr/local/etc/php.ini (FreeBSD 9.1) then when i looked at apc.php (which i copied from /usr/local/share/doc/APC/apc.php to /usr/local/www/apache24/data) i found that the cache size had increased from the default of 32M to 64M and i was no longer getting a large cache full count

references: http://au1.php.net/manual/en/apc.configuration.php also read Bokan's comments, they were very helpful

URL string format for connecting to Oracle database with JDBC

There are two ways to set this up. If you have an SID, use this (older) format:

jdbc:oracle:thin:@[HOST][:PORT]:SID

If you have an Oracle service name, use this (newer) format:

jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE

Source: this OraFAQ page

The call to getConnection() is correct.

Also, as duffymo said, make sure the actual driver code is present by including ojdbc6.jar in the classpath, where the number corresponds to the Java version you're using.

How do I get indices of N maximum values in a NumPy array?

The following is a very easy way to see the maximum elements and its positions. Here axis is the domain; axis = 0 means column wise maximum number and axis = 1 means row wise max number for the 2D case. And for higher dimensions it depends upon you.

M = np.random.random((3, 4))
print(M)
print(M.max(axis=1), M.argmax(axis=1))

get list of packages installed in Anaconda

For script creation at Windows cmd or powershell prompt:

C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
conda list
pip list

Convert Iterator to ArrayList

I just want to point out a seemingly obvious solution that will NOT work:

List list = Stream.generate(iterator::next)
    .collect(Collectors.toList());

That's because Stream#generate(Supplier<T>) can create only infinite streams, it doesn't expect its argument to throw NoSuchElementException (that's what Iterator#next() will do in the end).

The xehpuk's answer should be used instead if the Iterator?Stream?List way is your choice.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

I modified the script by Nicolay77 to output the database to stdout (the usual way of unix scripts) so that I could output the data to text file or pipe it to any program I want. The resulting script is a bit simpler and works well.

Some examples:

./mdb_to_mysql.sh database.mdb > data.sql

./mdb_to_mysql.sh database.mdb | mysql destination-db -u user -p

Here is the modified script (save to mdb_to_mysql.sh)

#!/bin/bash
TABLES=$(mdb-tables -1 $1)

for t in $TABLES
do
    echo "DROP TABLE IF EXISTS $t;"
done

mdb-schema $1 mysql

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t
done

Clear dropdown using jQuery Select2

You can use this or refer further this https://select2.org/programmatic-control/add-select-clear-items

$('#mySelect2').val(null).trigger('change');

Using isKindOfClass with Swift

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if touch.view.isKindOfClass(UIPickerView)
    {

    }
}

Edit

As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?. You can read more about it on the section Optional Chaining sub section Downcasting.

Edit 2

As pointed on the other answer by user @KPM, using the is operator is the right way to do it.

How to pass parameter to a promise function

Another way(Must Try):

_x000D_
_x000D_
var promise1 = new Promise(function(resolve, reject) {_x000D_
  resolve('Success!');_x000D_
});_x000D_
var extraData = 'ImExtraData';_x000D_
promise1.then(function(value) {_x000D_
  console.log(value, extraData);_x000D_
  // expected output: "Success!" "ImExtraData"_x000D_
}, extraData);
_x000D_
_x000D_
_x000D_

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

Although BeautifulSoup supports the HTML parser by default If you want to use any other third-party Python parsers you need to install that external parser like(lxml).

soup_object= BeautifulSoup(markup,"html.parser") #Python HTML parser

But if you don't specified any parser as parameter you will get an warning that no parser specified.

soup_object= BeautifulSoup(markup) #Warnning

To use any other external parser you need to install it and then need to specify it. like

pip install lxml

soup_object= BeautifulSoup(markup,'lxml') # C dependent parser 

External parser have c and python dependency which may have some advantage and disadvantage.

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

Easy way to write contents of a Java InputStream to an OutputStream

Using Java7 and try-with-resources, comes with a simplified and readable version.

try(InputStream inputStream = new FileInputStream("C:\\mov.mp4");
    OutputStream outputStream = new FileOutputStream("D:\\mov.mp4")) {

    byte[] buffer = new byte[10*1024];

    for (int length; (length = inputStream.read(buffer)) != -1; ) {
        outputStream.write(buffer, 0, length);
    }
} catch (FileNotFoundException exception) {
    exception.printStackTrace();
} catch (IOException ioException) {
    ioException.printStackTrace();
}

How to make an element width: 100% minus padding?

box-sizing: border-box is a quick, easy way to fix it:

This will work in all modern browsers, and IE8+.

Here's a demo: http://jsfiddle.net/thirtydot/QkmSk/301/

.content {
    width: 100%;
    box-sizing: border-box;
}

The browser prefixed versions (-webkit-box-sizing, etc.) are not needed in modern browsers.

Easy way to turn JavaScript array into comma-separated list?

The Array.prototype.join() method:

_x000D_
_x000D_
var arr = ["Zero", "One", "Two"];_x000D_
_x000D_
document.write(arr.join(", "));
_x000D_
_x000D_
_x000D_

How to clone git repository with specific revision/changeset?

You Can use simply git checkout <commit hash>

in this sequence

bash git clone [URLTORepository] git checkout [commithash]

commit hash looks like this "45ef55ac20ce2389c9180658fdba35f4a663d204"

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Check if an element is present in an array

Single line code.. will return true or false

!!(arr.indexOf("val")+1)

How to set layout_weight attribute dynamically from code?

If you already define your view in your layout(xml) file, only want to change the weight programmatically, this way is better

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)   
mButton.getLayoutParams();
params.weight = 1.0f;
mButton.setLayoutParams(params);

new a LayoutParams overwrites other params defined in you xml file like margins, or you need to specify all of them in LayoutParams.

Entity Framework: table without primary key

Update to @CodeNotFound's answer.

In EF Core 3.0 DbQuery<T> has been deprecated, instead you should use Keyless entity types which supposedly does the same thing. These are configured with the ModelBuilder HasNoKey() method. In your DbContext class, do this

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<YourEntityType>(eb =>
        {
            eb.HasNoKey();
        });

}

There are restrictions though, notably:

  • Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.
  • Only support a subset of navigation mapping capabilities, specifically:
    • They may never act as the principal end of a relationship.
    • They may not have navigations to owned entities
    • They can only contain reference navigation properties pointing to regular entities.
    • Entities cannot contain navigation properties to keyless entity types.

This means that for the question of

If I want to use them and modify data, must I necessarily add a PK to those tables, or is there a workaround so that I don't have to?

You cannot modify data this way - however you can read. One could envision using another way (e.g. ADO.NET, Dapper) to modify data though - this could be a solution in cases where you rarely need to do non-read operations and still would like to stick with EF Core for your majority cases.

Also, if you truly need/want to work with heap(keyless) tables - consider ditching EF and use another way to talk to your database.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

This is a problem if you are running out of disk space. Solution is to free some space from the HDD.

Please read more to have the explanation :

If you are running MySQL at LINUX check the free space of HDD with the command disk free :

 df 

if you are getting something like that :

Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda2              5162828   4902260         0 100% /
udev                    156676        84    156592   1% /dev
/dev/sda3              3107124     70844   2878444   3% /home

Then this is the problem and now you have the solution!

Since mysql.sock wants to be created at the mysql folder which is almost always under the root folder could not achieve it because lack of space.

If you are periodicaly give the ls command under the mysql directory (at openSUSE 11.1 is at /var/lib/mysql) you will get something like :

hostname:/var/lib/mysql #
.protected  IT     files        ibdata1             mysqld.log  systemtemp
.tmp        NEWS   greekDB      mysql               mysqld.pid  test
ARXEIO      TEMP1  ib_logfile0  mysql.sock          polis
DATING      deisi  ib_logfile1  mysql_upgrade_info  restore

The mysql.sock file appearing and disappearing often (you must to try allot with the ls to hit a instance with the mysql.sock file on folder).

This caused by not enough disk space.

I hope that i will help some people!!!! Thanks!

Fatal error: Call to undefined function mcrypt_encrypt()

On ubuntu 14.10 :

Install module mcrypt

sudo apt install php5-mcrypt

Enable module mcrypt on apache2

sudo a2enmod mcrypt

Reload module configuration

sudo service apache2 restart

What is the height of iPhone's onscreen keyboard?

I created this table which contains both the heights of iPhone and iPad keyboards, both for landscape and portrait mode, both with the toolbar on and off.

I even explained how you can use these dimensions in your code here.

Note that you should only use these dimensions if you need to know the keyboard's dimension before you layout the view. Otherwise the solutions from the other answers work better.

enter image description here

var self = this?

Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this value.

Naming threads and thread-pools of ExecutorService

There's an open RFE for this with Oracle. From the comments from the Oracle employee it seems they don't understand the issue and won't fix. It's one of these things that is dead simple to support in the JDK (without breaking backwards compatibility) so it is kind of a shame that the RFE gets misunderstood.

As pointed out you need to implement your own ThreadFactory. If you don't want to pull in Guava or Apache Commons just for this purpose I provide here a ThreadFactory implementation that you can use. It is exactly similar to what you get from the JDK except for the ability to set the thread name prefix to something else than "pool".

package org.demo.concurrency;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadFactory with the ability to set the thread name prefix. 
 * This class is exactly similar to 
 * {@link java.util.concurrent.Executors#defaultThreadFactory()}
 * from JDK8, except for the thread naming feature.
 *
 * <p>
 * The factory creates threads that have names on the form
 * <i>prefix-N-thread-M</i>, where <i>prefix</i>
 * is a string provided in the constructor, <i>N</i> is the sequence number of
 * this factory, and <i>M</i> is the sequence number of the thread created 
 * by this factory.
 */
public class ThreadFactoryWithNamePrefix implements ThreadFactory {

    // Note:  The source code for this class was based entirely on 
    // Executors.DefaultThreadFactory class from the JDK8 source.
    // The only change made is the ability to configure the thread
    // name prefix.


    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    /**
     * Creates a new ThreadFactory where threads are created with a name prefix
     * of <code>prefix</code>.
     *
     * @param prefix Thread name prefix. Never use a value of "pool" as in that
     *      case you might as well have used
     *      {@link java.util.concurrent.Executors#defaultThreadFactory()}.
     */
    public ThreadFactoryWithNamePrefix(String prefix) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup()
                : Thread.currentThread().getThreadGroup();
        namePrefix = prefix + "-"
                + poolNumber.getAndIncrement()
                + "-thread-";
    }


    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}

When you want to use it you simply take advantage of the fact that all Executors methods allow you to provide your own ThreadFactory.

This

    Executors.newSingleThreadExecutor();

will give an ExecutorService where threads are named pool-N-thread-M but by using

    Executors.newSingleThreadExecutor(new ThreadFactoryWithNamePrefix("primecalc"));

you'll get an ExecutorService where threads are named primecalc-N-thread-M. Voila!

Can someone explain mappedBy in JPA and Hibernate?

MappedBy signals hibernate that the key for the relationship is on the other side.

This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.

How to run TypeScript files from command line?

For environments such as Webstorm where the node command cannot be changed to ts-node or npx:

  1. npm install ts-node typescript (Install dependencies)
  2. node --require ts-node/register src/foo.ts (Add --require ts-node/register to "Node parameters")

BOOLEAN or TINYINT confusion

MySQL does not have internal boolean data type. It uses the smallest integer data type - TINYINT.

The BOOLEAN and BOOL are equivalents of TINYINT(1), because they are synonyms.

Try to create this table -

CREATE TABLE table1 (
  column1 BOOLEAN DEFAULT NULL
);

Then run SHOW CREATE TABLE, you will get this output -

CREATE TABLE `table1` (
  `column1` tinyint(1) DEFAULT NULL
)

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

<?xml version="1.0" encoding="utf-8"?>

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>

Oracle ORA-12154: TNS: Could not resolve service name Error?

I struggled to resolve this problem for hours until I found an Environment variable called TNS_ADMIN set in My Computer => Properties => Advanced => Environment Variables => look in System variables for an entry called TNS_ADMIN. TNS_ADMIN is added to change the default path for Tnsnames.ora entry. This is useful when its used in a network environment where a generic tnsnames.ora entry can be setup for all the network computers. To look at the default path of tnsnames.ora add the default path in TNS_ADMIN.

Reference alias (calculated in SELECT) in WHERE clause

You can do this using cross apply

SELECT c.BalanceDue AS BalanceDue
FROM Invoices
cross apply (select (InvoiceTotal - PaymentTotal - CreditTotal) as BalanceDue) as c
WHERE  c.BalanceDue  > 0;

How to prevent line-break in a column of a table cell (not a single cell)?

There are a few ways to do this; none of them are the easy, obvious way.

Applying white-space:nowrap to a <col> won't work; only four CSS properties work on <col> elements - background-color, width, border, and visibility. IE7 and earlier used to support all properties, but that's because they used a strange table model. IE8 now matches everyone else.

So, how do you solve this?

Well, if you can ignore IE (including IE8), you can use the :nth-child() pseudoclass to select particular <td>s from each row. You'd use td:nth-child(2) { white-space:nowrap; }. (This works for this example, but would break if you had any rowspans or colspans involved.)

If you have to support IE, then you've got to go the long way around and apply a class to every <td> that you want to affect. It sucks, but them's the breaks.

In the long run, there are proposals to fix this lack in CSS, so that you can more easily apply styles to all the cells in a column. You'll be able to do something like td:nth-col(2) { white-space:nowrap; } and it would do what you want.

How to get address location from latitude and longitude in Google Map.?

Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.

https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY

Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.

Click here to get an API key

How to round a floating point number up to a certain decimal place?

The easiest way to do this is by using the below function, which is built in:

format()

For example:

format(1.242563,".2f")

The output would be:

1.24

Similarly:

format(9.165654,".1f")

would give:

9.2

Unrecognized escape sequence for path string containing backslashes

If your string is a file path, as in your example, you can also use Unix style file paths:

string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";

But the other answers have the more general solutions to string escaping in C#.

Create a CSV File for a user in PHP

To have it send it as a CSV and have it give the file name, use header():

http://us2.php.net/header

header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');

As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.

Is it possible to have multiple statements in a python lambda expression?

After analyzing all solutions offered above I came up with this combination, which seem most clear ad useful for me:

func = lambda *args, **kwargs: "return value" if [
    print("function 1..."),
    print("function n"),
    ["for loop" for x in range(10)]
] else None

Isn't it beautiful? Remember that there have to be something in list, so it has True value. And another thing is that list can be replaced with set, to look more like C style code, but in this case you cannot place lists inside as they are not hashabe

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

How to connect to a MS Access file (mdb) using C#?

Another simplest way to connect is through an OdbcConnection using App.config file like this

  <appSettings>  
    <add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True"/>
  </appSettings>

MyDB.mdb is my database file and it is present in current primary application folder with main exe file.

if your mdf file has password then use like this

  <appSettings>
    <add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True;Jet OLEDB:Database Password=Admin$@123"/>
  </appSettings>

Simplest way to wait some asynchronous tasks complete, in Javascript?

Expanding upon @freakish answer, async also offers a each method, which seems especially suited for your case:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    conn.collection(name).drop( callback );
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

IMHO, this makes the code both more efficient and more legible. I've taken the liberty of removing the console.log('dropped') - if you want it, use this instead:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    // if you really want the console.log( 'dropped' ),
    // replace the 'callback' here with an anonymous function
    conn.collection(name).drop( function(err) {
        if( err ) { return callback(err); }
        console.log('dropped');
        callback()
    });
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

how to measure running time of algorithms in python

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

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

Get filename from input [type='file'] using jQuery

You have to do this on the change event of the input type file this way:

$('#select_file').click(function() {
    $('#image_file').show();
    $('.btn').prop('disabled', false);
    $('#image_file').change(function() {
        var filename = $('#image_file').val();
        $('#select_file').html(filename);
    });
});?

How to generate a QR Code for an Android application?

Maybe this old topic but i found this library is very helpful and easy to use

QRGen

example for using it in android

 Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);

Get the last inserted row ID (with SQL statement)

Assuming a simple table:

CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);

We can capture IDENTITY values in a table variable for further consumption.

DECLARE @IDs TABLE(ID INT);

-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name) 
  OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';

SELECT ID FROM @IDs;

The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.

How to resolve TypeError: can only concatenate str (not "int") to str

Use this:

print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
    sum += number
print("Total Sum is: %d" %sum )

OnClick in Excel VBA

I don't think so. But you can create a shape object ( or wordart or something similiar ) hook Click event and place the object to position of the specified cell.

SQL join: selecting the last records in a one-to-many relationship

Please try this,

SELECT 
c.Id,
c.name,
(SELECT pi.price FROM purchase pi WHERE pi.Id = MAX(p.Id)) AS [LastPurchasePrice]
FROM customer c INNER JOIN purchase p 
ON c.Id = p.customerId 
GROUP BY c.Id,c.name;

How long to brute force a salted SHA-512 hash? (salt provided)

I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.

Dictionary password

Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.

Random password

If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:

N = Log60(t * 10,000) where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).

1 minute:    3.2
5 minute:    3.6
30 minutes:  4.1
2 hours:     4.4
3 days:      5.2

So given a 3 days we'd be able to crack the password if it's 5 characters long.

This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.

What's going on here?

Let's clear up some misconceptions:

  • The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.

  • SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.

  • update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.


Notes on accepted answer:

The accepted answer as of September 2014 is incorrect and dangerously wrong:

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.

The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...

Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.

Django - makemigrations - No changes detected

I had a different issue while creating a new app called deals. I wanted to separate the models inside that app so I had 2 model files named deals.py and dealers.py. When running python manage.py makemigrations I got: No changes detected.

I went ahead and inside the __init__.py which lives on the same directory where my model files lived (deals and dealer) I did

from .deals import *
from .dealers import *

And then the makemigrations command worked.

Turns out that if you are not importing the models anywhere OR your models file name isn't models.py then the models wont be detected.

Another issue that happened to me is the way I wrote the app in settings.py:

I had:

apps.deals

It should've been including the root project folder:

cars.apps.deals

How to get form values in Symfony2 controller

I think that in order to get the request data, bound and validated by the form object, you must use this command :

$form->getViewData();
$form->getClientData(); // Deprecated since version 2.1, to be removed in 2.3.

Is there a command for formatting HTML in the Atom editor?

Not Just HTML, Using atom-beautify - Package for Atom, you can format code for HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more) in Atom within a matter of seconds.

To Install the atom-beautify package :

  • Open Atom Editor.
  • Press Ctrl+Shift+P (Cmd+Shift+P on mac), this will open the atom Command Palette.
  • Search and click on Install Packages & Themes. A Install Package window comes up.
  • Search for Beautify package, you will see a lot of beautify packages. Install any. I will recommend for atom-beautify.
  • Now Restart atom and TADA! now you are ready for quick formatting.

To Format text Using atom-beautify :

  • Go to the file you want to format.
  • Hit Ctrl+Alt+B (Ctrl+Option+B on mac).
  • Your file is formatted in seconds.

How to make a function wait until a callback has been called using node.js

It's 2020 and chances are the API has already a promise-based version that works with await. However, some interfaces, especially event emitters will require this workaround:

// doesn't wait
let value;
someEventEmitter.once((e) => { value = e.value; });
// waits
let value = await new Promise((resolve) => {
  someEventEmitter.once('event', (e) => { resolve(e.value); });
});

In this particular case it would be:

let response = await new Promise((resolve) => {
  myAPI.exec('SomeCommand', (response) => { resolve(response); });
});

Await has been in new Node.js releases for the past 3 years (since v7.6).

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

Tools for creating Class Diagrams

I've used Enterprise Architect in the past - not free, but not too expensive, and it produces nice diagrams.

angularjs ng-style: background-image isn't working

If we have a dynamic value that needs to go in a css background or background-image attribute, it can be just a bit more tricky to specify.

Let’s say we have a getImage() function in our controller. This function returns a string formatted similar to this: url(icons/pen.png). If we do, the ngStyle declaration is specified the exact same way as before:

ng-style="{ 'background-image': getImage() }"

Make sure to put quotes around the background-image key name. Remember, this must be formatted as a valid Javascript object key.

Session variables not working php

Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.

Determining 32 vs 64 bit in C++

Unfortunately there is no cross platform macro which defines 32 / 64 bit across the major compilers. I've found the most effective way to do this is the following.

First I pick my own representation. I prefer ENVIRONMENT64 / ENVIRONMENT32. Then I find out what all of the major compilers use for determining if it's a 64 bit environment or not and use that to set my variables.

// Check windows
#if _WIN32 || _WIN64
#if _WIN64
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif

// Check GCC
#if __GNUC__
#if __x86_64__ || __ppc64__
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif

Another easier route is to simply set these variables from the compiler command line.

How to alert using jQuery

$(".overdue").each( function() {
    alert("Your book is overdue.");
});

Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.

Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).

Perhaps use the size function:

alert( "You have " + $(".overdue").size() + " books overdue." );

How to destroy a DOM element with jQuery?

Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.

Ex: $("#my-element").remove();

I had to use the element's class instead, or nothing happened.

Ex: $(".my-element").remove();

C++ Matrix Class

In C++ you can use like this:

matrix *p = new matrix;

After that,

delete p; 

Create an array of integers property in Objective-C

You can put this in your .h file for your class and define it as property, in XCode 7:

@property int  (*stuffILike) [10];

Limit results in jQuery UI Autocomplete

Same like "Jayantha" said using css would be the easiest approach, but this might be better,

.ui-autocomplete { max-height: 200px; overflow-y: scroll; overflow-x: hidden;}

Note the only difference is "max-height". this will allow the widget to resize to smaller height but not more than 200px

Wheel file installation

you can follow the below command to install using the wheel file at your local

pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl

Run a controller function whenever a view is opened/shown

Considering Ionic's ability to cache view elements and scope data mentioned above, this might be another way of doing, if you want to run the controller every time the view gets loaded. You can globally disable the caching mechanism used by ionic by doing:

$ionicConfigProvider.views.maxCache(0);

Else, the way I had it working for me was doing

$scope.$on("$ionicView.afterLeave", function () {
     $ionicHistory.clearCache();
}); 

This is to clear the cache before leaving the view to re-run controller every time you enter back again.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Scanner's buffer full when we take a input string through scan.nextLine(); so it skips the input next time . So solution is that we can create a new object of Scanner , the name of the object can be same as previous object......

How can I schedule a job to run a SQL query daily?

Using T-SQL: My job is executing stored procedure. You can easy change @command to run your sql.

EXEC msdb.dbo.sp_add_job  
   @job_name = N'MakeDailyJob',   
   @enabled = 1,   
   @description = N'Procedure execution every day' ; 

 EXEC msdb.dbo.sp_add_jobstep  
    @job_name = N'MakeDailyJob',   
    @step_name = N'Run Procedure',   
    @subsystem = N'TSQL',   
    @command = 'exec BackupFromConfig';

 EXEC msdb.dbo.sp_add_schedule  
    @schedule_name = N'Everyday schedule',   
    @freq_type = 4,  -- daily start
    @freq_interval = 1,
    @active_start_time = '230000' ;   -- start time 23:00:00

 EXEC msdb.dbo.sp_attach_schedule  
   @job_name = N'MakeDailyJob',  
   @schedule_name = N'Everyday schedule' ;

 EXEC msdb.dbo.sp_add_jobserver  
   @job_name = N'MakeDailyJob',  
   @server_name = @@servername ;

What are the retransmission rules for TCP?

There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.

They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.

More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.

The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.

TCP never drops data so no, there is no way to indicate a server should forget about some segment.

How to force a WPF binding to refresh?

MultiBinding friendly version...

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}

How do I prevent Conda from activating the base environment by default?

So in the end I found that if I commented out the Conda initialisation block like so:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
# __conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
# if [ $? -eq 0 ]; then
    # eval "$__conda_setup"
# else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
    . "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
    export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
# unset __conda_setup
# <<< conda initialize <<<

It works exactly how I want. That is, Conda is available to activate an environment if I want, but doesn't activate by default.

Registering for Push Notifications in Xcode 8/Swift 3.0?

First, listen to user notification status, i.e., registerForRemoteNotifications() to get APNs device token;
Second, request authorization. When being authorized by the user, deviceToken will be sent to the listener, the AppDelegate;
Third, report the device token to your server.

extension AppDelegate {
    /// 1. ?? deviceToken
    UIApplication.shared.registerForRemoteNotifications()

    /// 2. ???????????(????? token)
    static func registerRemoteNotifications() {
        if #available(iOS 10, *) {
            let uc = UNUserNotificationCenter.current()
            uc.delegate = UIApplication.shared.delegate as? AppDelegate
            uc.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                if let error = error { // ???????,????? aps-certificate,? error ??? nil
                    print("UNUserNotificationCenter ??????, \(error)")
                }
                DispatchQueue.main.async {
                    onAuthorization(granted: granted)
                }
            }
        } else {
            let app = UIApplication.shared
            app.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) // ??????
        }
    }

    // ? app.registerUserNotificationSettings() ???????????????,????????
    func application(_ app: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        // ???????,????????
        // a ???????,???app????,?????????
        // b ??????????,??????????,???????,??token,?????
        // c ??badge, alert?sound ?,notificationSettings.types.rawValue ?? 0 ? app.isRegisteredForRemoteNotifications ??,????token,??????(?????????????),???types??????
        // ???????,????????,?? isRegisteredForRemoteNotifications ??? false
       onAuthorization(granted: app.isRegisteredForRemoteNotifications)
    }

    static func onAuthorization(granted: Bool) {
        guard granted else { return }
        // do something
    }
}

extension AppDelegate {
    func application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //
    }

    // ?????? token,??? aps-certificate ??????? token,???????????? token
    func application(_ app: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        //
    }
}

How to check if a file exists in Documents folder?

NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath =  [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:@"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:@".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(@"%@", imagePath);

//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
    NSLog("File not exist");
} else {
    NSLog("File exist");
}

//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
    cell.photoImageView.image = image;//Display image
}

How to change Angular CLI favicon

In my case, the problem was that I had different dimensions compared to normal one. I had 48x48 px whereas it was expecting 32x32 px and my extension was png so I had to change it to ico

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

How do I decode a string with escaped unicode?

UPDATE: Please note that this is a solution that should apply to older browsers or non-browser platforms, and is kept alive for instructional purposes. Please refer to @radicand 's answer below for a more up to date answer.


This is a unicode, escaped string. First the string was escaped, then encoded with unicode. To convert back to normal:

var x = "http\\u00253A\\u00252F\\u00252Fexample.com";
var r = /\\u([\d\w]{4})/gi;
x = x.replace(r, function (match, grp) {
    return String.fromCharCode(parseInt(grp, 16)); } );
console.log(x);  // http%3A%2F%2Fexample.com
x = unescape(x);
console.log(x);  // http://example.com

To explain: I use a regular expression to look for \u0025. However, since I need only a part of this string for my replace operation, I use parentheses to isolate the part I'm going to reuse, 0025. This isolated part is called a group.

The gi part at the end of the expression denotes it should match all instances in the string, not just the first one, and that the matching should be case insensitive. This might look unnecessary given the example, but it adds versatility.

Now, to convert from one string to the next, I need to execute some steps on each group of each match, and I can't do that by simply transforming the string. Helpfully, the String.replace operation can accept a function, which will be executed for each match. The return of that function will replace the match itself in the string.

I use the second parameter this function accepts, which is the group I need to use, and transform it to the equivalent utf-8 sequence, then use the built - in unescape function to decode the string to its proper form.

C compile error: "Variable-sized object may not be initialized"

int size=5;
int ar[size ]={O};

/* This  operation gives an error -  
variable sized array may not be 
initialised.  Then just try this. 
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
    ar[i]=0;
}

Difference between 'cls' and 'self' in Python classes?

cls implies that method belongs to the class while self implies that the method is related to instance of the class,therefore member with cls is accessed by class name where as the one with self is accessed by instance of the class...it is the same concept as static member and non-static members in java if you are from java background.

What exactly is a Maven Snapshot and why do we need it?

The three others answers provide you a good vision of what a -SNAPSHOT version is. I just wanted to add some information regarding the behavior of Maven when it finds a SNAPSHOT dependency.

When you build an application, Maven will search for dependencies in the local repository. If a stable version is not found there, it will search the remote repositories (defined in settings.xml or pom.xml) to retrieve this dependency. Then, it will copy it into the local repository, to make it available for the next builds.

For example, a foo-1.0.jar library is considered as a stable version, and if Maven finds it in the local repository, it will use this one for the current build.

Now, if you need a foo-1.0-SNAPSHOT.jar library, Maven will know that this version is not stable and is subject to changes. That's why Maven will try to find a newer version in the remote repositories, even if a version of this library is found on the local repository. However, this check is made only once per day. That means that if you have a foo-1.0-20110506.110000-1.jar (i.e. this library has been generated on 2011/05/06 at 11:00:00) in your local repository, and if you run the Maven build again the same day, Maven will not check the repositories for a newer version.

Maven provides you a way to change this update policy in your repository definition:

<repository>
    <id>foo-repository</id>
    <url>...</url>
    <snapshots>
        <enabled>true</enabled>
        <updatePolicy>XXX</updatePolicy>
    </snapshots>
</repository>

where XXX can be:

  • always: Maven will check for a newer version on every build;
  • daily, the default value;
  • interval:XXX: an interval in minutes (XXX)
  • never: Maven will never try to retrieve another version. It will do that only if it doesn't exist locally. With the configuration, SNAPSHOT version will be handled as the stable libraries.

(model of the settings.xml can be found here)

Turn off deprecated errors in PHP 5.3

I just faced a similar problem where a SEO plugin issued a big number of warnings making my blog disk use exceed the plan limit.

I found out that you must include the error_reporting command after the wp-settings.php require in the wp-config.php file:

   require_once( ABSPATH .'wp-settings.php' );
   error_reporting( E_ALL ^ ( E_NOTICE | E_WARNING | E_DEPRECATED ) );

by doing this no more warnings, notices nor deprecated lines are appended to your error log file!

Tested on WordPress 3.8 but I guess it works for every installation.

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

AngularJS: ng-model not binding to ng-checked for checkboxes

You can use ng-value-true to tell angular that your ng-model is a string.

I could only get ng-true-value working if I added the extra quotes like so (as shown in the official Angular docs - https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D)

ng-true-value="'1'"

Code line wrapping - how to handle long lines

This is how I do it, and Google does it my way.

  • Break before the symbol for non-assignment operators.
  • Break after the symbol for = and for ,.

In your case, since you're using 120 characters, you can break it after the assignment operator resulting in

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

In Java, and for this particular case, I would give two tabs (or eight spaces) after the break, depending on whether tabs or spaces are used for indentation.

This is of course a personal preference and if your project has its own convention for line-wrapping then that is what you should follow whether you like it or not.

What is the quickest way to HTTP GET in Python?

theller's solution for wget is really useful, however, i found it does not print out the progress throughout the downloading process. It's perfect if you add one line after the print statement in reporthook.

import sys, urllib

def reporthook(a, b, c):
    print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
    sys.stdout.flush()
for url in sys.argv[1:]:
    i = url.rfind("/")
    file = url[i+1:]
    print url, "->", file
    urllib.urlretrieve(url, file, reporthook)
print

Why can't I have abstract static methods in C#?

Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritance irrelevant.

Assume you could, for a moment, inherit static methods. Imagine this scenario:

public static class Base
{
    public static virtual int GetNumber() { return 5; }
}

public static class Child1 : Base
{
    public static override int GetNumber() { return 1; }
}

public static class Child2 : Base
{
    public static override int GetNumber() { return 2; }
}

If you call Base.GetNumber(), which method would be called? Which value returned? It's pretty easy to see that without creating instances of objects, inheritance is rather hard. Abstract methods without inheritance are just methods that don't have a body, so can't be called.

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

Add / remove input field dynamically with jQuery

Another solution could be:

<script>
$(document)
        .ready(
                function() {
                    var wrapper = $(".myFields");
                    $(add_button)
                            .click(
                                    function(e) {
                                        e.preventDefault();
                                        $(wrapper)
                                                .append(
                                                        '.....'); //add fields here
                                    });
                    $(wrapper).on("click", ".delFld", function(e) {
                        e.preventDefault();
                        $(this).parent('div').remove();
                    })
                }); 
</script>

Source: Here

Efficiency of Java "Double Brace Initialization"?

Mario Gleichman describes how to use Java 1.5 generic functions to simulate Scala List literals, though sadly you wind up with immutable Lists.

He defines this class:

package literal;

public class collection {
    public static <T> List<T> List(T...elems){
        return Arrays.asList( elems );
    }
}

and uses it thusly:

import static literal.collection.List;
import static system.io.*;

public class CollectionDemo {
    public void demoList(){
        List<String> slist = List( "a", "b", "c" );
        List<Integer> iList = List( 1, 2, 3 );
        for( String elem : List( "a", "java", "list" ) )
            System.out.println( elem );
    }
}

Google Collections, now part of Guava supports a similar idea for list construction. In this interview, Jared Levy says:

[...] the most heavily-used features, which appear in almost every Java class I write, are static methods that reduce the number of repetitive keystrokes in your Java code. It's so convenient being able to enter commands like the following:

Map<OneClassWithALongName, AnotherClassWithALongName> = Maps.newHashMap();

List<String> animals = Lists.immutableList("cat", "dog", "horse");

7/10/2014: If only it could be as simple as Python's:

animals = ['cat', 'dog', 'horse']

2/21/2020: In Java 11 you can now say:

animals = List.of(“cat”, “dog”, “horse”)

Get top most UIViewController

In a very rare case, with custom segue, the top most view controller is not in a navigation stack or tab bar controller or presented, but its view is inserted to the top of key windown's subviews.

In such situation, it's necessary to check if UIApplication.shared.keyWindow.subviews.last == self.view to determine if the current view controller is the top most.

How do I use a delimiter with Scanner.useDelimiter in Java?

The scanner can also use delimiters other than whitespace.

Easy example from Scanner API:

 String input = "1 fish 2 fish red fish blue fish";

 // \\s* means 0 or more repetitions of any whitespace character 
 // fish is the pattern to find
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

 System.out.println(s.nextInt());   // prints: 1
 System.out.println(s.nextInt());   // prints: 2
 System.out.println(s.next());      // prints: red
 System.out.println(s.next());      // prints: blue

 // don't forget to close the scanner!!
 s.close(); 

The point is to understand the regular expressions (regex) inside the Scanner::useDelimiter. Find an useDelimiter tutorial here.


To start with regular expressions here you can find a nice tutorial.

Notes

abc…    Letters
123…    Digits
\d      Any Digit
\D      Any Non-digit character
.       Any Character
\.      Period
[abc]   Only a, b, or c
[^abc]  Not a, b, nor c
[a-z]   Characters a to z
[0-9]   Numbers 0 to 9
\w      Any Alphanumeric character
\W      Any Non-alphanumeric character
{m}     m Repetitions
{m,n}   m to n Repetitions
*       Zero or more repetitions
+       One or more repetitions
?       Optional character
\s      Any Whitespace
\S      Any Non-whitespace character
^…$     Starts and ends
(…)     Capture Group
(a(bc)) Capture Sub-group
(.*)    Capture all
(ab|cd) Matches ab or cd

Month name as a string

The only one way on Android to get properly formatted stanalone month name for such languages as ukrainian, russian, czech

private String getMonthName(Calendar calendar, boolean short) {
    int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR;
    if (short) {
        flags |= DateUtils.FORMAT_ABBREV_MONTH;
    }
    return DateUtils.formatDateTime(getContext(), calendar.getTimeInMillis(), flags);
}

Tested on API 15-25

Output for May is ??? but not ???

Memory errors and list limits?

The MemoryError exception that you are seeing is the direct result of running out of available RAM. This could be caused by either the 2GB per program limit imposed by Windows (32bit programs), or lack of available RAM on your computer. (This link is to a previous question).

You should be able to extend the 2GB by using 64bit copy of Python, provided you are using a 64bit copy of windows.

The IndexError would be caused because Python hit the MemoryError exception before calculating the entire array. Again this is a memory issue.

To get around this problem you could try to use a 64bit copy of Python or better still find a way to write you results to file. To this end look at numpy's memory mapped arrays.

You should be able to run you entire set of calculation into one of these arrays as the actual data will be written disk, and only a small portion of it held in memory.

Return a `struct` from a function in C

struct var e2 address pushed as arg to callee stack and values gets assigned there. In fact, get() returns e2's address in eax reg. This works like call by reference.

Google maps Places API V3 autocomplete - select first option on enter

@Alexander 's solution is the one which I was looking for. But it was causing an error - TypeError: a.stopPropagation is not a function.

So I made the event with KeyboardEvent. Here's the working code and Javascript version is very convenient for React.js projects. I also used this for my React.js project.

(function selectFirst(input) {
  let _addEventListener = input.addEventListener
    ? input.addEventListener
    : input.attachEvent;

  function addEventListenerWrapper(type, listener) {
    if (type === 'keydown') {
      console.log('keydown');

      let orig_listener = listener;
      listener = event => {
        let suggestion_selected =
          document.getElementsByClassName('pac-item-selected').length > 0;

        if (event.keyCode === 13 && !suggestion_selected) {
          let simulated_downarrow = new KeyboardEvent('keydown', {
            bubbles: true,
            cancelable: true,
            keyCode: 40
          });

          orig_listener.apply(input, [simulated_downarrow]);
        }

        orig_listener.apply(input, [event]);
      };
    }

    _addEventListener.apply(input, [type, listener]);
  }

  if (input.addEventListener) input.addEventListener = addEventListenerWrapper;
  else if (input.attachEvent) input.attachEvent = addEventListenerWrapper;
})(addressInput);

this.autocomplete = new window.google.maps.places.Autocomplete(addressInput, options);

Hope this can help someone, :)

Change header text of columns in a GridView

You should do that in GridView's RowDataBound event which is triggered for every GridViewRow after it was databound.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Text = "Date";
    }
}

or you can set AutogenerateColumns to false and add the columns declaratively on aspx:

<asp:gridview id="GridView1" 
  onrowdatabound="GridView1_RowDataBound"
  autogeneratecolumns="False"
  emptydatatext="No data available." 
   runat="server">
    <Columns>
         <asp:BoundField DataField="DateField" HeaderText="Date" 
            SortExpression="DateField" />
    </Columns>
</asp:gridview>

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

This is what worked for me:

Add allowedHosts under devServer in your webpack.config.js:

devServer: {
  compress: true,
  inline: true,
  port: '8080',
  allowedHosts: [
      '.amazonaws.com'
  ]
},

I did not need to use the --host or --public params.

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

In case you are working with environments or docker images you can really change /etc/host I recommend just changing the binding from star to 0.0.0.0.

So (basing on my case for instance) instead of:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005"

You would define it as:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0.0.0.0:5005"

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

What character represents a new line in a text area

&#10;- Line Feed and &#13; Carriage Return

These HTML entities will insert a new line or carriage return inside a text area.

How to make a vertical SeekBar in Android?

Getting started

Add these lines to build.gradle.

dependencies {
    compile 'com.h6ah4i.android.widget.verticalseekbar:verticalseekbar:0.7.2'
}

Usage

Java code

public class TestVerticalSeekbar extends AppCompatActivity {
    private SeekBar volumeControl = null;


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

        volumeControl = (SeekBar) findViewById(R.id.mySeekBar);

        volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progressChanged = 0;

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progressChanged = progress;
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                Toast.makeText(getApplicationContext(), "seek bar progress:" + progressChanged,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

}

Layout XML

<!-- This library requires pair of the VerticalSeekBar and VerticalSeekBarWrapper classes -->
<com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper
    android:layout_width="wrap_content"
    android:layout_height="150dp">
    <com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar
        android:id="@+id/mySeekBar"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:max="100"
        android:progress="0"
        android:splitTrack="false"
        app:seekBarRotation="CW90" /> <!-- Rotation: CW90 or CW270 -->
</com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper>

NOTE: android:splitTrack="false" is required for Android N+.

What is AndroidX?

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Changes in gradle:

implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'

When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library

Refer to: https://developer.android.com/jetpack/androidx/migrate

Bootstrap 3: Using img-circle, how to get circle from non-square image?

You have to give height and width to that image.

eg. height : 200px and width : 200px also give border-radius:50%;

to create circle you have to give equal height and width

if you are using bootstrap then give height and width and img-circle class to img

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

python: Change the scripts working directory to the script's own directory

You can get a shorter version by using sys.path[0].

os.chdir(sys.path[0])

From http://docs.python.org/library/sys.html#sys.path

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter

How to make picturebox transparent?

GameBoard is control of type DataGridView; The image should be type of PNG with transparent alpha channel background;

        Image test = Properties.Resources.checker_black;
        PictureBox b = new PictureBox();
        b.Parent = GameBoard;
        b.Image = test;
        b.Width = test.Width*2;
        b.Height = test.Height*2;
        b.Location = new Point(0, 90);
        b.BackColor = Color.Transparent;
        b.BringToFront();

enter image description here

Window vs Page vs UserControl for WPF navigation?

We usually use One Main Window for the application and other windows can be used in situations like when you need popups because instead of using popup controls in XAML which are not visible we can use a Window that is visible at design time so that'll be easy to work with

on the other hand we use many pages to navigate from one screen to another like User management screen to Order Screen etc In the main Window we can use Frame control for navigation like below XAML

    <Frame Name="mainWinFrame" NavigationUIVisibility="Hidden"  ButtonBase.Click="mainWinFrame_Click">
    </Frame>

C#

     private void mainWinFrame_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (e.OriginalSource is Button)
            {
                Button btn = (Button)e.OriginalSource;

                if ((btn.CommandParameter != null) && (btn.CommandParameter.Equals("Order")))
                {

                    mainWinFrame.Navigate(OrderPage);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error");
        }
    }

That's one way of doing it We can also use a Tab Control instead of Fram and Add pages to it using a Dictionary while adding new page check if the control already exists then only navigate otherwise add and navigate. I hope that'll help someone

Passing an array by reference

It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don't use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

E.g. int &myArray[100] // array of references

So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

E.g int (&myArray)[100] // reference of an array of 100 ints

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

What is the difference between using constructor vs getInitialState in React / React Native?

The difference between constructor and getInitialState is the difference between ES6 and ES5 itself.
getInitialState is used with React.createClass and
constructor is used with React.Component.

Hence the question boils down to advantages/disadvantages of using ES6 or ES5.

Let's look at the difference in code

ES5

var TodoApp = React.createClass({ 
  propTypes: {
    title: PropTypes.string.isRequired
  },
  getInitialState () { 
    return {
      items: []
    }; 
  }
});

ES6

class TodoApp extends React.Component {
  constructor () {
    super()
    this.state = {
      items: []
    }
  }
};

There is an interesting reddit thread regarding this.

React community is moving closer to ES6. Also it is considered as the best practice.

There are some differences between React.createClass and React.Component. For instance, how this is handled in these cases. Read more about such differences in this blogpost and facebook's content on autobinding

constructor can also be used to handle such situations. To bind methods to a component instance, it can be pre-bonded in the constructor. This is a good material to do such cool stuff.

Some more good material on best practices
Best Practices for Component State in React.js
Converting React project from ES5 to ES6

Update: April 9, 2019,:

With the new changes in Javascript class API, you don't need a constructor.

You could do

class TodoApp extends React.Component {

    this.state = {items: []}
};

This will still get transpiled to constructor format, but you won't have to worry about it. you can use this format that is more readable.

react hooks image With React Hooks

From React version 16.8, there's a new API Called hooks.

Now, you don't even need a class component to have a state. It can even be done in a functional component.

import React, { useState } from 'react';

function TodoApp () {
  const items = useState([]);

Note that the initial state is passed as an argument to useState; useState([])

Read more about react hooks from the official docs

for each inside a for each - Java

If I understand correctly, what you want to do, in pseudo-code is the following:

for (Tweet tweet : tweets) {
    if (!db.containsTweet(tweet.getId())) {
        db.insertTweet(tweet.getText(), tweet.getId());
    }
}

I assume your db class actually uses an sqlite database as a backend? What you could do is implement containsTweet directly and just query the database each time, but that seems less than perfect. The easiest solution if we go by your base code is to just keep a Set around that indexes the tweets. Since I can't be sure what the equals() method of Tweet looks like, I'll just store the identifiers in there. Then you get:

Set<Integer> tweetIds = new HashSet<Integer>(); // or long, whatever
for (Tweet tweet : tweets) {
    if (!tweetIds.contains(tweet.getId())) {
        db.insertTweet(tweet.getText(), tweet.getId());
        tweetIds.add(tweet.getId());
    }
}

It would probably be better to save a tiny bit of this work, by sorting the list of tweets to begin with and then just filtering out duplicate tweets. You could use:

// if tweets is a List
Collections.sort(tweets, new Comparator() {
    public int compare (Object t1, Object t2) {
        // might be the wrong way around
        return ((Tweet)t1).getId() - ((Tweet)t2).getId();
    }
}

Then process it

Integer oldId;
for (Tweet tweet : tweets) {
    if (oldId == null || oldId != tweet.getId()) {
        db.insertTweet(tweet.getText(), tweet.getId());
    }
    oldId = tweet.getId();
}

Yes, you could do this using a second for-loop, but you'll run into performance problems much more quickly than with this approach (although what we're doing here is trading time for memory performance, of course).

JS search in object values

MAKE SIMPLE

const objects = [
     {
     "foo" : "bar",
     "bar" : "sit",
     "date":"2020-12-20"
     },
     {
     "foo" : "lorem",
     "bar" : "ipsum",
     "date":"2018-07-02"
     },
     {
     "foo" : "dolor",
     "bar" : "amet",
     "date":"2003-10-08"
     },
     {
     "foo" : "lolor",
     "bar" : "amet",
     "date":"2003-10-08"
     }
     ];
     
     
     
     const filter = objects.filter(item => {
     const obj = Object.values(item)
     return obj.join("").indexOf('2003') !== -1
     })
     
     console.log(filter)

How to get numeric position of alphabets in java?

First you need to write a loop to iterate over the characters in the string. Take a look at the String class which has methods to give you its length and to find the charAt at each index.

For each character, you need to work out its numeric position. Take a look at this question to see how this could be done.

PHP get dropdown value and text

Is there a reason you didn't just use this?

<select id="animal" name="animal">                      
  <option value="0">--Select Animal--</option>
  <option value="Cat">Cat</option>
  <option value="Dog">Dog</option>
  <option value="Cow">Cow</option>
</select>

if($_POST['submit'] && $_POST['submit'] != 0)
{
   $animal=$_POST['animal'];
}

Javascript ES6/ES5 find in array and change

worked for me

let returnPayments = [ ...this.payments ];

returnPayments[this.payments.findIndex(x => x.id == this.payment.id)] = this.payment;

How to get the cell value by column name not by index in GridView in asp.net

protected void CheckedRecords(object sender, EventArgs e)

    {
       string email = string.Empty;
        foreach (GridViewRow gridrows in GridView1.Rows)

        {

            CheckBox chkbox = (CheckBox)gridrows.FindControl("ChkRecords");
    if (chkbox != null & chkbox.Checked)

            {

    int columnIndex = 0;
                foreach (DataControlFieldCell cell in gridrows.Cells)
                {
                    if (cell.ContainingField is BoundField)
                        if (((BoundField)cell.ContainingField).DataField.Equals("UserEmail"))
                            break;
                    columnIndex++; 
                }


                email += gridrows.Cells[columnIndex].Text + ',';
                  }

        }

        Label1.Text = "email:" + email;

    }                           

How to save a bitmap on internal storage

You might be able to use the following for decoding, compressing and saving an image:

     @Override
     public void onClick(View view) {
                onItemSelected1();
                InputStream image_stream = null;
                try {
                    image_stream = getContentResolver().openInputStream(myUri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap image= BitmapFactory.decodeStream(image_stream );
                // path to sd card
                File path=Environment.getExternalStorageDirectory();
                //create a file
                File  dir=new File(path+"/ComDec/");
                dir.mkdirs();
                Date date=new Date();
                File file=new File(dir,date+".jpg");

                OutputStream out=null;
                try{
                    out=new FileOutputStream(file);
                    image.compress(format,size,out);
                    out.flush();
                    out.close();


                    MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");

                    image=null;


                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
            }
        });

Dynamically changing font size of UILabel

Just send the sizeToFit message to the UITextView. It will adjust its own height to just fit its text. It will not change its own width or origin.

[textViewA1 sizeToFit];

Replace one character with another in Bash

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

_x000D_
_x000D_
.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

_x000D_
_x000D_
div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_

(Or JSFiddle)

How to assign from a function which returns more than one value?

How about using assign?

functionReturningTwoValues <- function(a, b) {
  assign(a, 1, pos=1)
  assign(b, 2, pos=1)
}

You can pass the names of the variable you want to be passed by reference.

> functionReturningTwoValues('a', 'b')
> a
[1] 1
> b
[1] 2

If you need to access the existing values, the converse of assign is get.

How to convert LINQ query result to List?

You need to somehow convert each tbcourse object to an instance of course. For instance course could have a constructor that takes a tbcourse. You could then write the query like this:

var qry = from c in obj.tbCourses
          select new course(c);

List<course> lst = qry.ToList();

Way to create multiline comments in Bash?

After reading the other answers here I came up with the below, which IMHO makes it really clear it's a comment. Especially suitable for in-script usage info:

<< ////

Usage:
This script launches a spaceship to the moon. It's doing so by 
leveraging the power of the Fifth Element, AKA Leeloo.
Will only work if you're Bruce Willis or a relative of Milla Jovovich.

////

As a programmer, the sequence of slashes immediately registers in my brain as a comment (even though slashes are normally used for line comments).

Of course, "////" is just a string; the number of slashes in the prefix and the suffix must be equal.

How do I create a list of random numbers without duplicates?

to sample integers without replacement between minval and maxval:

import numpy as np

minval, maxval, n_samples = -50, 50, 10
generator = np.random.default_rng(seed=0)
samples = generator.permutation(np.arange(minval, maxval))[:n_samples]

# or, if minval is 0,
samples = generator.permutation(maxval)[:n_samples]

with jax:

import jax

minval, maxval, n_samples = -50, 50, 10
key = jax.random.PRNGKey(seed=0)
samples = jax.random.shuffle(key, jax.numpy.arange(minval, maxval))[:n_samples]

How do I insert datetime value into a SQLite database?

Use CURRENT_TIMESTAMP when you need it, instead OF NOW() (which is MySQL)

How do I select an element in jQuery by using a variable for the ID?

The shortest way would be:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

Evaluating string "3*(4+2)" yield int 18

I recently needed to do this for a project and I ended up using IronPython to do it. You can declare an instance of the engine, and then pass any valid python expression and get the result. If you're just doing simple math expressions, then it would suffice. My code ended up looking similar to:

IronPython.Hosting.PythonEngine pythonEngine = new IronPython.Hosting.PythonEngine();
string expression = "3*(2+4)";
double result = pythonEngine.EvaluateAs<double>(expression);

You'd probably not want to create the engine for each expression. You also need a reference to IronPython.dll

Excel function to get first word from sentence in other cell

I found this on exceljet.net and works for me:

=LEFT(B4,FIND(" ",B4)-1)

How do I jump to a closing bracket in Visual Studio Code?

For this, I installed an extension called TabOut. Pretty much does what the name suggests.

Linux command line howto accept pairing for bluetooth device without pin

Entering a PIN is actually an outdated method of pairing, now called Legacy Pairing. Secure Simple Pairing Mode is available in Bluetooth v2.1 and later, which comprises most modern Bluetooth devices. SSPMode authentication is handled by the Bluetooth protocol stack and thus works without user interaction.

Here is how one might go about connecting to a device:

# hciconfig hci0 sspmode 1
# hciconfig hci0 sspmode
hci0:   Type: BR/EDR  Bus: USB
BD Address: AA:BB:CC:DD:EE:FF  ACL MTU: 1021:8  SCO MTU: 64:1
Simple Pairing mode: Enabled
# hciconfig hci0 piscan
# sdptool add SP
# hcitool scan
    00:11:22:33:44:55    My_Device
# rfcomm connect /dev/rfcomm0 00:11:22:33:44:55 1 &
Connected /dev/rfcomm0 to 00:11:22:33:44:55 on channel 1
Press CTRL-C for hangup

This would establish a serial connection to the device.