Programs & Examples On #Database

A database is an organized collection of data. It is the collection of schemas, tables, queries, reports, views, and other objects. The data are typically organized to model aspects of reality in a way that supports processes requiring information. Use this tag if you have questions about designing a database. If it is about a particular database management system, (e.g., MySQL), please use that tag instead.

Run PostgreSQL queries from the command line

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

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

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

MySQL dump by query

Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.

mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep  '^INSERT' > 5406.sql

Is it possible to access an SQLite database from JavaScript?

One of the most interesting features in HTML5 is the ability to store data locally and to allow the application to run offline. There are three different APIs that deal with these features and choosing one depends on what exactly you want to do with the data you're planning to store locally:

  1. Web storage: For basic local storage with key/value pairs
  2. Offline storage: Uses a manifest to cache entire files for offline use
  3. Web database: For relational database storage

For more reference see Introducing the HTML5 storage APIs

And how to use

http://cookbooks.adobe.com/post_Store_data_in_the_HTML5_SQLite_database-19115.html

Should each and every table have a primary key?

I am in the role of maintaining application created by offshore development team. Now I am having all kinds of issues in the application because original database schema did not contain PRIMARY KEYS on some tables. So please dont let other people suffer because of your poor design. It is always good idea to have primary keys on tables.

SQL: How to to SUM two values from different tables

For your current structure, you could also try the following:

select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country

I think I prefer a union between the two tables, and a group by on the country name as mentioned above.

But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)

Why do you create a View in a database?

Among other things, it can be used for security. If you have a "customer" table, you might want to give all of your sales people access to the name, address, zipcode, etc. fields, but not credit_card_number. You can create a view that only includes the columns they need access to and then grant them access on the view.

H2 database error: Database may be already in use: "Locked by another process"

You can also delete file of the h2 file database and problem will disappear.

jdbc:h2:~/dbname means that file h2 database with name db name will be created in the user home directory(~/ means user home directory, I hope you work on Linux).

In my local machine its present in: /home/jack/dbname.mv.db I don't know why file has a name dbname.mv.db instead a dbname. May be its a h2 default settings. I remove this file:

rm ~/dbname.mv.db 

OR:

cd ~/ 
rm dbname.mv.db 

Database dbname will be removed with all data. After new data base init all will be ok.

Django CharField vs TextField

In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.

Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.

What is sharding and why is it important?

Sharding is horizontal(row wise) database partitioning as opposed to vertical(column wise) partitioning which is Normalization. It separates very large databases into smaller, faster and more easily managed parts called data shards. It is a mechanism to achieve distributed systems.

Why do we need distributed systems?

  • Increased availablity.
  • Easier expansion.
  • Economics: It costs less to create a network of smaller computers with the power of single large computer.

You can read more here: Advantages of Distributed database

How sharding help achieve distributed system?

You can partition a search index into N partitions and load each index on a separate server. If you query one server, you will get 1/Nth of the results. So to get complete result set, a typical distributed search system use an aggregator that will accumulate results from each server and combine them. An aggregator also distribute query onto each server. This aggregator program is called MapReduce in big data terminology. In other words, Distributed Systems = Sharding + MapReduce (Although there are other things too).

A visual representation below. Distributed System

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

How to select the nth row in a SQL database table?

For SQL Server, a generic way to go by row number is as such:

SET ROWCOUNT @row --@row = the row number you wish to work on.

For Example:

set rowcount 20   --sets row to 20th row

select meat, cheese from dbo.sandwich --select columns from table at 20th row

set rowcount 0   --sets rowcount back to all rows

This will return the 20th row's information. Be sure to put in the rowcount 0 afterward.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Call your hosting company and either have them set up regular log backups or set the recovery model to simple. I'm sure you know what informs the choice, but I'll be explicit anyway. Set the recovery model to full if you need the ability to restore to an arbitrary point in time. Either way the database is misconfigured as is.

How to generate the whole database script in MySQL Workbench?

in mysql workbench server>>>>>>export Data then follow instructions it will generate insert statements for all tables data each table will has .sql file for all its contained data

Set default value of an integer column SQLite

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).

It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).

Here is the code I used:

CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY>       INTEGER    UNIQUE
                                PRIMARY KEY,
<MY_TABLE_SERIAL>    TEXT       DEFAULT (<MY_VALUE>) 
                                NOT NULL
<THE_REST_COLUMNS>
);

Best way to work with dates in Android SQLite

Best way to store datein SQlite DB is to store the current DateTimeMilliseconds. Below is the code snippet to do so_

  1. Get the DateTimeMilliseconds
public static long getTimeMillis(String dateString, String dateFormat) throws ParseException {
    /*Use date format as according to your need! Ex. - yyyy/MM/dd HH:mm:ss */
    String myDate = dateString;//"2017/12/20 18:10:45";
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    return millis;
}
  1. Insert the data in your DB
public void insert(Context mContext, long dateTimeMillis, String msg) {
    //Your DB Helper
    MyDatabaseHelper dbHelper = new MyDatabaseHelper(mContext);
    database = dbHelper.getWritableDatabase();

    ContentValues contentValue = new ContentValues();
    contentValue.put(MyDatabaseHelper.DATE_MILLIS, dateTimeMillis);
    contentValue.put(MyDatabaseHelper.MESSAGE, msg);

    //insert data in DB
    database.insert("your_table_name", null, contentValue);

   //Close the DB connection.
   dbHelper.close(); 

}

Now, your data (date is in currentTimeMilliseconds) is get inserted in DB .

Next step is, when you want to retrieve data from DB you need to convert the respective date time milliseconds in to corresponding date. Below is the sample code snippet to do the same_

  1. Convert date milliseconds in to date string.
public static String getDate(long milliSeconds, String dateFormat)
{
    // Create a DateFormatter object for displaying date in specified format.
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);

    // Create a calendar object that will convert the date and time value in milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    return formatter.format(calendar.getTime());
}
  1. Now, Finally fetch the data and see its working...
public ArrayList<String> fetchData() {

    ArrayList<String> listOfAllDates = new ArrayList<String>();
    String cDate = null;

    MyDatabaseHelper dbHelper = new MyDatabaseHelper("your_app_context");
    database = dbHelper.getWritableDatabase();

    String[] columns = new String[] {MyDatabaseHelper.DATE_MILLIS, MyDatabaseHelper.MESSAGE};
    Cursor cursor = database.query("your_table_name", columns, null, null, null, null, null);

    if (cursor != null) {

        if (cursor.moveToFirst()){
            do{
                //iterate the cursor to get data.
                cDate = getDate(cursor.getLong(cursor.getColumnIndex(MyDatabaseHelper.DATE_MILLIS)), "yyyy/MM/dd HH:mm:ss");

                listOfAllDates.add(cDate);

            }while(cursor.moveToNext());
        }
        cursor.close();

    //Close the DB connection.
    dbHelper.close(); 

    return listOfAllDates;

}

Hope this will help all! :)

PDO get the last ID inserted

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

You mentioned Ubuntu so I'm going to guess you installed the PostgreSQL packages from Ubuntu through apt.

If so, the postgres PostgreSQL user account already exists and is configured to be accessible via peer authentication for unix sockets in pg_hba.conf. You get to it by running commands as the postgres unix user, eg:

sudo -u postgres createuser owning_user
sudo -u postgres createdb -O owning_user dbname

This is all in the Ubuntu PostgreSQL documentation that's the first Google hit for "Ubuntu PostgreSQL" and is covered in numerous Stack Overflow questions.

(You've made this question a lot harder to answer by omitting details like the OS and version you're on, how you installed PostgreSQL, etc.)

how to select first N rows from a table in T-SQL?

Try this.

declare @topval int

set @topval = 5 (customized value)

SELECT TOP(@topval) * from your_database

What's the best strategy for unit-testing database-driven applications?

I'm using the first approach but a bit different that allows to address the problems you mentioned.

Everything that is needed to run tests for DAOs is in source control. It includes schema and scripts to create the DB (docker is very good for this). If the embedded DB can be used - I use it for speed.

The important difference with the other described approaches is that the data that is required for test is not loaded from SQL scripts or XML files. Everything (except some dictionary data that is effectively constant) is created by application using utility functions/classes.

The main purpose is to make data used by test

  1. very close to the test
  2. explicit (using SQL files for data make it very problematic to see what piece of data is used by what test)
  3. isolate tests from the unrelated changes.

It basically means that these utilities allow to declaratively specify only things essential for the test in test itself and omit irrelevant things.

To give some idea of what it means in practice, consider the test for some DAO which works with Comments to Posts written by Authors. In order to test CRUD operations for such DAO some data should be created in the DB. The test would look like:

@Test
public void savedCommentCanBeRead() {
    // Builder is needed to declaratively specify the entity with all attributes relevant
    // for this specific test
    // Missing attributes are generated with reasonable values
    // factory's responsibility is to create entity (and all entities required by it
    //  in our example Author) in the DB
    Post post = factory.create(PostBuilder.post());

    Comment comment = CommentBuilder.comment().forPost(post).build();

    sut.save(comment);

    Comment savedComment = sut.get(comment.getId());

    // this checks fields that are directly stored
    assertThat(saveComment, fieldwiseEqualTo(comment));
    // if there are some fields that are generated during save check them separately
    assertThat(saveComment.getGeneratedField(), equalTo(expectedValue));        
}

This has several advantages over SQL scripts or XML files with test data:

  1. Maintaining the code is much easier (adding a mandatory column for example in some entity that is referenced in many tests, like Author, does not require to change lots of files/records but only a change in builder and/or factory)
  2. The data required by specific test is described in the test itself and not in some other file. This proximity is very important for test comprehensibility.

Rollback vs Commit

I find it more convenient that tests do commit when they are executed. Firstly, some effects (for example DEFERRED CONSTRAINTS) cannot be checked if commit never happens. Secondly, when a test fails the data can be examined in the DB as it is not reverted by the rollback.

Of cause this has a downside that test may produce a broken data and this will lead to the failures in other tests. To deal with this I try to isolate the tests. In the example above every test may create new Author and all other entities are created related to it so collisions are rare. To deal with the remaining invariants that can be potentially broken but cannot be expressed as a DB level constraint I use some programmatic checks for erroneous conditions that may be run after every single test (and they are run in CI but usually switched off locally for performance reasons).

SQL Order By Count

SELECT * FROM table 
group by `Group`
ORDER BY COUNT(Group)

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

Oracle - How to create a materialized view with FAST REFRESH and JOINS

To start with, from the Oracle Database Data Warehousing Guide:

Restrictions on Fast Refresh on Materialized Views with Joins Only

...

  • Rowids of all the tables in the FROM list must appear in the SELECT list of the query.

This means that your statement will need to look something like this:

CREATE MATERIALIZED VIEW MV_Test
  NOLOGGING
  CACHE
  BUILD IMMEDIATE 
  REFRESH FAST ON COMMIT 
  AS
    SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID 
    FROM TPM_PROJECTVERSION V,
         TPM_PROJECT P 
    WHERE P.PROJECTID = V.PROJECTID

Another key aspect to note is that your materialized view logs must be created as with rowid.

Below is a functional test scenario:

CREATE TABLE foo(foo NUMBER, CONSTRAINT foo_pk PRIMARY KEY(foo));

CREATE MATERIALIZED VIEW LOG ON foo WITH ROWID;

CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar));

CREATE MATERIALIZED VIEW LOG ON bar WITH ROWID;

CREATE MATERIALIZED VIEW foo_bar
  NOLOGGING
  CACHE
  BUILD IMMEDIATE
  REFRESH FAST ON COMMIT  AS SELECT foo.foo, 
                                    bar.bar, 
                                    foo.ROWID AS foo_rowid, 
                                    bar.ROWID AS bar_rowid 
                               FROM foo, bar
                              WHERE foo.foo = bar.foo;

Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created?

psql's inline help:

\h ALTER TABLE

Also documented in the postgres docs (an excellent resource, plus easy to read, too).

ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE (columns);

Calculating how many days are between two dates in DB2?

values timestampdiff (16, char( 
    timestamp(current timestamp + 1 year + 2 month - 3 day)- 
    timestamp(current timestamp)))
1
=
422



values timestampdiff (16, char( 
    timestamp('2012-03-08-00.00.00')- 
    timestamp('2011-12-08-00.00.00')))
1
=
90

---------- EDIT BY galador

SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'

EDIT

As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:

SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00 
WHERE CHSTAT = '05';

Query to list number of records in each table in a database

SELECT 
    T.NAME AS 'TABLE NAME',
    P.[ROWS] AS 'NO OF ROWS'
FROM SYS.TABLES T 
INNER JOIN  SYS.PARTITIONS P ON T.OBJECT_ID=P.OBJECT_ID;

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

An unsigned 1 byte number can contain the range [0-255] inclusive. So when you see 255, it is mostly because programmers think in base 10 (get the joke?) :)

Actually, for a while, 255 was the largest size you could give a VARCHAR in MySQL, and there are advantages to using VARCHAR over TEXT with indexing and other issues.

How to remove foreign key constraint in sql server?

ALTER TABLE table
DROP FOREIGN KEY fk_key

EDIT: didn't notice you were using sql-server, my bad

ALTER TABLE table
DROP CONSTRAINT fk_key

How do you check what version of SQL Server for a database using TSQL?

I know this is an older post but I updated the code found in the link (which is dead as of 2013-12-03) mentioned in the answer posted by Matt Rogish:

DECLARE @ver nvarchar(128)
SET @ver = CAST(serverproperty('ProductVersion') AS nvarchar)
SET @ver = SUBSTRING(@ver, 1, CHARINDEX('.', @ver) - 1)

IF ( @ver = '7' )
   SELECT 'SQL Server 7'
ELSE IF ( @ver = '8' )
   SELECT 'SQL Server 2000'
ELSE IF ( @ver = '9' )
   SELECT 'SQL Server 2005'
ELSE IF ( @ver = '10' )
   SELECT 'SQL Server 2008/2008 R2'
ELSE IF ( @ver = '11' )
   SELECT 'SQL Server 2012'
ELSE IF ( @ver = '12' )
   SELECT 'SQL Server 2014'
ELSE IF ( @ver = '13' )
   SELECT 'SQL Server 2016'
ELSE IF ( @ver = '14' )
   SELECT 'SQL Server 2017'
ELSE
   SELECT 'Unsupported SQL Server Version'

SQL Query for Student mark functionality

I would have said:

select s.stname, s2.subname, highmarks.mark
from students s
join marks m on s.stid = m.stid
join Subject s2 on m.subid = s2.subid
join (select subid, max(mark) as mark
  from marks group by subid) as highmarks
    on highmarks.subid = m.subid and highmarks.mark = m.mark
order by subname, stname;

SQLFiddle here: http://sqlfiddle.com/#!2/5ef84/3

This is a:

  • select on the students table to get the possible students
  • a join to the marks table to match up students to marks,
  • a join to the subjects table to resolve subject ids into names.
  • a join to a derived table of the maximum marks in each subject.

Only the students that get maximum marks will meet all three join conditions. This lists all students who got that maximum mark, so if there are ties, both get listed.

How to backup Sql Database Programmatically in C#

 private void BackupManager_Load(object sender, EventArgs e)
        {
            txtFileName.Text = "DB_Backup_" + DateTime.Now.ToString("dd-MMM-yy");
        }

        private void btnDBBackup_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtFileName.Text.Trim()))
            {
                BackUp();
            }
            else
            {
                MessageBox.Show("Please Enter Backup File Name", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtFileName.Focus();
                return;
            }
        }

        private void BackUp()
        {
            try
            {

                progressBar1.Value = 0;

                for (progressBar1.Value = 0; progressBar1.Value < 100; progressBar1.Value++)
                {

                }

                pl.DbName = "Inventry";
                pl.Path = @"D:/" + txtFileName.Text.Trim() + ".bak";

                for (progressBar1.Value = 100; progressBar1.Value < 200; progressBar1.Value++)
                {

                }

                bl.DbBackUp(pl);
                for (progressBar1.Value = 200; progressBar1.Value < 300; progressBar1.Value++)
                {

                }

                for (progressBar1.Value = 300; progressBar1.Value < 400; progressBar1.Value++)
                {

                }

                for (progressBar1.Value = 400; progressBar1.Value < progressBar1.Maximum; progressBar1.Value++)
                {

                }
                if (progressBar1.Value == progressBar1.Maximum)
                {
                    MessageBox.Show("Backup Saved Successfully...!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                progressBar1.Value = 0;
            }
        }

1052: Column 'id' in field list is ambiguous

The simplest solution is a join with USING instead of ON. That way, the database "knows" that both id columns are actually the same, and won't nitpick on that:

SELECT id, name, section
  FROM tbl_names
  JOIN tbl_section USING (id)

If id is the only common column name in tbl_names and tbl_section, you can even use a NATURAL JOIN:

SELECT id, name, section
  FROM tbl_names
  NATURAL JOIN tbl_section

See also: https://dev.mysql.com/doc/refman/5.7/en/join.html

How do I alter the position of a column in a PostgreSQL database table?

One, albeit a clumsy option to rearrange the columns when the column order must absolutely be changed, and foreign keys are in use, is to first dump the entire database with data, then dump just the schema (pg_dump -s databasename > databasename_schema.sql). Next edit the schema file to rearrange the columns as you would like, then recreate the database from the schema, and finally restore the data into the newly created database.

Simple check for SELECT query empty result

You can do it in a number of ways.

IF EXISTS(select * from ....)
begin
 -- select * from .... 
end
else
 -- do something 

Or you can use IF NOT EXISTS , @@ROW_COUNT like

select * from ....
IF(@@ROW_COUNT>0)
begin
-- do something
end

Python: Number of rows affected by cursor.execute("SELECT ...)

Try using fetchone:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
result=cursor.fetchone()

result will hold a tuple with one element, the value of COUNT(*). So to find the number of rows:

number_of_rows=result[0]

Or, if you'd rather do it in one fell swoop:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
(number_of_rows,)=cursor.fetchone()

PS. It's also good practice to use parametrized arguments whenever possible, because it can automatically quote arguments for you when needed, and protect against sql injection.

The correct syntax for parametrized arguments depends on your python/database adapter (e.g. mysqldb, psycopg2 or sqlite3). It would look something like

cursor.execute("SELECT COUNT(*) from result where server_state= %s AND name LIKE %s",[2,digest+"_"+charset+"_%"])
(number_of_rows,)=cursor.fetchone()

What is the best place for storing uploaded images, SQL database or disk file system?

We have had clients insist on option B (database storage) a few times on a few different backends, and we always ended up going back to option A (filesystem storage) eventually.

Large BLOBs like that just have not been handled well enough even by SQL Server 2005, which is the latest one we tried it on.

Specifically, we saw serious bloat and I think maybe locking problems.

One other note: if you are using NTFS based storage (windows server, etc) you might consider finding a way around putting thousands and thousands of files in one directory. I am not sure why, but sometimes the file system does not cope well with that situation. If anyone knows more about this I would love to hear it.

But I always try to use subdirectories to break things up a bit. Creation date often works well for this:

Images/2008/12/17/.jpg

...This provides a decent level of separation, and also helps a bit during debugging. Explorer and FTP clients alike can choke a bit when there are truly huge directories.

EDIT: Just a quick note for 2017, in more recent versions of SQL Server, there are new options for handling lots of BLOBs that are supposed to avoid the drawbacks I discussed.

EDIT: Quick note for 2020, Blob Storage in AWS/Azure/etc has also been an option for years now. This is a great fit for many web-based projects since it's cheap and it can often simplify certain issues around deployment, scaling to multiple servers, debugging other environments when necessary, etc.

Cast int to varchar

You're getting that because VARCHAR is not a valid type to cast into. According to the MySQL docs (http://dev.mysql.com/doc/refman/5.5/en/cast-functions.html#function_cast) you can only cast to:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED
  • [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

I think your best-bet is to use CHAR.

Create SQLite database in android

Why not refer to the documentation or the sample code shipping with the SDK? There's code in the samples on how to create/update/fill/read databases using the helper class described in the document I linked.

How to fix a collation conflict in a SQL Server query?

if the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!

How to find largest objects in a SQL Server database?

In SQL Server 2008, you can also just run the standard report Disk Usage by Top Tables. This can be found by right clicking the DB, selecting Reports->Standard Reports and selecting the report you want.

What is an ORM, how does it work, and how should I use one?

Like all acronyms it's ambiguous, but I assume they mean object-relational mapper -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as the Vietnam of CS;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)

MySQL: Check if the user exists and drop it

in terminal do:

sudo mysql -u root -p

enter the password.

select user from mysql.user;

now delete the user 'the_username'

DROP USER the_unername;

replace 'the_username' with the user that you want to delete.

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

How SID is different from Service name in Oracle tnsnames.ora

I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like:

mySID, mySID.whereever.com =
(DESCRIPTION =
  (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))
  )
  (CONNECT_DATA =
    (SERVICE_NAME = mySID.whereever.com)
    (SID = mySID)
    (SERVER = DEDICATED)
  )
)

I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking.

Generate insert script for selected records?

If possible use Visual Studio. The Microsoft SQL Server Data Tools (SSDT) bring a built in functionality for this since the March 2014 release:

  1. Open Visual Studio
  2. Open "View" ? "SQL Server Object Explorer"
  3. Add a connection to your Server
  4. Expand the relevant database
  5. Expand the "Tables" folder
  6. Right click on relevant table
  7. Select "View Data" from context menu
  8. In the new window, viewing the data use the "Sort and filter dataset" functionality in the tool bar to apply your filter. Note that this functionality is limited and you can't write explicit SQL queries.
  9. After you have applied your filter and see only the data you want, click on "Script" or "Script to file" in the tool bar
  10. Voilà - Here you have your insert script for your filtered data

Note: Be careful, the "View Data" window is just like SSMS "Edit Top 200 Rows"- you can edit data right away

(Tested with Visual Studio 2015 with Microsoft SQL Server Data Tools (SSDT) Version 14.0.60812.0 and Microsoft SQL Server 2012)

Do conditional INSERT with SQL?

I dont know about SmallSQL, but this works for MSSQL:

IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
    UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
    INSERT INTO Table1 VALUES (...)

Based on the where-condition, this updates the row if it exists, else it will insert a new one.

I hope that's what you were looking for.

How to insert special characters into a database?

You are propably pasting them directly into a query. Istead you should "escape" them, using appriopriate function - mysql_real_escape_string, mysqli_real_escape_string or PDO::quote depending on extension you are using.

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Drop all tables command

I don't think you can drop all tables in one hit but you can do the following to get the commands:

select 'drop table ' || name || ';' from sqlite_master
    where type = 'table';

The output of this is a script that will drop the tables for you. For indexes, just replace table with index.

You can use other clauses in the where section to limit which tables or indexes are selected (such as "and name glob 'pax_*'" for those starting with "pax_").

You could combine the creation of this script with the running of it in a simple bash (or cmd.exe) script so there's only one command to run.

If you don't care about any of the information in the DB, I think you can just delete the file it's stored in off the hard disk - that's probably faster. I've never tested this but I can't see why it wouldn't work.

Maximum concurrent connections to MySQL

I can assure you that raw speed ultimately lies in the non-standard use of Indexes for blazing speed using large tables.

How to replace a string in a SQL Server Table Column

UPDATE CustomReports_Ta
SET vchFilter = REPLACE(CAST(vchFilter AS nvarchar(max)), '\\Ingl-report\Templates', 'C:\Customer_Templates')
where CAST(vchFilter AS nvarchar(max)) LIKE '%\\Ingl-report\Templates%'

Without the CAST function I got an error

Argument data type ntext is invalid for argument 1 of replace function.

How to insert Records in Database using C# language?

sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";

(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.

get data from mysql database to use in javascript

You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

MySQL Query to select data from last week?

You can make your calculation in php and then add it to your query:

$date = date('Y-m-d H:i:s',time()-(7*86400)); // 7 days ago

$sql = "SELECT * FROM table WHERE date <='$date' ";

now this will give the date for a week ago

SQL query to select distinct row with minimum value

This is another way of doing the same thing, which would allow you to do interesting things like select the top 5 winning games, etc.

 SELECT *
 FROM
 (
     SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Point) as RowNum, *
     FROM Table
 ) X 
 WHERE RowNum = 1

You can now correctly get the actual row that was identified as the one with the lowest score and you can modify the ordering function to use multiple criteria, such as "Show me the earliest game which had the smallest score", etc.

Create mysql table directly from CSV file using the CSV Storage engine?

If someone is looking for a PHP solution see "PHP_MySQL_wrapper":

$db = new MySQL_wrapper(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect(); 

// this sample gets column names from first row of file
//$db->createTableFromCSV('test_files/countrylist.csv', 'csv_to_table_test');

// this sample generates column names 
$db->createTableFromCSV('test_files/countrylist1.csv', 'csv_to_table_test_no_column_names', ',', '"', '\\', 0, array(), 'generate', '\r\n');

/** Create table from CSV file and imports CSV data to Table with possibility to update rows while import.
 * @param   string      $file           - CSV File path
 * @param   string      $table          - Table name
 * @param   string      $delimiter      - COLUMNS TERMINATED BY (Default: ',')
 * @param   string      $enclosure      - OPTIONALLY ENCLOSED BY (Default: '"')
 * @param   string      $escape         - ESCAPED BY (Default: '\')
 * @param   integer     $ignore         - Number of ignored rows (Default: 1)
 * @param   array       $update         - If row fields needed to be updated eg date format or increment (SQL format only @FIELD is variable with content of that field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
 * @param   string      $getColumnsFrom - Get Columns Names from (file or generate) - this is important if there is update while inserting (Default: file)
 * @param   string      $newLine        - New line delimiter (Default: \n)
 * @return  number of inserted rows or false
 */
// function createTableFromCSV($file, $table, $delimiter = ',', $enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = '\r\n')

$db->close();

Sqlite or MySql? How to decide?

The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.

What's the best practice for primary keys in tables?

Just an extra comment on something that is often overlooked. Sometimes not using a surrogate key has benefits in the child tables. Let's say we have a design that allows you to run multiple companies within the one database (maybe it's a hosted solution, or whatever).

Let's say we have these tables and columns:

Company:
  CompanyId   (primary key)

CostCenter:
  CompanyId   (primary key, foreign key to Company)
  CostCentre  (primary key)

CostElement
  CompanyId   (primary key, foreign key to Company)
  CostElement (primary key)

Invoice:
  InvoiceId    (primary key)
  CompanyId    (primary key, in foreign key to CostCentre, in foreign key to CostElement)
  CostCentre   (in foreign key to CostCentre)
  CostElement  (in foreign key to CostElement)

In case that last bit doesn't make sense, Invoice.CompanyId is part of two foreign keys, one to the CostCentre table and one to the CostElement table. The primary key is (InvoiceId, CompanyId).

In this model, it's not possible to screw-up and reference a CostElement from one company and a CostCentre from another company. If a surrogate key was used on the CostElement and CostCentre tables, it would be.

The fewer chances to screw up, the better.

How can I create database tables from XSD files?

XML Schemas describe hierarchial data models and may not map well to a relational data model. Mapping XSD's to database tables is very similar mapping objects to database tables, in fact you could use a framework like Castor that does both, it allows you to take a XML schema and generate classes, database tables, and data access code. I suppose there are now many tools that do the same thing, but there will be a learning curve and the default mappings will most like not be what you want, so you have to spend time customizing whatever tool you use.

XSLT might be the fastest way to generate exactly the code that you want. If it is a small schema hardcoding it might be faster than evaluating and learing a bunch of new technologies.

How to configure postgresql for the first time?

EDIT: Warning: Please, read the answer posted by Evan Carroll. It seems that this solution is not safe and not recommended.

This worked for me in the standard Ubuntu 14.04 64 bits installation.

I followed the instructions, with small modifications, that I found in http://suite.opengeo.org/4.1/dataadmin/pgGettingStarted/firstconnect.html

  1. Install postgreSQL (if not already in your machine):

sudo apt-get install postgresql

  1. Run psql using the postgres user

sudo –u postgres psql postgres

  1. Set a new password for the postgres user:

\password postgres

  1. Exit psql

\q

  1. Edit /etc/postgresql/9.3/main/pg_hba.conf and change:

#Database administrative login by Unix domain socket local all postgres peer

To:

#Database administrative login by Unix domain socket local all postgres md5

  1. Restart postgreSQL:

sudo service postgresql restart

  1. Create a new database

sudo –u postgres createdb mytestdb

  1. Run psql with the postgres user again:

psql –U postgres –W

  1. List the existing databases (your new database should be there now):

\l

How big can a MySQL database get before performance starts to degrade

I once was called upon to look at a mysql that had "stopped working". I discovered that the DB files were residing on a Network Appliance filer mounted with NFS2 and with a maximum file size of 2GB. And sure enough, the table that had stopped accepting transactions was exactly 2GB on disk. But with regards to the performance curve I'm told that it was working like a champ right up until it didn't work at all! This experience always serves for me as a nice reminder that there're always dimensions above and below the one you naturally suspect.

How to create user for a db in postgresql?

Create the user with a password :

http://www.postgresql.org/docs/current/static/sql-createuser.html

CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | CREATEUSER | NOCREATEUSER
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid

Then grant the user rights on a specific database :

http://www.postgresql.org/docs/current/static/sql-grant.html

Example :

grant all privileges on database db_name to someuser;

What is the syntax meaning of RAISERROR()

The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).

The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.

How can I add comments in MySQL?

Several ways:

# Comment
-- Comment
/* Comment */

Remember to put the space after --.

See the documentation.

How to display table data more clearly in oracle sqlplus

Ahhh, the stupid linesize ... Here is what I do in my profile.sql - works only on unixes:

echo SET LINES $(tput cols) > $HOME/.login_tmp.sql
@$HOME/.login_tmp.sql

if you find an equivalent for tput on Windows, it might work there as well

How to load data from a text file in a PostgreSQL database?

The slightly modified version of COPY below worked better for me, where I specify the CSV format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT.

COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );

Unable to connect to SQL Server instance remotely

In addition to configuring the SQL Server Browser service in Services.msc to Automatic, and starting the service, I had to enable TCP/IP in: SQL Server Configuration Manager | SQL Server Network Configuration | Protocols for [INSTANCE NAME] | TCP/IP

enter image description here

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

Difference between a theta join, equijoin and natural join

Natural Join: Natural join can be possible when there is at least one common attribute in two relations.

Theta Join: Theta join can be possible when two act on particular condition.

Equi Join: Equi can be possible when two act on equity condition. It is one type of theta join.

Store images in a MongoDB database

http://blog.mongodb.org/post/183689081/storing-large-objects-and-files-in-mongodb

There is a Mongoose plugin available on NPM called mongoose-file. It lets you add a file field to a Mongoose Schema for file upload. I have never used it but it might prove useful. If the images are very small you could Base64 encode them and save the string to the database.

Storing some small (under 1MB) files with MongoDB in NodeJS WITHOUT GridFS

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

When to use MyISAM and InnoDB?

Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.

I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.

EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/

OperationalError: database is locked

A very unusual scenario, which happened to me.

There was infinite recursion, which kept creating the objects.

More specifically, using DRF, I was overriding create method in a view, and I did

def create(self, request, *args, **kwargs):
    ....
    ....

    return self.create(request, *args, **kwargs)

MyISAM versus InnoDB

To add to the wide selection of responses here covering the mechanical differences between the two engines, I present an empirical speed comparison study.

In terms of pure speed, it is not always the case that MyISAM is faster than InnoDB but in my experience it tends to be faster for PURE READ working environments by a factor of about 2.0-2.5 times. Clearly this isn't appropriate for all environments - as others have written, MyISAM lacks such things as transactions and foreign keys.

I've done a bit of benchmarking below - I've used python for looping and the timeit library for timing comparisons. For interest I've also included the memory engine, this gives the best performance across the board although it is only suitable for smaller tables (you continually encounter The table 'tbl' is full when you exceed the MySQL memory limit). The four types of select I look at are:

  1. vanilla SELECTs
  2. counts
  3. conditional SELECTs
  4. indexed and non-indexed sub-selects

Firstly, I created three tables using the following SQL

CREATE TABLE
    data_interrogation.test_table_myisam
    (
        index_col BIGINT NOT NULL AUTO_INCREMENT,
        value1 DOUBLE,
        value2 DOUBLE,
        value3 DOUBLE,
        value4 DOUBLE,
        PRIMARY KEY (index_col)
    )
    ENGINE=MyISAM DEFAULT CHARSET=utf8

with 'MyISAM' substituted for 'InnoDB' and 'memory' in the second and third tables.

 

1) Vanilla selects

Query: SELECT * FROM tbl WHERE index_col = xx

Result: draw

Comparison of vanilla selects by different database engines

The speed of these is all broadly the same, and as expected is linear in the number of columns to be selected. InnoDB seems slightly faster than MyISAM but this is really marginal.

Code:

import timeit
import MySQLdb
import MySQLdb.cursors
import random
from random import randint

db = MySQLdb.connect(host="...", user="...", passwd="...", db="...", cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()

lengthOfTable = 100000

# Fill up the tables with random data
for x in xrange(lengthOfTable):
    rand1 = random.random()
    rand2 = random.random()
    rand3 = random.random()
    rand4 = random.random()

    insertString = "INSERT INTO test_table_innodb (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"
    insertString2 = "INSERT INTO test_table_myisam (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"
    insertString3 = "INSERT INTO test_table_memory (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"

    cur.execute(insertString)
    cur.execute(insertString2)
    cur.execute(insertString3)

db.commit()

# Define a function to pull a certain number of records from these tables
def selectRandomRecords(testTable,numberOfRecords):

    for x in xrange(numberOfRecords):
        rand1 = randint(0,lengthOfTable)

        selectString = "SELECT * FROM " + testTable + " WHERE index_col = " + str(rand1)
        cur.execute(selectString)

setupString = "from __main__ import selectRandomRecords"

# Test time taken using timeit
myisam_times = []
innodb_times = []
memory_times = []

for theLength in [3,10,30,100,300,1000,3000,10000]:

    innodb_times.append( timeit.timeit('selectRandomRecords("test_table_innodb",' + str(theLength) + ')', number=100, setup=setupString) )
    myisam_times.append( timeit.timeit('selectRandomRecords("test_table_myisam",' + str(theLength) + ')', number=100, setup=setupString) )
    memory_times.append( timeit.timeit('selectRandomRecords("test_table_memory",' + str(theLength) + ')', number=100, setup=setupString) )

 

2) Counts

Query: SELECT count(*) FROM tbl

Result: MyISAM wins

Comparison of counts by different database engines

This one demonstrates a big difference between MyISAM and InnoDB - MyISAM (and memory) keeps track of the number of records in the table, so this transaction is fast and O(1). The amount of time required for InnoDB to count increases super-linearly with table size in the range I investigated. I suspect many of the speed-ups from MyISAM queries that are observed in practice are due to similar effects.

Code:

myisam_times = []
innodb_times = []
memory_times = []

# Define a function to count the records
def countRecords(testTable):

    selectString = "SELECT count(*) FROM " + testTable
    cur.execute(selectString)

setupString = "from __main__ import countRecords"

# Truncate the tables and re-fill with a set amount of data
for theLength in [3,10,30,100,300,1000,3000,10000,30000,100000]:

    truncateString = "TRUNCATE test_table_innodb"
    truncateString2 = "TRUNCATE test_table_myisam"
    truncateString3 = "TRUNCATE test_table_memory"

    cur.execute(truncateString)
    cur.execute(truncateString2)
    cur.execute(truncateString3)

    for x in xrange(theLength):
        rand1 = random.random()
        rand2 = random.random()
        rand3 = random.random()
        rand4 = random.random()

        insertString = "INSERT INTO test_table_innodb (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"
        insertString2 = "INSERT INTO test_table_myisam (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"
        insertString3 = "INSERT INTO test_table_memory (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"

        cur.execute(insertString)
        cur.execute(insertString2)
        cur.execute(insertString3)

    db.commit()

    # Count and time the query
    innodb_times.append( timeit.timeit('countRecords("test_table_innodb")', number=100, setup=setupString) )
    myisam_times.append( timeit.timeit('countRecords("test_table_myisam")', number=100, setup=setupString) )
    memory_times.append( timeit.timeit('countRecords("test_table_memory")', number=100, setup=setupString) )

 

3) Conditional selects

Query: SELECT * FROM tbl WHERE value1<0.5 AND value2<0.5 AND value3<0.5 AND value4<0.5

Result: MyISAM wins

Comparison of conditional selects by different database engines

Here, MyISAM and memory perform approximately the same, and beat InnoDB by about 50% for larger tables. This is the sort of query for which the benefits of MyISAM seem to be maximised.

Code:

myisam_times = []
innodb_times = []
memory_times = []

# Define a function to perform conditional selects
def conditionalSelect(testTable):
    selectString = "SELECT * FROM " + testTable + " WHERE value1 < 0.5 AND value2 < 0.5 AND value3 < 0.5 AND value4 < 0.5"
    cur.execute(selectString)

setupString = "from __main__ import conditionalSelect"

# Truncate the tables and re-fill with a set amount of data
for theLength in [3,10,30,100,300,1000,3000,10000,30000,100000]:

    truncateString = "TRUNCATE test_table_innodb"
    truncateString2 = "TRUNCATE test_table_myisam"
    truncateString3 = "TRUNCATE test_table_memory"

    cur.execute(truncateString)
    cur.execute(truncateString2)
    cur.execute(truncateString3)

    for x in xrange(theLength):
        rand1 = random.random()
        rand2 = random.random()
        rand3 = random.random()
        rand4 = random.random()

        insertString = "INSERT INTO test_table_innodb (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"
        insertString2 = "INSERT INTO test_table_myisam (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"
        insertString3 = "INSERT INTO test_table_memory (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"

        cur.execute(insertString)
        cur.execute(insertString2)
        cur.execute(insertString3)

    db.commit()

    # Count and time the query
    innodb_times.append( timeit.timeit('conditionalSelect("test_table_innodb")', number=100, setup=setupString) )
    myisam_times.append( timeit.timeit('conditionalSelect("test_table_myisam")', number=100, setup=setupString) )
    memory_times.append( timeit.timeit('conditionalSelect("test_table_memory")', number=100, setup=setupString) )

 

4) Sub-selects

Result: InnoDB wins

For this query, I created an additional set of tables for the sub-select. Each is simply two columns of BIGINTs, one with a primary key index and one without any index. Due to the large table size, I didn't test the memory engine. The SQL table creation command was

CREATE TABLE
    subselect_myisam
    (
        index_col bigint NOT NULL,
        non_index_col bigint,
        PRIMARY KEY (index_col)
    )
    ENGINE=MyISAM DEFAULT CHARSET=utf8;

where once again, 'MyISAM' is substituted for 'InnoDB' in the second table.

In this query, I leave the size of the selection table at 1000000 and instead vary the size of the sub-selected columns.

Comparison of sub-selects by different database engines

Here the InnoDB wins easily. After we get to a reasonable size table both engines scale linearly with the size of the sub-select. The index speeds up the MyISAM command but interestingly has little effect on the InnoDB speed. subSelect.png

Code:

myisam_times = []
innodb_times = []
myisam_times_2 = []
innodb_times_2 = []

def subSelectRecordsIndexed(testTable,testSubSelect):
    selectString = "SELECT * FROM " + testTable + " WHERE index_col in ( SELECT index_col FROM " + testSubSelect + " )"
    cur.execute(selectString)

setupString = "from __main__ import subSelectRecordsIndexed"

def subSelectRecordsNotIndexed(testTable,testSubSelect):
    selectString = "SELECT * FROM " + testTable + " WHERE index_col in ( SELECT non_index_col FROM " + testSubSelect + " )"
    cur.execute(selectString)

setupString2 = "from __main__ import subSelectRecordsNotIndexed"

# Truncate the old tables, and re-fill with 1000000 records
truncateString = "TRUNCATE test_table_innodb"
truncateString2 = "TRUNCATE test_table_myisam"

cur.execute(truncateString)
cur.execute(truncateString2)

lengthOfTable = 1000000

# Fill up the tables with random data
for x in xrange(lengthOfTable):
    rand1 = random.random()
    rand2 = random.random()
    rand3 = random.random()
    rand4 = random.random()

    insertString = "INSERT INTO test_table_innodb (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"
    insertString2 = "INSERT INTO test_table_myisam (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"

    cur.execute(insertString)
    cur.execute(insertString2)

for theLength in [3,10,30,100,300,1000,3000,10000,30000,100000]:

    truncateString = "TRUNCATE subselect_innodb"
    truncateString2 = "TRUNCATE subselect_myisam"

    cur.execute(truncateString)
    cur.execute(truncateString2)

    # For each length, empty the table and re-fill it with random data
    rand_sample = sorted(random.sample(xrange(lengthOfTable), theLength))
    rand_sample_2 = random.sample(xrange(lengthOfTable), theLength)

    for (the_value_1,the_value_2) in zip(rand_sample,rand_sample_2):
        insertString = "INSERT INTO subselect_innodb (index_col,non_index_col) VALUES (" + str(the_value_1) + "," + str(the_value_2) + ")"
        insertString2 = "INSERT INTO subselect_myisam (index_col,non_index_col) VALUES (" + str(the_value_1) + "," + str(the_value_2) + ")"

        cur.execute(insertString)
        cur.execute(insertString2)

    db.commit()

    # Finally, time the queries
    innodb_times.append( timeit.timeit('subSelectRecordsIndexed("test_table_innodb","subselect_innodb")', number=100, setup=setupString) )
    myisam_times.append( timeit.timeit('subSelectRecordsIndexed("test_table_myisam","subselect_myisam")', number=100, setup=setupString) )
        
    innodb_times_2.append( timeit.timeit('subSelectRecordsNotIndexed("test_table_innodb","subselect_innodb")', number=100, setup=setupString2) )
    myisam_times_2.append( timeit.timeit('subSelectRecordsNotIndexed("test_table_myisam","subselect_myisam")', number=100, setup=setupString2) )

I think the take-home message of all of this is that if you are really concerned about speed, you need to benchmark the queries that you're doing rather than make any assumptions about which engine will be more suitable.

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

From the documentation , the function mysqli_real_escape_string() has two parameters.

string mysqli_real_escape_string ( mysqli $link , string $escapestr ).

The first one is a link for a mysqli instance (database connection object), the second one is the string to escape. So your code should be like :

$username = mysqli_real_escape_string($yourconnectionobject,$_POST['username']);

What are the performance characteristics of sqlite with very large database files?

I've experienced problems with large sqlite files when using the vacuum command.

I haven't tried the auto_vacuum feature yet. If you expect to be updating and deleting data often then this is worth looking at.

How to find the mysql data directory from command line in windows

Check if the Data directory is in "C:\ProgramData\MySQL\MySQL Server 5.7\Data". This is where it is on my computer. Someone might find this helpful.

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

Here was my solution:

  • press Ctrl + Alt + Del
  • Task Manager
  • Select the Services Tab
  • Under name, right click on "MySql" and select Start

phpMyAdmin - Error > Incorrect format parameter?

Note: If you're using MAMP you MUST edit the file using the built-in editor.

Select PHP in the languages section (LH Menu Column) Next, in the main panel next to the default version drop-down click the small arrow pointing to the right. This will launch the php.ini file using the MAMP text editor. Any changes you make to this file will persist after you restart the servers.

Editing the file through Application->MAMP->bin->php->{choosen the version}->php.ini would not work. Since the application overwrites any changes you make.

Needless to say: "Here be dragons!" so please cut and paste a copy of the original and store it somewhere safe in case of disaster.enter image description here

Show MySQL host via SQL Command

I think you try to get the remote host of the conneting user...

You can get a String like 'myuser@localhost' from the command:

SELECT USER()

You can split this result on the '@' sign, to get the parts:

-- delivers the "remote_host" e.g. "localhost" 
SELECT SUBSTRING_INDEX(USER(), '@', -1) 

-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)

if you are conneting via ip address you will get the ipadress instead of the hostname.

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

You have to run the create_tables.sql inside the examples/ folder on phpMyAdmin to create the tables needed for the advanced features. That or disable those features by commenting them on the config file.

What is the difference between a schema and a table and a database?

schema : database : table :: floor plan : house : room

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

For data import scripts, to replace "IF NOT EXISTS", in a way, there's a slightly awkward formulation that nevertheless works:

DO
$do$
BEGIN
PERFORM id
FROM whatever_table;

IF NOT FOUND THEN
-- INSERT stuff
END IF;
END
$do$;

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

For windows Go inside MongoDB\Server\4.0\bin folder and open mongod.cfg file in any text editor. Then locate the line that specifies the dbPath param. The line looks something similar

dbPath: D:\Program Files\MongoDB\Server\4.0\data

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

View's SELECT contains a subquery in the FROM clause

As per documentation:

MySQL Docs

  • The SELECT statement cannot contain a subquery in the FROM clause.

Your workaround would be to create a view for each of your subqueries.

Then access those views from within your view view_credit_status

There is already an object named in the database

Note: not recommended solution. but quick fix in some cases.

For me, dbo._MigrationHistory in production database missed migration records during publish process, but development database had all migration records.

If you are sure that production db has same-and-newest schema compared to dev db, copying all migration records to production db could resolve the issue.

You can do with VisualStudio solely.

  1. Open 'SQL Server Object Explorer' panel > right-click dbo._MigrationHistory table in source(in my case dev db) database > Click "Data Comparison..." menu.
  2. Then, Data Comparison wizard poped up, select target database(in my case production db) and click Next.
  3. A few seconds later, it will show some records only in source database. just click 'Update Target' button.
  4. In browser, hit refresh button and see the error message gone.

Note that, again, it is not recommended in complex and serious project. Use this only you have problem during ASP.Net or EntityFramework learning.

How do I quickly rename a MySQL database (change schema name)?

UPDATE `db`SET Db = 'new_db_name' where Db = 'old_db_name';

What is the default Precision and Scale for a Number in Oracle?

I expand on spectra‘s answer so people don’t have to try it for themselves.

This was done on Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production.

CREATE TABLE CUSTOMERS
(
  CUSTOMER_ID NUMBER NOT NULL,
  FOO FLOAT NOT NULL,
  JOIN_DATE DATE NOT NULL,
  CUSTOMER_STATUS VARCHAR2(8) NOT NULL,
  CUSTOMER_NAME VARCHAR2(20) NOT NULL,
  CREDITRATING VARCHAR2(10)
);

select column_name, data_type, nullable, data_length, data_precision, data_scale
from user_tab_columns where table_name ='CUSTOMERS'; 

Which yields

COLUMN_NAME      DATA_TYPE  NULLABLE DATA_LENGTH DATA_PRECISION DATA_SCALE
CUSTOMER_ID      NUMBER     N        22        
FOO              FLOAT      N        22          126    
JOIN_DATE        DATE       N        7        
CUSTOMER_STATUS  VARCHAR2   N        8        
CUSTOMER_NAME    VARCHAR2   N        20        
CREDITRATING     VARCHAR2   Y        10    

Best design for a changelog / auditing database table?

In general custom audit (creating various tables) is a bad option. Database/table triggers can be disabled to skip some log activities. Custom audit tables can be tampered. Exceptions can take place that will bring down application. Not to mentions difficulties designing a robust solution. So far I see a very simple cases in this discussion. You need a complete separation from current database and from any privileged users(DBA, Developers). Every mainstream RDBMSs provide audit facilities that even DBA not able to disable, tamper in secrecy. Therefore, provided audit capability by RDBMS vendor must be the first option. Other option would be 3rd party transaction log reader or custom log reader that pushes decomposed information into messaging system that ends up in some forms of Audit Data Warehouse or real time event handler. In summary: Solution Architect/"Hands on Data Architect" needs to involve in destining such a system based on requirements. It is usually too serious stuff just to hand over to a developers for solution.

SQL Query Where Date = Today Minus 7 Days

You can subtract 7 from the current date with this:

WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()

What are the differences between the BLOB and TEXT datatypes in MySQL?

A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field

L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.

Reference: http://dev.mysql.com/doc/refman/5.0/en/blob.html

SQL Server: Importing database from .mdf?

Open SQL Management Studio Express and log in to the server to which you want to attach the database. In the 'Object Explorer' window, right-click on the 'Databases' folder and select 'Attach...' The 'Attach Databases' window will open; inside that window click 'Add...' and then navigate to your .MDF file and click 'OK'. Click 'OK' once more to finish attaching the database and you are done. The database should be available for use. best regards :)

Know relationships between all the tables of database in SQL Server

Microsoft Visio is probably the best I've came across, although as far as I know it won't automatically generate based on your relationships.

EDIT: try this in Visio, could give you what you need http://office.microsoft.com/en-us/visio-help/reverse-engineering-an-existing-database-HA001182257.aspx

What does character set and collation mean exactly?

A character set is a subset of all written glyphs. A character encoding specifies how those characters are mapped to numeric values. Some character encodings, like UTF-8 and UTF-16, can encode any character in the Universal Character Set. Others, like US-ASCII or ISO-8859-1 can only encode a small subset, since they use 7 and 8 bits per character, respectively. Because many standards specify both a character set and a character encoding, the term "character set" is often substituted freely for "character encoding".

A collation comprises rules that specify how characters can be compared for sorting. Collations rules can be locale-specific: the proper order of two characters varies from language to language.

Choosing a character set and collation comes down to whether your application is internationalized or not. If not, what locale are you targeting?

In order to choose what character set you want to support, you have to consider your application. If you are storing user-supplied input, it might be hard to foresee all the locales in which your software will eventually be used. To support them all, it might be best to support the UCS (Unicode) from the start. However, there is a cost to this; many western European characters will now require two bytes of storage per character instead of one.

Choosing the right collation can help performance if your database uses the collation to create an index, and later uses that index to provide sorted results. However, since collation rules are often locale-specific, that index will be worthless if you need to sort results according to the rules of another locale.

Insert data into hive table

If table is without partition then code will be,

Insert into table table_name select col_a,col_b,col_c from another_table(source table)

--here any condition can be applied such as limit, group by, order by etc...

If table is with partitions then code will be,

set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;

insert into table table_name partition(partition_col1, paritition_col2) select col_a,col_b,col_c,partition_col1,partition_col2 from another_table(source table)

--here any condition can be applied such as limit, group by, order by etc...

A beginner's guide to SQL database design

I started with this book: Relational Database Design Clearly Explained (The Morgan Kaufmann Series in Data Management Systems) (Paperback) by Jan L. Harrington and found it very clear and helpful

and as you get up to speed this one was good too Database Systems: A Practical Approach to Design, Implementation and Management (International Computer Science Series) (Paperback)

I think SQL and database design are different (but complementary) skills.

How to generate sample XML documents from their DTD or XSD?

In Visual Studio 2008 SP1 and later the XML Schema Explorer can create an XML document with some basic sample data:

  1. Open your XSD document
  2. Switch to XML Schema Explorer
  3. Right click the root node and choose "Generate Sample Xml"

Screenshot of the XML Schema Explorer

Execute a command line binary with Node.js

For even newer version of Node.js (v8.1.4), the events and calls are similar or identical to older versions, but it's encouraged to use the standard newer language features. Examples:

For buffered, non-stream formatted output (you get it all at once), use child_process.exec:

const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }

  // the *entire* stdout and stderr (buffered)
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

You can also use it with Promises:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function ls() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
ls();

If you wish to receive the data gradually in chunks (output as a stream), use child_process.spawn:

const { spawn } = require('child_process');
const child = spawn('ls', ['-lh', '/usr']);

// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.on('data', (chunk) => {
  // data from standard output is here as buffers
});

// since these are streams, you can pipe them elsewhere
child.stderr.pipe(dest);

child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Both of these functions have a synchronous counterpart. An example for child_process.execSync:

const { execSync } = require('child_process');
// stderr is sent to stderr of parent process
// you can set options.stdio if you want it to go elsewhere
let stdout = execSync('ls');

As well as child_process.spawnSync:

const { spawnSync} = require('child_process');
const child = spawnSync('ls', ['-lh', '/usr']);

console.log('error', child.error);
console.log('stdout ', child.stdout);
console.log('stderr ', child.stderr);

Note: The following code is still functional, but is primarily targeted at users of ES5 and before.

The module for spawning child processes with Node.js is well documented in the documentation (v5.0.0). To execute a command and fetch its complete output as a buffer, use child_process.exec:

var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

If you need to use handle process I/O with streams, such as when you are expecting large amounts of output, use child_process.spawn:

var spawn = require('child_process').spawn;
var child = spawn('prince', [
  '-v', 'builds/pdf/book.html',
  '-o', 'builds/pdf/book.pdf'
]);

child.stdout.on('data', function(chunk) {
  // output will be here in chunks
});

// or if you want to send output elsewhere
child.stdout.pipe(dest);

If you are executing a file rather than a command, you might want to use child_process.execFile, which parameters which are almost identical to spawn, but has a fourth callback parameter like exec for retrieving output buffers. That might look a bit like this:

var execFile = require('child_process').execFile;
execFile(file, args, options, function(error, stdout, stderr) {
  // command output is in stdout
});

As of v0.11.12, Node now supports synchronous spawn and exec. All of the methods described above are asynchronous, and have a synchronous counterpart. Documentation for them can be found here. While they are useful for scripting, do note that unlike the methods used to spawn child processes asynchronously, the synchronous methods do not return an instance of ChildProcess.

Add Insecure Registry to Docker

Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 resolved the issue.

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Pass array to mvc Action via AJAX

You need to convert Array to string :

//arrayOfValues = [1, 2, 3];  
$.get('/controller/MyAction', { arrayOfValues: "1, 2, 3" }, function (data) {...

this works even in form of int, long or string

public ActionResult MyAction(int[] arrayOfValues )

SET versus SELECT when assigning variables?

I believe SET is ANSI standard whereas the SELECT is not. Also note the different behavior of SET vs. SELECT in the example below when a value is not found.

declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */

set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */

Get all validation errors from Angular 2 FormGroup

You can iterate over this.form.errors property.

Photoshop text tool adds punctuation to the beginning of text

You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.

(if you want to use your project created with other text engine type) copy /paste all layers to new project.

getResourceAsStream returns null

What worked for me was to add the file under My Project/Java Resources/src and then use

this.getClass().getClassLoader().getResourceAsStream("myfile.txt");

I didn't need to explicitly add this file to the path (adding it to /src does that apparently)

Check if a given key already exists in a dictionary

Check if a given key already exists in a dictionary

To get the idea how to do that we first inspect what methods we can call on dictionary. Here are the methods:

d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

Python Dictionary clear()       Removes all Items
Python Dictionary copy()        Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys()    Creates dictionary from given sequence
Python Dictionary get()         Returns Value of The Key
Python Dictionary items()       Returns view of dictionary (key, value) pair
Python Dictionary keys()        Returns View Object of All Keys
Python Dictionary pop()         Removes and returns element having given key
Python Dictionary popitem()     Returns & Removes Element From Dictionary
Python Dictionary setdefault()  Inserts Key With a Value if Key is not Present
Python Dictionary update()      Updates the Dictionary 
Python Dictionary values()      Returns view of all values in dictionary

The brutal method to check if the key already exists may be the get() method:

d.get("key")

The other two interesting methods items() and keys() sounds like too much of work. So let's examine if get() is the right method for us. We have our dict d:

d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

Printing shows the key we don't have will return None:

print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1

We may use that to get the info if the key is present or no. But consider this if we create a dict with a single key:None:

d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None

Leading that get() method is not reliable in case some values may be None. This story should have a happier ending. If we use the in comparator:

print('key' in d) #True
print('key2' in d) #False

We get the correct results. We may examine the Python byte code:

import dis
dis.dis("'key' in d")
#   1           0 LOAD_CONST               0 ('key')
#               2 LOAD_NAME                0 (d)
#               4 COMPARE_OP               6 (in)
#               6 RETURN_VALUE

dis.dis("d.get('key2')")
#   1           0 LOAD_NAME                0 (d)
#               2 LOAD_METHOD              1 (get)
#               4 LOAD_CONST               0 ('key2')
#               6 CALL_METHOD              1
#               8 RETURN_VALUE

This shows that in compare operator is not just more reliable but even faster than get().

How to see docker image contents

We can try a simpler one as follows:

docker image inspect image_id

This worked in Docker version:

DockerVersion": "18.05.0-ce"

How to remove "Server name" items from history of SQL Server Management Studio

In SSMS 2012 there is a documented way to delete the server name from the "Connect to Server" dialog. Now, we can remove the server name by selecting it in the dialog and pressing DELETE.

How to read and write INI file with Python3?

This can be something to start with:

import configparser

config = configparser.ConfigParser()
config.read('FILE.INI')
print(config['DEFAULT']['path'])     # -> "/path/name/"
config['DEFAULT']['path'] = '/var/shared/'    # update
config['DEFAULT']['default_message'] = 'Hey! help me!!'   # create

with open('FILE.INI', 'w') as configfile:    # save
    config.write(configfile)

You can find more at the official configparser documentation.

Prevent scroll-bar from adding-up to the Width of page on Chrome

It doesn't seem my other answer is working quite right at the moment (but I'll continue to try to get it operational).

But basically what you'll need to do, and what it was trying to do dynamically, is set the contents' width to slightly less than that of the parent, scrollable pane.
So that when the scrollbar appears it has no affect on the content.

This EXAMPLE shows a more hacky way of attaining that goal, by hardcoding widths instead of trying to get the browser to do it for us via padding.
If this is feasible this is the most simplest solution if you don't want a permanent scrollbar.

Update Git branches from master

  1. git checkout master
  2. git pull
  3. git checkout feature_branch
  4. git rebase master
  5. git push -f

You need to do a forceful push after rebasing against master

How to edit log message already committed in Subversion?

Essentially you have to have admin rights (directly or indirectly) to the repository to do this. You can either configure the repository to allow all users to do this, or you can modify the log message directly on the server.

See this part of the Subversion FAQ (emphasis mine):

Log messages are kept in the repository as properties attached to each revision. By default, the log message property (svn:log) cannot be edited once it is committed. That is because changes to revision properties (of which svn:log is one) cause the property's previous value to be permanently discarded, and Subversion tries to prevent you from doing this accidentally. However, there are a couple of ways to get Subversion to change a revision property.

The first way is for the repository administrator to enable revision property modifications. This is done by creating a hook called "pre-revprop-change" (see this section in the Subversion book for more details about how to do this). The "pre-revprop-change" hook has access to the old log message before it is changed, so it can preserve it in some way (for example, by sending an email). Once revision property modifications are enabled, you can change a revision's log message by passing the --revprop switch to svn propedit or svn propset, like either one of these:

$svn propedit -r N --revprop svn:log URL 
$svn propset -r N --revprop svn:log "new log message" URL 

where N is the revision number whose log message you wish to change, and URL is the location of the repository. If you run this command from within a working copy, you can leave off the URL.

The second way of changing a log message is to use svnadmin setlog. This must be done by referring to the repository's location on the filesystem. You cannot modify a remote repository using this command.

$ svnadmin setlog REPOS_PATH -r N FILE

where REPOS_PATH is the repository location, N is the revision number whose log message you wish to change, and FILE is a file containing the new log message. If the "pre-revprop-change" hook is not in place (or you want to bypass the hook script for some reason), you can also use the --bypass-hooks option. However, if you decide to use this option, be very careful. You may be bypassing such things as email notifications of the change, or backup systems that keep track of revision properties.

How to retrieve a file from a server via SFTP?

The best solution I've found is Paramiko. There's a Java version.

Selenium Webdriver move mouse to Point

Using MoveToElement you will be able to find or click in whatever point you want, you have just to define the first parameter, it can be the session(winappdriver) or driver(in other ways) which is created when you instance WindowsDriver. Otherwise you can set as first parameter a grid (my case), a list, a panel or whatever you want.

Note: The top-left of your first parameter element will be the position X = 0 and Y = 0

   Actions actions = new Actions(this.session);
    int xPosition = this.session.FindElementsByAccessibilityId("GraphicView")[0].Size.Width - 530;
    int yPosition = this.session.FindElementsByAccessibilityId("GraphicView")[0].Size.Height- 150;
    actions.MoveToElement(this.xecuteClientSession.FindElementsByAccessibilityId("GraphicView")[0], xPosition, yPosition).ContextClick().Build().Perform();

Find length (size) of an array in jquery

Integer has no method length. Try string

var testvar={};
testvar[1]="2";
alert(testvar[1].length);

INSERT INTO...SELECT for all MySQL columns

More Examples & Detail

    INSERT INTO vendors (
     name, 
     phone, 
     addressLine1,
     addressLine2,
     city,
     state,
     postalCode,
     country,
     customer_id
 )
 SELECT 
     name,
     phone,
     addressLine1,
     addressLine2,
     city,
     state ,
     postalCode,
     country,
     customer_id
 FROM 
     customers;

Python for and if on one line

The reason it prints "three" is because you didnt define your array. The equivalent to what you're doing is:

arr = []
for i in array :
    if i == "two" :
        arr.push(i)
print(i)

You are asking for the last element it looked through, which is not what you should be doing. You need to be storing the array to a variable in order to get the element.

The english equivalent of what you are doing is:

You: "I need you to print all the elements in this array that equal two, but in an array. And each time you cycle through the list, define the current element as I."
Computer: "Here: ["two"]"
You: "Now tell me 'i'"
Computer: "'i' is equal to "three"
You: "Why?"

The reason 'i' is equal to "three" is because three was the last thing that was defined as I

the computer did:

i = "one"
i = "two"
i = "three"

print(["two"])

Because you asked it to.

If you want the index, go here If you want the values in an array, define the array, like this:

MyArray = [(i) for i in my_list if i=="two"]

rbenv not changing ruby version

All the other answers here give good advice for various situations, but there is an easier way.

The rbenv docs point us to the rbenv-doctor diagnostic tool that will quickly verify all these potential pitfalls on your system:

curl -fsSL https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-doctor | bash

When all is well, you'll see this:

$ curl -fsSL https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-doctor | bash                                     <aws:hd-pmp-developer>
Checking for `rbenv' in PATH: /usr/local/bin/rbenv
Checking for rbenv shims in PATH: OK
Checking `rbenv install' support: /usr/local/bin/rbenv-install (ruby-build 20201005)
Counting installed Ruby versions: 1 versions
Checking RubyGems settings: OK
Auditing installed plugins: OK

Now, if we break one of those expectations (e.g. remove rbenv-install), the tool will point us directly to the problem, with a link to how to fix it:

$ mv /usr/local/bin/rbenv-install rbenv-install-GONE
                                                                      
$ curl -fsSL https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-doctor | bash                                     
Checking for `rbenv' in PATH: /usr/local/bin/rbenv
Checking for rbenv shims in PATH: OK

===> Checking `rbenv install' support: not found <===
  Unless you plan to add Ruby versions manually, you should install ruby-build.
  Please refer to https://github.com/rbenv/ruby-build#installation

Counting installed Ruby versions: 1 versions
Checking RubyGems settings: OK
Auditing installed plugins: OK

What is the difference between new/delete and malloc/free?

new and delete are operators in c++; which can be overloaded too. malloc and free are function in c;

malloc returns null ptr when fails while new throws exception.

address returned by malloc need to by type casted again as it returns the (void*)malloc(size) New return the typed pointer.

Retrieving the text of the selected <option> in <select> element

document.getElementById('test').options[document.getElementById('test').selectedIndex].text;

Disable LESS-CSS Overwriting calc()

Here's a cross-browser less mixin for using CSS's calc with any property:

.calc(@prop; @val) {
  @{prop}: calc(~'@{val}');
  @{prop}: -moz-calc(~'@{val}');
  @{prop}: -webkit-calc(~'@{val}');
  @{prop}: -o-calc(~'@{val}');
}

Example usage:

.calc(width; "100% - 200px");

And the CSS that's output:

width: calc(100% - 200px);
width: -moz-calc(100% - 200px);
width: -webkit-calc(100% - 200px);
width: -o-calc(100% - 200px);

A codepen of this example: http://codepen.io/patrickberkeley/pen/zobdp

How to empty the message in a text area with jquery?

A comment to jarijira

Well I have had many issues with .html and .empty() methods for inputs o. If the id represents an input and not another type of html selector like

or use the .val() function to manipulate.

For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').val('') //clear input value
     $('#someInput').val(newVal) //override w/ the new value
     $('#someInput').val('test2) 
     newVal= $('#someInput').val(newVal) //get input value

}

For improper, but sometimes works For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').html('') //clear input value
     $('#someInput').empty() //clear html inside of the id
     $('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
     really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input. 
     newVal= $('#someInput').val(newVal) //get input value

}

An issue that I had was I was using the $getJson method and I was indeed able to use .html calls to manipulate my inputs. However, whenever I had an error or fail on the getJSON I could no longer change my inputs using the .clear and .html calls. I could still return the .val(). After some experimentation and research I discovered that you should only use the .val() function to make changes to input fields.

Why does SSL handshake give 'Could not generate DH keypair' exception?

It is possible that you have incorrect Maven dependencies. You must find these libraries in Maven dependency hierarchy:

bcprov-jdk14, bcpkix-jdk14, bcmail-jdk14

If you have these dependencies that is the error, and you should do this:

Add the dependency:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcmail-jdk15on</artifactId>
    <version>1.59</version>
</dependency>

Exclude these dependencies from the artifact that included the wrong dependencies, in my case it is:

<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
    <exclusions>
        <exclusion>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bctsp-jdk14</artifactId>                
        </exclusion>
        <exclusion>
            <groupId>bouncycastle</groupId>
            <artifactId>bcprov-jdk14</artifactId>               
        </exclusion>
        <exclusion>
            <groupId>bouncycastle</groupId>
            <artifactId>bcmail-jdk14</artifactId>               
        </exclusion>
    </exclusions>       
</dependency>

One liner for If string is not null or empty else

This may help:

public string NonBlankValueOf(string strTestString)
{
    return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}

Difference between staticmethod and classmethod

One pretty important practical difference occurs when subclassing. If you don't mind, I'll hijack @unutbu's example:

class A: 
    def foo(self, x): 
        print("executing foo(%s, %s)" % (self, x)) 
 
    @classmethod
    def class_foo(cls, x): 
        print("executing class_foo(%s, %s)" % (cls, x))
 
    @staticmethod 
    def static_foo(x): 
        print("executing static_foo(%s)" % x)

class B(A):
    pass

In class_foo, the method knows which class it is called on:

A.class_foo(1)
# => executing class_foo(<class '__main__.A'>, 1)
B.class_foo(1)
# => executing class_foo(<class '__main__.B'>, 1)

In static_foo, there is no way to determine whether it is called on A or B:

A.static_foo(1)
# => executing static_foo(1)
B.static_foo(1)
# => executing static_foo(1)

Note that this doesn't mean you can't use other methods in a staticmethod, you just have to reference the class directly, which means subclasses' staticmethods will still reference the parent class:

class A:
    @classmethod
    def class_qux(cls, x):
        print(f"executing class_qux({cls}, {x})")
    
    @classmethod
    def class_bar(cls, x):
        cls.class_qux(x)

    @staticmethod
    def static_bar(x):
        A.class_qux(x)

class B(A):
    pass

A.class_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)
B.class_bar(1)
# => executing class_qux(<class '__main__.B'>, 1)
A.static_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)
B.static_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)

What is the best way to remove accents (normalize) in a Python unicode string?

Unidecode is the correct answer for this. It transliterates any unicode string into the closest possible representation in ascii text.

Example:

accented_string = u'Málaga'
# accented_string is of type 'unicode'
import unidecode
unaccented_string = unidecode.unidecode(accented_string)
# unaccented_string contains 'Malaga'and is of type 'str'

Java get last element of a collection

There isn't a last() or first() method in a Collection interface. For getting the last method, you can either do get(size() - 1) on a List or reverse the List and do get(0). I don't see a need to have last() method in any Collection API unless you are dealing with Stacks or Queues

OpenCV & Python - Image too big to display

Use this for example:

cv2.namedWindow('finalImg', cv2.WINDOW_NORMAL)
cv2.imshow("finalImg",finalImg)

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

If someone needs to call Dialog from services here is how to solve the issue. I agree with some of above answer, my answer is for calling dialog in services if someone may face issues on.

Create a service for example DialogService then move your dialog function inside the services and add your dialogservice in the component you call like below code:

 @Component({
  selector: "app-newsfeed",
  templateUrl: "./abc.component.html",
  styleUrls: ["./abc.component.css",],
  providers:[DialogService]
})

otherwise you get error

macro - open all files in a folder

You have to add this line just before loop

    MyFile = Dir
Loop

get all the elements of a particular form

var inputs = document.getElementById("formId").getElementsByTagName("input");
var inputs = document.forms[1].getElementsByTagName("input");

Update for 2020:

var inputs = document.querySelectorAll("#formId input");

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

Creating csv file with php

Its blank because you are writing to file. you should write to output using php://output instead and also send header information to indicate that it's csv.

Example

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
        'aaa,bbb,ccc,dddd',
        '123,456,789',
        '"aaa","bbb"'
);

$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, $val);
}
fclose($fp);

Why are Python's 'private' methods not actually private?

It's not like you absolutly can't get around privateness of members in any language (pointer arithmetics in C++, Reflections in .NET/Java).

The point is that you get an error if you try to call the private method by accident. But if you want to shoot yourself in the foot, go ahead and do it.

Edit: You don't try to secure your stuff by OO-encapsulation, do you?

maven error: package org.junit does not exist

Ok, you've declared junit dependency for test classes only (those that are in src/test/java but you're trying to use it in main classes (those that are in src/main/java).

Either do not use it in main classes, or remove <scope>test</scope>.

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

PHP check file extension

$file = $_FILES["file"] ["tmp_name"]; 
$check_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
if ($check_ext == "fileext") {
    //code
}
else { 
    //code
}

How to fix committing to the wrong Git branch?

I recently did the same thing, where I accidentally committed a change to master, when I should have committed to other-branch. But I didn't push anything.

If you just committed to the wrong branch, and have not changed anything since, and have not pushed to the repo, then you can do the following:

// rewind master to point to the commit just before your most recent commit.
// this takes all changes in your most recent commit, and turns them into unstaged changes. 
git reset HEAD~1 

// temporarily save your unstaged changes as a commit that's not attached to any branch using git stash
// all temporary commits created with git stash are put into a stack of temporary commits.
git stash

// create other-branch (if the other branch doesn't already exist)
git branch other-branch

// checkout the other branch you should have committed to.
git checkout other-branch

// take the temporary commit you created, and apply all of those changes to the new branch. 
//This also deletes the temporary commit from the stack of temp commits.
git stash pop

// add the changes you want with git add...

// re-commit your changes onto other-branch
git commit -m "some message..."

NOTE: in the above example, I was rewinding 1 commit with git reset HEAD~1. But if you wanted to rewind n commits, then you can do git reset HEAD~n.

Also, if you ended up committing to the wrong branch, and also ended up write some more code before realizing that you committed to the wrong branch, then you could use git stash to save your in-progress work:

// save the not-ready-to-commit work you're in the middle of
git stash 

// rewind n commits
git reset HEAD~n 

// stash the committed changes as a single temp commit onto the stack. 
git stash 

// create other-branch (if it doesn't already exist)
git branch other-branch

// checkout the other branch you should have committed to.
git checkout other-branch

// apply all the committed changes to the new branch
git stash pop

// add the changes you want with git add...

// re-commit your changes onto the new branch as a single commit.
git commit -m "some message..."

// pop the changes you were in the middle of and continue coding
git stash pop

NOTE: I used this website as a reference https://www.clearvision-cm.com/blog/what-to-do-when-you-commit-to-the-wrong-git-branch/

How to solve privileges issues when restore PostgreSQL Database

Try using the -L flag with pg_restore by specifying the file taken from pg_dump -Fc

-L list-file --use-list=list-file

Restore only those archive elements that are listed in list-file, and restore them in the order they appear in the file. Note that if filtering switches such as -n or -t are used with -L, they will further restrict the items restored.

list-file is normally created by editing the output of a previous -l operation. Lines can be moved or removed, and can also be commented out by placing a semicolon (;) at the start of the line. See below for examples.

https://www.postgresql.org/docs/9.5/app-pgrestore.html

pg_dump -Fc -f pg.dump db_name
pg_restore -l pg.dump | grep -v 'COMMENT - EXTENSION' > pg_restore.list
pg_restore -L pg_restore.list pg.dump

Here you can see the Inverse is true by outputting only the comment:

pg_dump -Fc -f pg.dump db_name
pg_restore -l pg.dump | grep 'COMMENT - EXTENSION' > pg_restore_inverse.list
pg_restore -L pg_restore_inverse.list pg.dump
--
-- PostgreSQL database dump
--

-- Dumped from database version 9.4.15
-- Dumped by pg_dump version 9.5.14

SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;

--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: 
--

COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';


--
-- PostgreSQL database dump complete
--

What does file:///android_asset/www/index.html mean?

It took me more than 4 hours to fix this problem. I followed the guide from http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

I'm using Android Studio (Eclipse with ADT could not work properly because of the build problem).

Solution that worked for me:

  1. I put the /assets/www/index.html under app/src/main/assets directory. (take care AndroidStudio has different perspectives like Project or Android)

  2. use super.loadUrl("file:///android_asset/www/index.html"); instead of super.loadUrl("file:///android_assets/www/index.html"); (no s)

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

how to create a logfile in php?

For printing log use this function, this will create log file in log folder. Create log folder if its not exists .

logger("Your msg in log ", "Filename you want ", "Data to be log string or array or object");


function logger($logMsg="logger", $filename="logger", $logData=""){     
            $log  = date("j.n.Y h:i:s")." || $logMsg : ".print_r($logData,1).PHP_EOL .                  
            "-------------------------".PHP_EOL;
            file_put_contents('./log/'.$filename.date("j.n.Y").'.log', $log, FILE_APPEND);                      
    }

Http Get using Android HttpURLConnection

A more contemporary way of doing it on a separate thread using Tasks and Kotlin

private val mExecutor: Executor = Executors.newSingleThreadExecutor()

private fun createHttpTask(u:String): Task<String> {
    return Tasks.call(mExecutor, Callable<String>{
        val url = URL(u)
        val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
        conn.requestMethod = "GET"
        conn.connectTimeout = 3000
        conn.readTimeout = 3000
        val rc = conn.responseCode
        if ( rc != HttpURLConnection.HTTP_OK) {
            throw java.lang.Exception("Error: ${rc}")
        }
        val inp: InputStream = BufferedInputStream(conn.inputStream)
        val resp: String = inp.bufferedReader(UTF_8).use{ it.readText() }
        return@Callable resp
    })
}

and now you can use it like below in many places:

            createHttpTask("https://google.com")
                    .addOnSuccessListener {
                        Log.d("HTTP", "Response: ${it}") // 'it' is a response string here
                    }
                    .addOnFailureListener {
                        Log.d("HTTP", "Error: ${it.message}") // 'it' is an Exception object here
                    }

How do I launch a program from command line without opening a new cmd window?

20190907

OS: Win 10

I'm making an exe in c++, for some reason usting START make my program fail.

So, just use quotes:

"c:\folder\program.exe"

Can I set text box to readonly when using Html.TextBoxFor?

By setting readonly attribute to either true or false is not going to work in most browsers, I have done it as below, when the mode of the page is "reload", I've not included "readonly" attribute.

@if(Model.Mode.Equals("edit")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @readonly = moduleEditModel.Content.ReadOnly, @style = "width:99%; height:360px;" })
}
@if (Model.Mode.Equals("reload")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @style = "width:99%; height:360px;" })}

Split string in C every white space

Something going wrong is get_words() always returning one less than the actual word count, so eventually you attempt to:

char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */

newbuff[count2] = (char *)malloc(strlen(buffer))

count2, eventually, is always one more than the number of elements you've declared for newbuff[]. Why malloc() isn't returning a valid ptr, though, I don't know.

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to pass a textbox value from view to a controller in MVC 4?

When you want to pass new information to your application, you need to use POST form. In Razor you can use the following

View Code:

@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
     @Html.Hidden("id", Model.Id)
     @Html.Hidden("productid", Model.ProductId)
     @Html.TextBox("qty", Model.Quantity)
     @Html.TextBox("unitrate", Model.UnitRate)
     <input type="submit" value="Update" />
}

Controller's actions

[HttpGet]
public ActionResult Update(){
     //[...] retrive your record object
     return View(objRecord);
}

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
      if (ModelState.IsValid){
           int _records = UpdatePrice(id,productid,qty,unitrate);
           if (_records > 0){                    {
              return RedirectToAction("Index1", "Shopping");
           }else{                   
                ModelState.AddModelError("","Can Not Update");
           }
      }
      return View("Index1");
 }

Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity) you can either have an input with the name (respectecting case) "Quantity" or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:

Model

public class Record {
    public string Id { get; set; }
    public string ProductId { get; set; }
    public string Quantity { get; set; }
    public decimal UnitRate { get; set; }
}

View

@using(Html.BeginForm("Update")){
     @Html.HiddenFor(model => model.Id)
     @Html.HiddenFor(model => model.ProductId)
     @Html.TextBoxFor(model=> model.Quantity)
     @Html.TextBoxFor(model => model.UnitRate)
     <input type="submit" value="Update" />
}

Post Action

[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well 
   if(TryValidateModel(rec)){
        //update code
   }
   return View("Index1");
}

How to force Docker for a clean build of an image

You can manage the builder cache with docker builder

To clean all the cache with no prompt: docker builder prune -af

Simulating Button click in javascript

The reason your code isn't working the way you would expect is because this line:

<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>

should be changed to:

<button type="button" value="submit" onClick="document.getElementById('datepicker').focus()">submit </button>

There are two things to notice here:

1: The "s around datepicker have been changed to 's so that they do not interfere with the quotes surrounding the onclick event.

2: The click() has been changed to focus() to activate the datepicker calendar. When the button is pressed.

Now, this fixes your issue...but I do agree with the other posts that using jQuery to access the DOM element and trigger the event is the better way to go. Since you're already doing this for the jQuery datapicker plugin via <script src="http://code.jquery.com/jquery-1.8.3.js"></script>, this should not be a problem.

Inline events are not recommended.

Use RSA private key to generate public key?

My answer below is a bit lengthy, but hopefully it provides some details that are missing in previous answers. I'll start with some related statements and finally answer the initial question.

To encrypt something using RSA algorithm you need modulus and encryption (public) exponent pair (n, e). That's your public key. To decrypt something using RSA algorithm you need modulus and decryption (private) exponent pair (n, d). That's your private key.

To encrypt something using RSA public key you treat your plaintext as a number and raise it to the power of e modulus n:

ciphertext = ( plaintext^e ) mod n

To decrypt something using RSA private key you treat your ciphertext as a number and raise it to the power of d modulus n:

plaintext = ( ciphertext^d ) mod n

To generate private (d,n) key using openssl you can use the following command:

openssl genrsa -out private.pem 1024

To generate public (e,n) key from the private key using openssl you can use the following command:

openssl rsa -in private.pem -out public.pem -pubout

To dissect the contents of the private.pem private RSA key generated by the openssl command above run the following (output truncated to labels here):

openssl rsa -in private.pem -text -noout | less

modulus         - n
privateExponent - d
publicExponent  - e
prime1          - p
prime2          - q
exponent1       - d mod (p-1)
exponent2       - d mod (q-1)
coefficient     - (q^-1) mod p

Shouldn't private key consist of (n, d) pair only? Why are there 6 extra components? It contains e (public exponent) so that public RSA key can be generated/extracted/derived from the private.pem private RSA key. The rest 5 components are there to speed up the decryption process. It turns out that by pre-computing and storing those 5 values it is possible to speed the RSA decryption by the factor of 4. Decryption will work without those 5 components, but it can be done faster if you have them handy. The speeding up algorithm is based on the Chinese Remainder Theorem.

Yes, private.pem RSA private key actually contains all of those 8 values; none of them are generated on the fly when you run the previous command. Try running the following commands and compare output:

# Convert the key from PEM to DER (binary) format
openssl rsa -in private.pem -outform der -out private.der

# Print private.der private key contents as binary stream
xxd -p private.der

# Now compare the output of the above command with output 
# of the earlier openssl command that outputs private key
# components. If you stare at both outputs long enough
# you should be able to confirm that all components are
# indeed lurking somewhere in the binary stream
openssl rsa -in private.pem -text -noout | less

This structure of the RSA private key is recommended by the PKCS#1 v1.5 as an alternative (second) representation. PKCS#1 v2.0 standard excludes e and d exponents from the alternative representation altogether. PKCS#1 v2.1 and v2.2 propose further changes to the alternative representation, by optionally including more CRT-related components.

To see the contents of the public.pem public RSA key run the following (output truncated to labels here):

openssl rsa -in public.pem -text -pubin -noout

Modulus             - n
Exponent (public)   - e

No surprises here. It's just (n, e) pair, as promised.

Now finally answering the initial question: As was shown above private RSA key generated using openssl contains components of both public and private keys and some more. When you generate/extract/derive public key from the private key, openssl copies two of those components (e,n) into a separate file which becomes your public key.

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

What does [object Object] mean?

You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString() value is automatically set as "[object Object]".

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

Change tab bar tint color on iOS 7

Write this in your View Controller class of your Tab Bar:

// Generate a black tab bar
self.tabBarController.tabBar.barTintColor = [UIColor blackColor];

// Set the selected icons and text tint color
self.tabBarController.tabBar.tintColor = [UIColor orangeColor];

How to get value by key from JObject?

This should help -

var json = "{'@STARTDATE': '2016-02-17 00:00:00.000',  '@ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["@STARTDATE"];

Add Expires headers

try this solution and it is working fine for me

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js 
</IfModule>

## EXPIRES CACHING ##

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

How to go to a specific element on page?

To scroll to a specific element on your page, you can add a function into your jQuery(document).ready(function($){...}) as follows:

$("#fromTHIS").click(function () {
    $("html, body").animate({ scrollTop: $("#toTHIS").offset().top }, 500);
    return true;
});

It works like a charm in all browsers. Adjust the speed according to your need.

Run Python script at startup in Ubuntu

If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-

  • Open Dash (The First Icon In Sidebar).
  • Then type Startup Applications and open that app.
  • Here Click the Add Button on the right.
  • There fill in the details and in the command area browse for your Python File and click Ok.
  • Test it by Restarting System . Done . Enjoy !!

How to search for an element in an stl list?

You use std::find from <algorithm>, which works equally well for std::list and std::vector. std::vector does not have its own search/find function.

#include <list>
#include <algorithm>

int main()
{
    std::list<int> ilist;
    ilist.push_back(1);
    ilist.push_back(2);
    ilist.push_back(3);

    std::list<int>::iterator findIter = std::find(ilist.begin(), ilist.end(), 1);
}

Note that this works for built-in types like int as well as standard library types like std::string by default because they have operator== provided for them. If you are using using std::find on a container of a user-defined type, you should overload operator== to allow std::find to work properly: EqualityComparable concept

PHP - find entry by object property from an array of objects

I did this with some sort of Java keymap. If you do that, you do not need to loop over your objects array every time.

<?php

//This is your array with objects
$object1 = (object) array('id'=>123,'name'=>'Henk','age'=>65);
$object2 = (object) array('id'=>273,'name'=>'Koos','age'=>25);
$object3 = (object) array('id'=>685,'name'=>'Bram','age'=>75);
$firstArray = Array($object1,$object2);
var_dump($firstArray);

//create a new array
$secondArray = Array();
//loop over all objects
foreach($firstArray as $value){
    //fill second        key          value
    $secondArray[$value->id] = $value->name;
}

var_dump($secondArray);

echo $secondArray['123'];

output:

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'id' => int 123
      public 'name' => string 'Henk' (length=4)
      public 'age' => int 65
  1 => 
    object(stdClass)[2]
      public 'id' => int 273
      public 'name' => string 'Koos' (length=4)
      public 'age' => int 25
array (size=2)
  123 => string 'Henk' (length=4)
  273 => string 'Koos' (length=4)
Henk

Converting BitmapImage to Bitmap and vice versa

Here the async version.

public static Task<BitmapSource> ToBitmapSourceAsync(this Bitmap bitmap)
{
    return Task.Run(() =>
    {
        using (System.IO.MemoryStream memory = new System.IO.MemoryStream())
        {
            bitmap.Save(memory, ImageFormat.Png);
            memory.Position = 0;
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            bitmapImage.Freeze();
            return bitmapImage as BitmapSource;
        }
    });

}

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

MySQL is getting stupid here. It tries to create files under /tmp/data/.... So what you can do is the following:

mkdir /tmp/data
mount --bind /data /tmp/data

Then try your query. This worked for me after hours of debugging the issue.

sql use statement with variable

Just wanted to thank KM for his valuable solution. I implemented it myself to reduce the amount of lines in a shrinkdatabase request on SQLServer. Here is my SQL request if it can help anyone :

-- Declare the variable to be used
DECLARE @Query varchar (1000)
DECLARE @MyDBN varchar(11);
-- Initializing the @MyDBN variable (possible values : db1, db2, db3, ...)
SET @MyDBN = 'db1';
-- Creating the request to execute
SET @Query='use '+ @MyDBN +'; ALTER DATABASE '+ @MyDBN +' SET RECOVERY SIMPLE WITH NO_WAIT; DBCC SHRINKDATABASE ('+ @MyDBN +', 1, TRUNCATEONLY); ALTER DATABASE '+ @MyDBN +' SET RECOVERY FULL WITH NO_WAIT'
-- 
EXEC (@Query)

Getting all types in a namespace via reflection

For a specific Assembly, NameSpace and ClassName:

var assemblyName = "Some.Assembly.Name"
var nameSpace = "Some.Namespace.Name";
var className = "ClassNameFilter";

var asm = Assembly.Load(assemblyName);
var classes = asm.GetTypes().Where(p =>
     p.Namespace == nameSpace &&
     p.Name.Contains(className) 
).ToList();

Note: The project must reference the assembly

Make div 100% Width of Browser Window

Try to give it a postion: absolute;

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

We use the Url Rewrite extension for IIS for redirecting all HTTP requests to HTTPS. When trying to call a service not using transport security on an http://... address, this is the error that appeared.

So it might be worth checking if you can hit both the http and https addresses of the service via a browser and that it doesn't auto forward you with a 303 status code.

How to parse freeform street/postal address out of text, and into components

There are many street address parsers. They come in two basic flavors - ones that have databases of place names and street names, and ones that don't.

A regular expression street address parser can get up to about a 95% success rate without much trouble. Then you start hitting the unusual cases. The Perl one in CPAN, "Geo::StreetAddress::US", is about that good. There are Python and Javascript ports of that, all open source. I have an improved version in Python which moves the success rate up slightly by handling more cases. To get the last 3% right, though, you need databases to help with disambiguation.

A database with 3-digit ZIP codes and US state names and abbreviations is a big help. When a parser sees a consistent postal code and state name, it can start to lock on to the format. This works very well for the US and UK.

Proper street address parsing starts from the end and works backwards. That's how the USPS systems do it. Addresses are least ambiguous at the end, where country names, city names, and postal codes are relatively easy to recognize. Street names can usually be isolated. Locations on streets are the most complex to parse; there you encounter things such as "Fifth Floor" and "Staples Pavillion". That's when a database is a big help.

SQL Server Service not available in service list after installation of SQL Server Management Studio

You need to start the SQL Server manually. Press

windows + R

type

sqlservermanager12.msc

right click ->Start

Service configuration does not display SQL Server?

How can I restore the MySQL root user’s full privileges?

GRANT ALL ON *.* TO 'user'@'localhost' with GRANT OPTION;

Just log in from root using the respective password if any and simply run the above command to whatever the user is.

For example:

GRANT ALL ON *.* TO 'root'@'%' with GRANT OPTION;

How to set Spring profile from system variable?

If i run the command line : java -Dspring.profiles.active=development -jar yourApplication.jar from my webapplication directory it states that the path is incorrect. So i just defined the profile in manualy in the application.properties file like this :

spring.profiles.active=mysql 

or

spring.profiles.active=postgres

or

spring.profiles.active=mongodb

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

You might be running an older version of Intel HAXM (or haven't installed it at all). Go to https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager and download/install the latest Intel HAXM package for MAC OS X.

EDIT: according to https://software.intel.com/en-us/forums/topic/506790 you should also make sure that Virtual PC/Parallel/VMWare is not running.

Minimal web server using netcat

Another way to do this

while true; do (echo -e 'HTTP/1.1 200 OK\r\n'; echo -e "\n\tMy website has date function" ; echo -e "\t$(date)\n") | nc -lp 8080; done

Let's test it with 2 HTTP request using curl

In this example, 172.16.2.6 is the server IP Address.

Server Side

admin@server:~$ while true; do (echo -e 'HTTP/1.1 200 OK\r\n'; echo -e "\n\tMy website has date function" ; echo -e "\t$(date)\n") | nc -lp 8080; done

GET / HTTP/1.1 Host: 172.16.2.6:8080 User-Agent: curl/7.48.0 Accept:
*/*

GET / HTTP/1.1 Host: 172.16.2.6:8080 User-Agent: curl/7.48.0 Accept:
*/*

Client Side

user@client:~$ curl 172.16.2.6:8080

        My website has date function
        Tue Jun 13 18:00:19 UTC 2017

user@client:~$ curl 172.16.2.6:8080

        My website has date function
        Tue Jun 13 18:00:24 UTC 2017

user@client:~$

If you want to execute another command, feel free to replace $(date).

Start a fragment via Intent within a Fragment

The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...

Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.

@Override
public void onClick(View v) {
    // Create new fragment and transaction
    Fragment newFragment = new chartsFragment(); 
    // consider using Java coding conventions (upper first char class names!!!)
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit(); 
}

http://developer.android.com/guide/components/fragments.html#Transactions

How do I find out what type each object is in a ArrayList<Object>?

You can use the getClass() method, or you can use instanceof. For example

for (Object obj : list) {
  if (obj instanceof String) {
   ...
  }
}

or

for (Object obj : list) {
 if (obj.getClass().equals(String.class)) {
   ...
 }
}

Note that instanceof will match subclasses. For instance, of C is a subclass of A, then the following will be true:

C c = new C();
assert c instanceof A;

However, the following will be false:

C c = new C();
assert !c.getClass().equals(A.class)

How do I make WRAP_CONTENT work on a RecyclerView

Put the recyclerview in any other layout (Relative layout is preferable). Then change recyclerview's height/width as match parent to that layout and set the parent layout's height/width as wrap content.

Source: This comment.

Full examples of using pySerial package

I have not used pyserial but based on the API documentation at https://pyserial.readthedocs.io/en/latest/shortintro.html it seems like a very nice interface. It might be worth double-checking the specification for AT commands of the device/radio/whatever you are dealing with.

Specifically, some require some period of silence before and/or after the AT command for it to enter into command mode. I have encountered some which do not like reads of the response without some delay first.

What is the difference between 'protected' and 'protected internal'?

There is still a lot of confusion in understanding the scope of "protected internal" accessors, though most have the definition defined correctly. This helped me to understand the confusion between "protected" and "protected internal":

public is really public inside and outside the assembly (public internal / public external)

protected is really protected inside and outside the assembly (protected internal / protected external) (not allowed on top level classes)

private is really private inside and outside the assembly (private internal / private external) (not allowed on top level classes)

internal is really public inside the assembly but excluded outside the assembly like private (public internal / excluded external)

protected internal is really public inside the assembly but protected outside the assembly (public internal / protected external) (not allowed on top level classes)

As you can see protected internal is a very strange beast. Not intuitive.

That now begs the question why didn't Microsoft create a (protected internal / excluded external), or I guess some kind of "private protected" or "internal protected"? lol. Seems incomplete?

Added to the confusion is the fact you can nest public or protected internal nested members inside protected, internal, or private types. Why would you access a nested "protected internal" inside an internal class that excludes outside assembly access?

Microsoft says such nested types are limited by their parent type scope, but that's not what the compiler says. You can compiled protected internals inside internal classes which should limit scope to just the assembly.

To me this feels like incomplete design. They should have simplified scope of all types to a system that clearly consider inheritance but also security and hierarchy of nested types. This would have made the sharing of objects extremely intuitive and granular rather than discovering accessibility of types and members based on an incomplete scoping system.

Set textarea width to 100% in bootstrap modal

The provided solutions do resolve the issue. However, they also impact all other textarea elements with the same styling. I had to solve this and just created a more specific selector. Here is what I came up with to prevent invasive changes.

.modal-content textarea.form-control {
    max-width: 100%;
}

While this selector may seem aggressive. It helps restrain the textarea into the content area of the modal itself.

Additionally, the min-width solution presented, above, works with basic bootstrap modals, though I had issues when using it with angular-ui-bootstrap modals.

In a URL, should spaces be encoded using %20 or +?

This confusion is because URL is still 'broken' to this day

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+   
|      Part     |      Data         |   
+---------------+-------------------+   
|  Scheme       | http              |   
|  Host address | www.google.com    |   
+---------------+-------------------+  

If we look at a more complex URL such as "https://bob:[email protected]:8080/file;p=1?q=2#third" we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host address     | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file               |
|  Path parameters  | p=1                 |
|  Query parameters | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

The reserved characters are different for each part

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts: "http://example.com/blue+light%20blue?blue%2Blight+blue". From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

What this boils down to is

you should have %20 before the ? and + after

Source

How can I rollback an UPDATE query in SQL server 2005?

You can use implicit transactions for this

SET IMPLICIT_TRANSACTIONS ON

update Staff set staff_Name='jas' where staff_id=7

ROLLBACK

As you request-- You can SET this setting ( SET IMPLICIT_TRANSACTIONS ON) from a stored procedure by setting that stored procedure as the start up procedure.

But SET IMPLICIT TRANSACTION ON command is connection specific. So any connection other than the one which running the start up stored procedure will not benefit from the setting you set.

How can I recursively find all files in current and subfolders based on wildcard matching?

Use

find path/to/dir -name "*.ext1" -o -name "*.ext2"

Explanation

  1. The first parameter is the directory you want to search.
  2. By default find does recursion.
  3. The -o stands for -or. So above means search for this wildcard OR this one. If you have only one pattern then no need for -o.
  4. The quotes around the wildcard pattern are required.

Center div on the middle of screen

Try this:

 div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background: red;
}

Here div is html tag. You wrote a html tag followed by a dot that is wrong.Only a class is written followed by dot.

Is there a foreach loop in Go?

Yes, Range :

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

Example :

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
    for i, v := range pow {
        fmt.Printf("2**%d = %d\n", i, v)
    }

    for i := range pow {
        pow[i] = 1 << uint(i) // == 2**i
    }
    for _, value := range pow {
        fmt.Printf("%d\n", value)
    }
}
  • You can skip the index or value by assigning to _.
  • If you only want the index, drop the , value entirely.

How do I check if a file exists in Java?

Don't use File constructor with String.
This may not work!
Instead of this use URI:

File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) { 
    // to do
}

How to wrap text of HTML button with fixed width?

I have found that a button works, but that you'll want to add style="height: 100%;" to the button so that it will show more than the first line on Safari for iPhone iOS 5.1.1

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

The only one reason why you get some error like that, it's because your node version is not compatible with your node-sass version.

So, make sure to checkout the documentation at here: https://www.npmjs.com/package/node-sass

Or this image below will be help you, what the node version can use the node-sass version.

enter image description here

For an example, if you're using node version 12 on your windows ("maybe"), then you should have to install the node-sass version 4.12.

npm install [email protected]

Yeah, like that. So now you only need to install the node-sass version recommended by the node-sass team with the nodes installed on your computer.

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Try this:

<div id="wrapper">
    <div class="float left">left</div>
    <div class="float right">right</div>
</div>

#wrapper {
   width:500px; 
   height:300px; 
   position:relative;
}

.float {
   background-color:black; 
   height:300px; 
   margin:0; 
   padding:0; 
   color:white;
}

.left {
   background-color:blue; 
   position:fixed; 
   width:400px;
}

.right {
   float:right; 
   width:100px;
}

jsFiddle: http://jsfiddle.net/khA4m

How to change Oracle default data pump directory to import dumpfile?

You can use the following command to update the DATA PUMP DIRECTORY path,

create or replace directory DATA_PUMP_DIR as '/u01/app/oracle/admin/MYDB/dpdump/';

For me data path correction was required as I have restored the my database from production to test environment.

Same command can be used to create a new DATA PUMP DIRECTORY name and path.

Sequelize.js delete query?

This example shows how to you promises instead of callback.

Model.destroy({
   where: {
      id: 123 //this will be your id that you want to delete
   }
}).then(function(rowDeleted){ // rowDeleted will return number of rows deleted
  if(rowDeleted === 1){
     console.log('Deleted successfully');
   }
}, function(err){
    console.log(err); 
});

Check this link out for more info http://docs.sequelizejs.com/en/latest/api/model/#destroyoptions-promiseinteger

Separators for Navigation

Simply use the separator image as a background image on the li.

To get it to only appear in between list items, position the image to the left of the li, but not on the first one.

For example:

#nav li + li {
    background:url('seperator.gif') no-repeat top left;
    padding-left: 10px
}

This CSS adds the image to every list item that follows another list item - in other words all of them but the first.

NB. Be aware the adjacent selector (li + li) doesn't work in IE6, so you will have to just add the background image to the conventional li (with a conditional stylesheet) and perhaps apply a negative margin to one of the edges.

Make a link open a new window (not tab)

That will open a new window, not tab (with JavaScript, but quite laconically):

<a href="print.html"  
    onclick="window.open('print.html', 
                         'newwindow', 
                         'width=300,height=250'); 
              return false;"
 >Print</a>

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Is it possible to format an HTML tooltip (title attribute)?

No. But there are other options out there like Overlib, and jQuery that allow you this freedom.

Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your <head>).

Get text from DataGridView selected cells

or, we can use something like this

dim i = dgv1.CurrentCellAddress.X
dim j = dgv1.CurrentCellAddress.Y
MsgBox(dgv1.Item(i,j).Value.ToString())

Regex match one of two words

This will do:

/^(apple|banana)$/

to exclude from captured strings (e.g. $1,$2):

(?:apple|banana)

How to check if a line is blank using regex

Full credit to bchr02 for this answer. However, I had to modify it a bit to catch the scenario for lines that have */ (end of comment) followed by an empty line. The regex was matching the non empty line with */.

New: (^(\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm

All I did is add ^ as second character to signify the start of line.

PHP Pass by reference in foreach

I had to spend a few hours to figure out why a[3] is changing on each iteration. This is the explanation at which I arrived.

There are two types of variables in PHP: normal variables and reference variables. If we assign a reference of a variable to another variable, the variable becomes a reference variable.

for example in

$a = array('zero', 'one', 'two', 'three');

if we do

$v = &$a[0]

the 0th element ($a[0]) becomes a reference variable. $v points towards that variable; therefore, if we make any change to $v, it will be reflected in $a[0] and vice versa.

now if we do

$v = &$a[1]

$a[1] will become a reference variable and $a[0] will become a normal variable (Since no one else is pointing to $a[0] it is converted to a normal variable. PHP is smart enough to make it a normal variable when no one else is pointing towards it)

This is what happens in the first loop

foreach ($a as &$v) {

}

After the last iteration $a[3] is a reference variable.

Since $v is pointing to $a[3] any change to $v results in a change to $a[3]

in the second loop,

foreach ($a as $v) {
  echo $v.'-'.$a[3].PHP_EOL;
}

in each iteration as $v changes, $a[3] changes. (because $v still points to $a[3]). This is the reason why $a[3] changes on each iteration.

In the iteration before the last iteration, $v is assigned the value 'two'. Since $v points to $a[3], $a[3] now gets the value 'two'. Keep this in mind.

In the last iteration, $v (which points to $a[3]) now has the value of 'two', because $a[3] was set to two in the previous iteration. two is printed. This explains why 'two' is repeated when $v is printed in the last iteration.

What is the difference between hg forget and hg remove?

A file can be tracked or not, you use hg add to track a file and hg remove or hg forget to un-track it. Using hg remove without flags will both delete the file and un-track it, hg forget will simply un-track it without deleting it.

Transparent background in JPEG image

You can't make a JPEG image transparent. You should use a format that allows transparency, like GIF or PNG.

Paint will open these files, but AFAIK it'll erase transparency if you edit the file. Use some other application like Paint.NET (it's free).

Edit: since other people have mentioned it: you can convert JPEG images into PNG, in any editor that's capable of working with both types.

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

Change URL and redirect using jQuery

var temp="/yourapp/";
$(location).attr('href','http://abcd.com'+temp);

Try this... used as an alternative

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

This error typically comes up when the necessary port is taken by another program.

You said that you have changed the HTTP connector port from 8080 to 8081 so the two Tomcats do not clash, but have you also changed the <Server port="..." in tomcat/conf/server.xml to be different between your Tomcats?

Are there any other connectors ports which may possibly clash?

Synchronous request in Node.js

Another possibility is to set up a callback that tracks completed tasks:

function onApiResults(requestId, response, results) {
    requestsCompleted |= requestId;

    switch(requestId) {
        case REQUEST_API1:
            ...
            [Call API2]
            break;
        case REQUEST_API2:
            ...
            [Call API3]
            break;
        case REQUEST_API3:
            ...
            break;
    }

    if(requestId == requestsNeeded)
        response.end();
}

Then simply assign an ID to each and you can set up your requirements for which tasks must be completed before closing the connection.

const var REQUEST_API1 = 0x01;
const var REQUEST_API2 = 0x02;
const var REQUEST_API3 = 0x03;
const var requestsNeeded = REQUEST_API1 | REQUEST_API2 | REQUEST_API3;

Okay, it's not pretty. It is just another way to make sequential calls. It's unfortunate that NodeJS does not provide the most basic synchronous calls. But I understand what the lure is to asynchronicity.

"Invalid form control" only in Google Chrome

Chrome wants to focus on a control that is required but still empty so that it can pop up the message 'Please fill out this field'. However, if the control is hidden at the point that Chrome wants to pop up the message, that is at the time of form submission, Chrome can't focus on the control because it is hidden, therefore the form won't submit.

So, to get around the problem, when a control is hidden by javascript, we also must remove the 'required' attribute from that control.

Android Pop-up message

Use This And Call This In OnCreate Method In Which Activity You Want

public void popupMessage(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("No Internet Connection. Check Your Wifi Or enter code hereMobile Data.");
        alertDialogBuilder.setIcon(R.drawable.ic_no_internet);
        alertDialogBuilder.setTitle("Connection Failed");
        alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d("internet","Ok btn pressed");
                finishAffinity();
                System.exit(0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

std::string length() and size() member functions

Ruby's just the same, btw, offering both #length and #size as synonyms for the number of items in arrays and hashes (C++ only does it for strings).

Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

refresh leaflet map: map container is already initialized

I had the same problem on angular when switching page. I had to add this code before leaving the page to make it works:

    $scope.$on('$locationChangeStart', function( event ) {
    if(map != undefined)
    {
      map.remove();
      map = undefined
      document.getElementById('mapLayer').innerHTML = "";
    }
});

Without document.getElementById('mapLayer').innerHTML = "" the map was not displayed on the next page.

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

Force browser to clear cache

I implemented this simple solution that works for me (not yet on production environment):

function verificarNovaVersio() {
    var sVersio = localStorage['gcf_versio'+ location.pathname] || 'v00.0.0000';
    $.ajax({
        url: "./versio.txt"
        , dataType: 'text'
        , cache: false
        , contentType: false
        , processData: false
        , type: 'post'
     }).done(function(sVersioFitxer) {
        console.log('Versió App: '+ sVersioFitxer +', Versió Caché: '+ sVersio);
        if (sVersio < (sVersioFitxer || 'v00.0.0000')) {
            localStorage['gcf_versio'+ location.pathname] = sVersioFitxer;
            location.reload(true);
        }
    });
}

I've a little file located where the html are:

"versio.txt":

v00.5.0014

This function is called in all of my pages, so when loading it checks if the localStorage's version value is lower than the current version and does a

location.reload(true);

...to force reload from server instead from cache.

(obviously, instead of localStorage you can use cookies or other persistent client storage)

I opted for this solution for its simplicity, because only mantaining a single file "versio.txt" will force the full site to reload.

The queryString method is hard to implement and is also cached (if you change from v1.1 to a previous version will load from cache, then it means that the cache is not flushed, keeping all previous versions at cache).

I'm a little newbie and I'd apreciate your professional check & review to ensure my method is a good approach.

Hope it helps.

How to revert to origin's master branch's version of file

If you didn't commit it to the master branch yet, its easy:

  • get off the master branch (like git checkout -b oops/fluke/dang)
  • commit your changes there (like git add -u; git commit;)
  • go back the master branch (like git checkout master)

Your changes will be saved in branch oops/fluke/dang; master will be as it was.

How to bind RadioButtons to an enum?

For the EnumToBooleanConverter answer: Instead of returning DependencyProperty.UnsetValue consider returning Binding.DoNothing for the case where the radio button IsChecked value becomes false. The former indicates a problem (and might show the user a red rectangle or similar validation indicators) while the latter just indicates that nothing should be done, which is what is wanted in that case.

http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convertback.aspx http://msdn.microsoft.com/en-us/library/system.windows.data.binding.donothing.aspx

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

MySQL LEFT JOIN 3 tables

SELECT p.*, f.Fear
FROM Persons p
LEFT JOIN Person_Fear pf ON pf.PersonID = p.PersonID
LEFT JOIN Fears f ON f.FearID = pf.FearID
ORDER BY p.PersonID

  1. You need to select from the Persons table to ensure you generate a row for every person, whether they have fears or not.
  2. Then you can left join Person_Fear to every person, which will just be NULL if they don't have any entries (as you want).
  3. Finally, you left join Fears on Person_Fear so that you can select the name of the fear.
  4. Optionally, add an order so that each person has all their fears listed together, even if they were added to the Person_Fear table at different times.

iterrows pandas get next rows value

I would use shift() function as follows:

df['value_1'] = df.value.shift(-1)
[print(x) for x in df.T.unstack().dropna(how = 'any').values];

which produces

AA
BB
BB
CC
CC

This is how the code above works:

Step 1) Use shift function

df['value_1'] = df.value.shift(-1)
print(df)

produces

value value_1
0    AA      BB
1    BB      CC
2    CC     NaN

step 2) Transpose:

df = df.T
print(df)

produces:

          0   1    2
value    AA  BB   CC
value_1  BB  CC  NaN

Step 3) Unstack:

df = df.unstack()
print(df)

produces:

0  value       AA
   value_1     BB
1  value       BB
   value_1     CC
2  value       CC
   value_1    NaN
dtype: object

Step 4) Drop NaN values

df = df.dropna(how = 'any')
print(df)

produces:

0  value      AA
   value_1    BB
1  value      BB
   value_1    CC
2  value      CC
dtype: object

Step 5) Return a Numpy representation of the DataFrame, and print value by value:

df = df.values
[print(x) for x in df];

produces:

AA
BB
BB
CC
CC

How to insert a text at the beginning of a file?

To insert just a newline:

sed '1i\\'

Converting Secret Key into a String and Vice Versa

Converting SecretKeySpec to String and vice-versa: you can use getEncoded() method in SecretKeySpec which will give byteArray, from that you can use encodeToString() to get string value of SecretKeySpec in Base64 object.

While converting SecretKeySpec to String: use decode() in Base64 will give byteArray, from that you can create instance for SecretKeySpec with the params as the byteArray to reproduce your SecretKeySpec.

String mAesKey_string;
SecretKeySpec mAesKey= new SecretKeySpec(secretKey.getEncoded(), "AES");

//SecretKeySpec to String 
    byte[] byteaes=mAesKey.getEncoded();
    mAesKey_string=Base64.encodeToString(byteaes,Base64.NO_WRAP);

//String to SecretKeySpec
    byte[] aesByte = Base64.decode(mAesKey_string, Base64.NO_WRAP);
    mAesKey= new SecretKeySpec(aesByte, "AES");

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Query for documents where array size is greater than 1

You can use aggregate, too:

db.accommodations.aggregate(
[
     {$project: {_id:1, name:1, zipcode:1, 
                 size_of_name: {$size: "$name"}
                }
     },
     {$match: {"size_of_name": {$gt: 1}}}
])

// you add "size_of_name" to transit document and use it to filter the size of the name

How to change a table name using an SQL query?

In MySQL :

RENAME TABLE template_function TO business_function;

How to use sbt from behind proxy?

I found that starting IntelliJ IDEA from terminal let me connect and download over the internet. To start from terminal, type in:

$ idea

Bootstrap 3 Slide in Menu / Navbar on Mobile

Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:

_x000D_
_x000D_
$('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
  $navMenuCont = $($(this).data('target'));_x000D_
  $navMenuCont.animate({_x000D_
    'width': 'toggle'_x000D_
  }, 350);_x000D_
  $(".menu-overlay").fadeIn(500);_x000D_
});_x000D_
_x000D_
$(".menu-overlay").click(function(event) {_x000D_
  $(".navbar-toggle").trigger("click");_x000D_
  $(".menu-overlay").fadeOut(500);_x000D_
});_x000D_
_x000D_
// if ($(window).width() >= 767) {_x000D_
//     $('ul.nav li.dropdown').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
//     $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
_x000D_
//     $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
//         event.preventDefault();_x000D_
//         event.stopPropagation();_x000D_
//         $(this).parent().siblings().removeClass('open');_x000D_
//         $(this).parent().toggleClass('open');_x000D_
//         $('b', this).toggleClass("caret caret-up");_x000D_
//     });_x000D_
// }_x000D_
_x000D_
// $(window).resize(function() {_x000D_
//     if( $(this).width() >= 767) {_x000D_
//         $('ul.nav li.dropdown').hover(function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//         }, function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//         });_x000D_
//     }_x000D_
// });_x000D_
_x000D_
var windowWidth = $(window).width();_x000D_
if (windowWidth > 767) {_x000D_
  // $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
  //     event.preventDefault();_x000D_
  //     event.stopPropagation();_x000D_
  //     $(this).parent().siblings().removeClass('open');_x000D_
  //     $(this).parent().toggleClass('open');_x000D_
  //     $('b', this).toggleClass("caret caret-up");_x000D_
  // });_x000D_
_x000D_
  $('ul.nav li.dropdown').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
  $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
if (windowWidth < 767) {_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
_x000D_
// $('.dropdown a').append('Some text');
_x000D_
@media only screen and (max-width: 767px) {_x000D_
  #slide-navbar-collapse {_x000D_
    position: fixed;_x000D_
    top: 0;_x000D_
    left: 15px;_x000D_
    z-index: 999999;_x000D_
    width: 280px;_x000D_
    height: 100%;_x000D_
    background-color: #f9f9f9;_x000D_
    overflow: auto;_x000D_
    bottom: 0;_x000D_
    max-height: inherit;_x000D_
  }_x000D_
  .menu-overlay {_x000D_
    display: none;_x000D_
    background-color: #000;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    opacity: 0.5;_x000D_
    filter: alpha(opacity=50);_x000D_
    /* IE7 & 8 */_x000D_
    position: fixed;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    z-index: 49;_x000D_
  }_x000D_
  .navbar-fixed-top {_x000D_
    position: initial !important;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu {_x000D_
    background-color: #ffffff;_x000D_
  }_x000D_
  ul.nav.navbar-nav li {_x000D_
    border-bottom: 1px solid #eee;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
  .navbar-nav .open .dropdown-menu>li>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
}_x000D_
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
  margin-top: -1px;_x000D_
}_x000D_
_x000D_
li.dropdown a {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 5px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 10px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
ul.dropdown-menu li {_x000D_
  border-bottom: 1px solid #eee;_x000D_
}_x000D_
_x000D_
.dropdown-menu {_x000D_
  padding: 0px;_x000D_
  margin: 0px;_x000D_
  border: none !important;_x000D_
}_x000D_
_x000D_
li.dropdown.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
li.dropdown>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
.navbar-default .navbar-nav>li>a {_x000D_
  font-weight: bold !important;_x000D_
  padding: 10px 20px 10px 15px;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 9px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
@media (min-width: 767px) {_x000D_
  li.dropdown-submenu>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
  li.dropdown>a:before {_x000D_
    content: "\f107";_x000D_
    font-family: FontAwesome;_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 12px;_x000D_
    font-size: 15px;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
  <head>_x000D_
    <title>Bootstrap Example</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <nav class="navbar navbar-default navbar-fixed-top">_x000D_
      <div class="container-fluid">_x000D_
        <!-- Brand and toggle get grouped for better mobile display -->_x000D_
        <div class="navbar-header">_x000D_
          <button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
          <a class="navbar-brand" href="#">Brand</a>_x000D_
        </div>_x000D_
        <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
        <div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
          <ul class="nav navbar-nav">_x000D_
            <li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
                <li><a href="#">One more separated link</a></li>_x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
              </ul>_x000D_
            </li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
          </ul>_x000D_
          <ul class="nav navbar-nav navbar-right">_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.navbar-collapse -->_x000D_
      </div>_x000D_
      <!-- /.container-fluid -->_x000D_
    </nav>_x000D_
    <div class="menu-overlay"></div>_x000D_
    <div class="col-md-12">_x000D_
      <h1>Resize the window to see the result</h1>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference JS fiddle

jQuery AJAX file upload PHP

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$name;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" height="100" width="100" />';
}

Understanding Fragment's setRetainInstance(boolean)

SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.

Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html

How to enable native resolution for apps on iPhone 6 and 6 Plus?

If you are using asset catalog, and have multiple targets both using same asset catalog file, be sure that this file has checked both targets in the right panel in xcode.

That was my problem.

enter image description here

Django: OperationalError No Such Table

If anyone finds that any of the suggested:

python manage.py makemigrations

python manage.py migrate

python manage.py migrate --run-syncdb

fail, you may need to add a folder named "migrations" inside the app directory, and create an empty __init__.py file.

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

How do I diff the same file between two different commits on the same branch?

Just another way to use Git's awesomeness...

git difftool HEAD HEAD@{N} /PATH/FILE.ext

How to upgrade docker container after its image changed

Update

This is mainly to query the container not to update as building images is the way to be done

I had the same issue so I created docker-run, a very simple command-line tool that runs inside a docker container to update packages in other running containers.

It uses docker-py to communicate with running docker containers and update packages or run any arbitrary single command

Examples:

docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run exec

by default this will run date command in all running containers and return results but you can issue any command e.g. docker-run exec "uname -a"

To update packages (currently only using apt-get):

docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run update

You can create and alias and use it as a regular command line e.g.

alias docker-run='docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run'

Rails: How can I rename a database column in a Ruby on Rails migration?

You have two ways to do this:

  1. In this type it automatically runs the reverse code of it, when rollback.

    def change
      rename_column :table_name, :old_column_name, :new_column_name
    end
    
  2. To this type, it runs the up method when rake db:migrate and runs the down method when rake db:rollback:

    def self.up
      rename_column :table_name, :old_column_name, :new_column_name
    end
    
    def self.down
      rename_column :table_name,:new_column_name,:old_column_name
    end
    

file_get_contents behind a proxy?

There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.

function file_get_contents_proxy($url,$proxy){

    // Create context stream
    $context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
    $context = stream_context_create($context_array);

    // Use context stream with file_get_contents
    $data = file_get_contents($url,false,$context);

    // Return data via proxy
    return $data;

}

Symfony2 : How to get form validation errors after binding the request to the form

For Symfony 2.1 onwards for use with Twig error display I altered the function to add a FormError instead of simply retrieving them, this way you have more control over errors and do not have to use error_bubbling on each individual input. If you do not set it in the manner below {{ form_errors(form) }} will remain blank:

/**
 * @param \Symfony\Component\Form\Form $form
 *
 * @return void
 */
private function setErrorMessages(\Symfony\Component\Form\Form $form) {      

    if ($form->count() > 0) {
        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                if( isset($this->getErrorMessages($child)[0]) ) {
                    $error = new FormError( $this->getErrorMessages($child)[0] );
                    $form->addError($error);
                }
            }
        }
    }

}

Import a custom class in Java

Import by using the import keyword:

import package.myclass;

But since it's the default package and same, you just create a new instance like:

elf ob = new elf(); //Instance of elf class

How to know the git username and email saved during configuration?

List all variables set in the config file, along with their values.

git config --list

If you are new to git then use the following commands to set a user name and email address.

Set user name

git config --global user.name "your Name"

Set user email

git config --global user.email "[email protected]"

Check user name

git config user.name

Check user email

git config user.email

Real escape string and PDO

PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.

Here is an excerpt from the PHP website:

<?php
    $conn = new PDO('sqlite:/home/lynn/music.sql3');

    /* Simple string */
    $string = 'Nice';
    print "Unquoted string: $string\n";
    print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above code will output:

Unquoted string: Nice
Quoted string: 'Nice'

setting y-axis limit in matplotlib

Try this . Works for subplots too .

axes = plt.gca()
axes.set_xlim([xmin,xmax])
axes.set_ylim([ymin,ymax])

Changing nav-bar color after scrolling?

I've recently done it slightly different to some of the examples above so thought I'd share, albeit very late!

Firstly the HTML, note there is only one class within the header:

<body>

<header class="GreyHeader">
</header>


</body>

And the CSS:

body {
height: 3000px;
}

.GreyHeader{
height: 200px; 
background-color: rgba(107,107,107,0.66);
position: fixed;
top:200;
width: 100%;

}

.FireBrickRed {
height: 100px;
background-color: #b22222;
position: fixed;
top:200;
width: 100%;
}

.transition {
  -webkit-transition: height 2s; /* For Safari 3.1 to 6.0 */
  transition: height 2s;
}

The html uses only the class .greyHeader but within the CSS I have created another class to call once the scroll has reached a certain point from the top:

$(function() {
    var header = $(".GreyHeader");
    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();

        if (scroll >= 500) {
            header.removeClass('GreyHeader').addClass("FireBrickRed ");
            header.addClass("transition");
        } else {
            header.removeClass("FireBrickRed ").addClass('GreyHeader');
            header.addClass("transition");
        }
    });
});

check this fiddle: https://jsfiddle.net/29y64L7d/1/

Change the icon of the exe file generated from Visual Studio 2010

I found it easier to edit the project file directly e.g. YourApp.csproj.

You can do this by modifying ApplicationIcon property element:

<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>

Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.

Calling a function on bootstrap modal open

Bootstrap modal exposes events. Listen for the the shown event like this

$('#my-modal').on('shown', function(){
  // code here
});

close fxml window by code, javafx

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent we) {                        
        Platform.setImplicitExit(false);
        stage.close();
    }
});

It is equivalent to hide. So when you are going to open it next time, you just check if the stage object is exited or not. If it is exited, you just show() i.e. (stage.show()) call. Otherwise, you have to start the stage.

Get all directories within directory nodejs

Alternatively, if you are able to use external libraries, you can use filehound. It supports callbacks, promises and sync calls.

Using promises:

const Filehound = require('filehound');

Filehound.create()
  .path("MyFolder")
  .directory() // only search for directories
  .find()
  .then((subdirectories) => {
    console.log(subdirectories);
  });

Using callbacks:

const Filehound = require('filehound');

Filehound.create()
  .path("MyFolder")
  .directory()
  .find((err, subdirectories) => {
    if (err) return console.error(err);

    console.log(subdirectories);
  });

Sync call:

const Filehound = require('filehound');

const subdirectories = Filehound.create()
  .path("MyFolder")
  .directory()
  .findSync();

console.log(subdirectories);

For further information (and examples), check out the docs: https://github.com/nspragg/filehound

Disclaimer: I'm the author.

Java: print contents of text file to screen

For those new to Java and wondering why Jiri's answer doesn't work, make sure you do what he says and handle the exception or else it won't compile. Here's the bare minimum:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("test.txt"));
        for (String line; (line = br.readLine()) != null;) {
            System.out.print(line);
        }
        br.close()
    }
}

How to use pip with python 3.4 on windows?

Assuming you don't have any other Python installations, you should be able to do python -m pip after a default installation. Something like the following should be in your system path:

C:\Python34\Scripts

This would obviously be different, if you installed Python in a different location.

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

How to get POSTed JSON in Flask?

First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here.

You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation:

This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see is_json()), otherwise it will be None.

You can tell request.get_json() to skip the content type requirement by passing it the force=True keyword argument.

Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.

Change GridView row color based on condition

\\loop throgh all rows of the grid view  

if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value1")
{
   GridView1.Rows[i - 1].ForeColor = Color.Black;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value2")
{
   GridView1.Rows[i - 1].ForeColor = Color.Blue;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value3")
{
   GridView1.Rows[i - 1].ForeColor = Color.Red;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value4")
{
   GridView1.Rows[i - 1].ForeColor = Color.Green;
}

Freeing up a TCP/IP port?

As the others have said, you'll have to kill all processes that are listening on that port. The easiest way to do that would be to use the fuser(1) command. For example, to see all of the processes listening for http requests on port 80 (run as root or use sudo):

# fuser 80/tcp

If you want to kill them, then just add the -k option.

Pass array to MySQL stored routine

I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my similar problem. Here I try to just use LOCATE() just once per delimiter.

-- *****************************************************************************
-- test_PVreplace

DROP FUNCTION IF EXISTS test_PVreplace;

delimiter //
CREATE FUNCTION test_PVreplace (
   str TEXT,   -- String to do search'n'replace on
   pv TEXT     -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
   )
   RETURNS TEXT

-- Replace specific tags with specific values.

sproc:BEGIN
   DECLARE idx INT;
   DECLARE idx0 INT DEFAULT 1;   -- 1-origined, not 0-origined
   DECLARE len INT;
   DECLARE sPV TEXT;
   DECLARE iPV INT;
   DECLARE sP TEXT;
   DECLARE sV TEXT;

   -- P/V string *must* end with a delimiter.

   IF (RIGHT (pv, 1) <> '|') THEN
      SET pv = CONCAT (pv, '|');
      END IF;

   -- Find all the P/V pairs.

   SELECT LOCATE ('|', pv, idx0) INTO idx;
   WHILE (idx > 0) DO
      SET len = idx - idx0;
      SELECT SUBSTRING(pv, idx0, len) INTO sPV;

      -- Found a P/V pair.  Break it up.

      SELECT LOCATE ('=', sPV) INTO iPV;
      IF (iPV = 0) THEN
         SET sP = sPV;
         SET sV = '';
      ELSE
         SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
         SELECT SUBSTRING(sPV, iPV+1) INTO sV;
         END IF;

      -- Do the substitution(s).

      SELECT REPLACE (str, sP, sV) INTO str;

      -- Do next P/V pair.

      SET idx0 = idx + 1;
      SELECT LOCATE ('|', pv, idx0) INTO idx;
      END WHILE;
   RETURN (str);
END//
delimiter ;

SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

Java abstract interface

It isn't necessary. It's a quirk of the language.

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

How to delete a workspace in Eclipse?

It's possible to remove the workspace in Eclipse without much complications. The options are available under Preferences->General->Startup and Shutdown->Workspaces.

Note that this does not actually delete the files from the system, it simply removes it from the list of suggested workspaces. It changes the org.eclipse.ui.ide.prefs file in Jon's answer from within Eclipse.

Stop an input field in a form from being submitted

You could insert input fields without "name" attribute:

<input type="text" id="in-between" />

Or you could simply remove them once the form is submitted (in jQuery):

$("form").submit(function() {
   $(this).children('#in-between').remove();
});

List names of all tables in a SQL Server 2012 schema

Your should really use the INFORMATION_SCHEMA views in your database:

USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES

You can then filter that by table schema and/or table type, e.g.

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

How to select a node of treeview programmatically in c#?

TreeViewItem tempItem = new TreeViewItem();
TreeViewItem tempItem1 = new TreeViewItem(); 
tempItem =  (TreeViewItem) treeView1.Items.GetItemAt(0);    // Selecting the first of the top level nodes
tempItem1 = (TreeViewItem)tempItem.Items.GetItemAt(0);      // Selecting the first child of the first first level node
SelectedCategoryHeaderString = tempItem.Header.ToString();  // gets the header for the first top level node
SelectedCategoryHeaderString = tempItem1.Header.ToString(); // gets the header for the first child node of the first top level node
tempItem.IsExpanded = true;         //  will expand the first node

Can you split a stream into two streams?

I stumbled across this question to my self and I feel that a forked stream has some use cases that could prove valid. I wrote the code below as a consumer so that it does not do anything but you could apply it to functions and anything else you might come across.

class PredicateSplitterConsumer<T> implements Consumer<T>
{
  private Predicate<T> predicate;
  private Consumer<T>  positiveConsumer;
  private Consumer<T>  negativeConsumer;

  public PredicateSplitterConsumer(Predicate<T> predicate, Consumer<T> positive, Consumer<T> negative)
  {
    this.predicate = predicate;
    this.positiveConsumer = positive;
    this.negativeConsumer = negative;
  }

  @Override
  public void accept(T t)
  {
    if (predicate.test(t))
    {
      positiveConsumer.accept(t);
    }
    else
    {
      negativeConsumer.accept(t);
    }
  }
}

Now your code implementation could be something like this:

personsArray.forEach(
        new PredicateSplitterConsumer<>(
            person -> person.getDateOfBirth().isPresent(),
            person -> System.out.println(person.getName()),
            person -> System.out.println(person.getName() + " does not have Date of birth")));

How to enable CORS in flask

If you can't find your problem and you're code should work, it may be that your request is just reaching the maximum of time heroku allows you to make a request. Heroku cancels requests if it takes more than 30 seconds.

Reference: https://devcenter.heroku.com/articles/request-timeout

How to sum a list of integers with java streams?

From the docs

Reduction operations A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, called reduce() and collect(), as well as multiple specialized reduction forms such as sum(), max(), or count().

Of course, such operations can be readily implemented as simple sequential loops, as in:

int sum = 0;
for (int x : numbers) {
   sum += x;
}

However, there are good reasons to prefer a reduce operation over a mutative accumulation such as the above. Not only is a reduction "more abstract" -- it operates on the stream as a whole rather than individual elements -- but a properly constructed reduce operation is inherently parallelizable, so long as the function(s) used to process the elements are associative and stateless. For example, given a stream of numbers for which we want to find the sum, we can write:

int sum = numbers.stream().reduce(0, (x,y) -> x+y);

or:

int sum = numbers.stream().reduce(0, Integer::sum);

These reduction operations can run safely in parallel with almost no modification:

int sum = numbers.parallelStream().reduce(0, Integer::sum);

So, for a map you would use:

integers.values().stream().mapToInt(i -> i).reduce(0, (x,y) -> x+y);

Or:

integers.values().stream().reduce(0, Integer::sum);

What does android:layout_weight mean?

As the name suggests, Layout weight specifies what amount or percentage of space a particular field or widget should occupy the screen space.
If we specify weight in horizontal orientation, then we must specify layout_width = 0px.
Similarly, If we specify weight in vertical orientation, then we must specify layout_height = 0px.

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

Gradle finds wrong JAVA_HOME even though it's correctly set

In my Ubuntu, I have a headache for 2 days on this issue.

Step 1. Type on the terminal whereis java then it will display something like this

java: /usr/bin/java /etc/java /usr/share/java /usr/lib/jvm/java-8-openjdk-amd64/bin/java /usr/share/man/man1/java.1.gz

Step 2. Take note of the path: /usr/lib/jvm/java-8-openjdk-amd64/bin/java

exclude the bin/java

your JAVA_HOME = /usr/lib/jvm/java-8-openjdk-amd64

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

BEST solution if you ask me is this. This will save the file with the file name of your choice and automatically in HTML or in TXT at your choice with buttons.

Example:

_x000D_
_x000D_
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}

function addTextHTML()
{
    document.addtext.name.value = document.addtext.name.value + ".html"
}

function addTextTXT()
{
    document.addtext.name.value = document.addtext.name.value + ".txt"
}
_x000D_
<html>
  <head></head>
  <body>

    <form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">

    <textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea>
    <br>
    <input type="text" name="name" value="" placeholder="File Name">
    <input type="submit" onClick="addTextHTML();" value="Save As HTML">
    <input type="submit" onClick="addTexttxt();" value="Save As TXT">

    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

Draw text in OpenGL ES

In the OpenGL ES 2.0/3.0 you can also combining OGL View and Android's UI-elements:

public class GameActivity extends AppCompatActivity {
    private SurfaceView surfaceView;
    @Override
    protected void onCreate(Bundle state) { 
        setContentView(R.layout.activity_gl);
        surfaceView = findViewById(R.id.oglView);
        surfaceView.init(this.getApplicationContext());
        ...
    } 
}

public class SurfaceView extends GLSurfaceView {
    private SceneRenderer renderer;
    public SurfaceView(Context context) {
        super(context);
    }

    public SurfaceView(Context context, AttributeSet attributes) {
        super(context, attributes);
    }

    public void init(Context context) {
        renderer = new SceneRenderer(context);
        setRenderer(renderer);
        ...
    }
}

Create layout activity_gl.xml:

<?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        tools:context=".activities.GameActivity">
    <com.app.SurfaceView
        android:id="@+id/oglView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <TextView ... />
    <TextView ... />
    <TextView ... />
</androidx.constraintlayout.widget.ConstraintLayout>

To update elements from the render thread, can use Handler/Looper.

How to save local data in a Swift app?

Using NSCoding and NSKeyedArchiver is another great option for data that's too complex for NSUserDefaults, but for which CoreData would be overkill. It also gives you the opportunity to manage the file structure more explicitly, which is great if you want to use encryption.

PHP multiline string with PHP

You cannot run PHP code within a string like that. It just doesn't work. As well, when you're "out" of PHP code (?>), any text outside of the PHP blocks is considered output anyway, so there's no need for the echo statement.

If you do need to do multiline output from with a chunk of PHP code, consider using a HEREDOC:

<?php

$var = 'Howdy';

echo <<<EOL
This is output
And this is a new line
blah blah blah and this following $var will actually say Howdy as well

and now the output ends
EOL;

alert a variable value

If you're using greasemonkey, it's possible the page isn't ready for the javascript yet. You may need to use window.onReady.

var inputs;

function doThisWhenReady() {
    inputs = document.getElementsByTagName('input');

    //Other code here...
}

window.onReady = doThisWhenReady;

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once.

In general, you use @BeforeClass when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass into @Before, but your test run may take longer. Note that the code marked @BeforeClass is run as static initializer, therefore it will run before the class instance of your test fixture is created.

In JUnit 5, the tags @BeforeEach and @BeforeAll are the equivalents of @Before and @BeforeClass in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

Access elements of parent window from iframe

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If you have msi installer open it with Orca (tool from Microsoft), table Property (rows UpgradeCode, ProductCode, Product version etc) or table Upgrade column Upgrade Code.

Try to find instller via registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall find required subkey and watch value InstallSource. Maybe along the way you'll be able to find the MSI file.

Adding elements to a C# array

What's abaut this one:

List<int> tmpList = intArry.ToList(); tmpList.Add(anyInt); intArry = tmpList.ToArray();

fatal error LNK1104: cannot open file 'kernel32.lib'

Add lib path of WindowsSdks in project->properties->Configuration Properties->VC++ Directories -> Library directories.

I added following path and error goes::

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib;

My system is Win-7, 64bit, VS 2013, .net framework 4.5

Is there a /dev/null on Windows?

Jon Skeet is correct. Here is the Nul Device Driver page in the Windows Embedded documentation (I have no idea why it's not somewhere else...).

Here is another:

Unlocking tables if thread is lost

With Sequel Pro:

Restarting the app unlocked my tables. It resets the session connection.

NOTE: I was doing this for a site on my local machine.

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

PHP - Get bool to echo false when false

This will print out boolean value as it is, instead of 1/0.

    $bool = false;

    echo json_encode($bool);   //false

What is the purpose of XSD files?

The xsd file is the schema of the xml file - it defines which elements may occur and their restrictions (like amount, order, boundaries, relationships,...)

Render HTML in React Native

React Native has updated the WebView component to allow for direct html rendering. Here's an example that works for me

var htmlCode = "<b>I am rendered in a <i>WebView</i></b>";

<WebView
  ref={'webview'}
  automaticallyAdjustContentInsets={false}
  style={styles.webView}
  html={htmlCode} />

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

None of these solutions really met my expectations. I wanted to subclass the TextField since I don't want to set the border manually all the time. I also wanted to change the border color e.g. for an error. So here's my solution with Anchors:

class CustomTextField: UITextField {

    var bottomBorder = UIView()

    override func awakeFromNib() {

            // Setup Bottom-Border

            self.translatesAutoresizingMaskIntoConstraints = false

            bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
            bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1) // Set Border-Color
            bottomBorder.translatesAutoresizingMaskIntoConstraints = false

            addSubview(bottomBorder)

            bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
            bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
            bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
            bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength

    }
}

---- Optional ----

To change the color add sth like this to the CustomTextField Class:

@IBInspectable var hasError: Bool = false {
    didSet {

        if (hasError) {

            bottomBorder.backgroundColor = UIColor.red

        } else {

            bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1)

        }

    }
}

And to trigger the Error call this after you created an instance of CustomTextField

textField.hasError = !textField.hasError

enter image description here

Hope it helps someone ;)

Counting repeated elements in an integer array

public class ArrayDuplicate {
private static Scanner sc;
static int totalCount = 0;

    public static void main(String[] args) {
        int n, num;
        sc = new Scanner(System.in);
        System.out.print("Enter the size of array: ");
        n =sc.nextInt();
        int[] a = new int[n];
        for(int i=0;i<n;i++){
            System.out.print("Enter the element at position "+i+": ");
            num = sc.nextInt();
            a[enter image description here][1][i]=num;
        }
        System.out.print("Elements in array are: ");
        for(int i=0;i<a.length;i++)
            System.out.print(a[i]+" ");
        System.out.println();
        duplicate(a);
        System.out.println("There are "+totalCount+" repeated numbers:");
    }

    public static void duplicate(int[] a){
        int j = 0,count, recount, temp;
        for(int i=0; i<a.length;i++){
            count = 0;
            recount = 0;
            j=i+1;
            while(j<a.length){
                if(a[i]==a[j])
                    count++;
                j++;
            }
            if(count>0){
                temp = a[i];
                for(int x=0;x<i;x++){
                    if(a[x]==temp)
                        recount++;
                }
                if(recount==0){                 
                    totalCount++;
                    System.out.println(+a[i]+" : "+count+" times");
                }   
            }

        }
    }

}

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.

You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.

There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.

That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.

This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)

Reset MySQL root password using ALTER USER statement after install on Mac

remember versions 5.7.23 and up - the user table doesn't has column password instead authentication string so below works while resetting password for a user.

update user set authentication_string=password('root') where user='root';

Why is Dictionary preferred over Hashtable in C#?

Since .NET Framework 3.5 there is also a HashSet<T> which provides all the pros of the Dictionary<TKey, TValue> if you need only the keys and no values.

So if you use a Dictionary<MyType, object> and always set the value to null to simulate the type safe hash table you should maybe consider switching to the HashSet<T>.

TypeScript and React - children type?

As a type that contains children, I'm using:

type ChildrenContainer = Pick<JSX.IntrinsicElements["div"], "children">

This children container type is generic enough to support all the different cases and also aligned with the ReactJS API.

So, for your example it would be something like:

const layout = ({ children }: ChildrenContainer) => (
    <Aux>
        <div>Toolbar, SideDrawer, Backdrop</div>
        <main>
            {children}
        </main>
    <Aux/>
)

How to search images from private 1.0 registry in docker?

So I know this is a rapidly changing field but (as of 2015-09-08) I found the following in the Docker Registry HTTP API V2:

Listing Repositories (link)

GET /v2/_catalog

Listing Image Tags (link)

GET /v2/<name>/tags/list

Based on that the following worked for me on a local registry (registry:2 IMAGE ID 1e847b14150e365a95d76a9cc6b71cd67ca89905e3a0400fa44381ecf00890e1 created on 2015-08-25T07:55:17.072):

$ curl -X GET http://localhost:5000/v2/_catalog
{"repositories":["ubuntu"]}
$ curl -X GET http://localhost:5000/v2/ubuntu/tags/list
{"name":"ubuntu","tags":["latest"]}

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

Android: set view style programmatically

For a new Button/TextView:

Button mMyButton = new Button(new ContextThemeWrapper(this, R.style.button_disabled), null, 0);

For an existing instance:

mMyButton.setTextAppearance(this, R.style.button_enabled);

For Image or layouts:

Image mMyImage = new ImageView(new ContextThemeWrapper(context, R.style.article_image), null, 0);

Key Presses in Python

There's a solution:

import pyautogui
for i in range(1000):
    pyautogui.typewrite("a")

How to compress a String in Java?

Huffman Coding might help, but only if you have a lot of frequent characters in your small String

jQuery + client-side template = "Syntax error, unrecognized expression"

You can use

var modal_template_html = $.trim($('#modal_template').html());
var template = $(modal_template_html);

Metadata file '.dll' could not be found

I saw this error because I had the following line in my code (looks like I was still thinking in SQL mode):

if(myVar is null)
    DoSomething();

Visual studio (2017) reported no errors at design or compile time however the project would not build and gave the "missing .dll" error. Upon changing the erroneous line to:

if(myVar == null)

The problem was resolved.