Programs & Examples On #Bulkinsert

Act of inserting multiple rows into a database simultaneously.

How to speed up insertion performance in PostgreSQL

In addition to excellent Craig Ringer's post and depesz's blog post, if you would like to speed up your inserts through ODBC (psqlodbc) interface by using prepared-statement inserts inside a transaction, there are a few extra things you need to do to make it work fast:

  1. Set the level-of-rollback-on-errors to "Transaction" by specifying Protocol=-1 in the connection string. By default psqlodbc uses "Statement" level, which creates a SAVEPOINT for each statement rather than an entire transaction, making inserts slower.
  2. Use server-side prepared statements by specifying UseServerSidePrepare=1 in the connection string. Without this option the client sends the entire insert statement along with each row being inserted.
  3. Disable auto-commit on each statement using SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(SQL_AUTOCOMMIT_OFF), 0);
  4. Once all rows have been inserted, commit the transaction using SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);. There is no need to explicitly open a transaction.

Unfortunately, psqlodbc "implements" SQLBulkOperations by issuing a series of unprepared insert statements, so that to achieve the fastest insert one needs to code up the above steps manually.

Import CSV file into SQL Server

The best, quickest and easiest way to resolve the comma in data issue is to use Excel to save a comma separated file after having set Windows' list separator setting to something other than a comma (such as a pipe). This will then generate a pipe (or whatever) separated file for you that you can then import. This is described here.

How to insert multiple rows from array using CodeIgniter framework?

Well, you don't want to execute 1000 query calls, but doing this is fine:

$stmt= array( 'array of statements' );
$query= 'INSERT INTO yourtable (col1,col2,col3) VALUES ';
foreach( $stmt AS $k => $v ) {
  $query.= '(' .$v. ')'; // NOTE: you'll have to change to suit
  if ( $k !== sizeof($stmt)-1 ) $query.= ', ';
}
$r= mysql_query($query);

Depending on your data source, populating the array might be as easy as opening a file and dumping the contents into an array via file().

SQL Bulk Insert with FIRSTROW parameter skips the following line

You can use the below snippet

BULK INSERT TextData
FROM 'E:\filefromabove.txt'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = '|',  --CSV field delimiter
ROWTERMINATOR = '\n',   --Use to shift the control to next row
ERRORFILE = 'E:\ErrorRows.csv',
TABLOCK
)

Bulk Insert to Oracle using .NET

The solution of Rob Stevenson-Legget is slow because he doesn't bind his values but he uses string.Format( ).

When you ask Oracle to execute a sql statement it starts with calculating the has value of this statement. After that it looks in a hash table whether it already knows this statement. If it already knows it statement it can retrieve its execution path from this hash table and execute this statement really fast because Oracle has executed this statement before. This is called the library cache and it doesn't work properly if you don't bind your sql statements.

For example don't do:

int n;

    for (n = 0; n < 100000; n ++)
    {
      mycommand.CommandText = String.Format("INSERT INTO [MyTable] ([MyId]) VALUES({0})", n + 1);
      mycommand.ExecuteNonQuery();
    }

but do:

      OracleParameter myparam = new OracleParameter();
      int n;

      mycommand.CommandText = "INSERT INTO [MyTable] ([MyId]) VALUES(?)";
      mycommand.Parameters.Add(myparam);

      for (n = 0; n < 100000; n ++)
      {
        myparam.Value = n + 1;
        mycommand.ExecuteNonQuery();
      }

Not using parameters can also cause sql injection.

Bulk Insert Correctly Quoted CSV File in SQL Server

I had the same problem, with data that only occasionally double-quotes some text. My solution is to let the BULK LOAD import the double-quotes, then run a REPLACE on the imported data.

For example:

bulk insert CodePoint_tbl from "F:\Data\Map\CodePointOpen\Data\CSV\ab.csv" with (FIRSTROW = 1, FIELDTERMINATOR = ',', ROWTERMINATOR='\n');

update CodePoint_tbl set Postcode = replace(Postcode,'"','') where charindex('"',Postcode) > 0

To make it less painful to write the REPLACE script, just copy and paste what you need from the results of something like this:

select C.ColID, C.[name] as Columnname into #Columns
from syscolumns C
join sysobjects T on C.id = T.id
where T.[name] = 'User_tbl'
order by 1;

declare @QUOTE char(1);
set @QUOTE = Char(39);
select 'Update User_tbl set '+ColumnName+'=replace('+ColumnName+','
 + @QUOTE + '"' + @QUOTE + ',' + @QUOTE + @QUOTE + ');
GO'
from #Columns
where ColID > 2
order by ColID;

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

How to Bulk Insert from XLSX file extension?

It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.

How do I temporarily disable triggers in PostgreSQL?

SET session_replication_role = replica; 

It doesn't work with PostgreSQL 9.4 on my Linux machine if i change a table through table editor in pgAdmin and works if i change table through ordinary query. Manual changes in pg_trigger table also don't work without server restart but dynamic query like on postgresql.nabble.com ENABLE / DISABLE ALL TRIGGERS IN DATABASE works. It could be useful when you need some tuning.

For example if you have tables in a particular namespace it could be:

create or replace function disable_triggers(a boolean, nsp character varying) returns void as
$$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_namespace n
        join pg_class c on c.relnamespace = n.oid and c.relhastriggers = true
        where n.nspname = nsp
    loop
        execute format('alter table %I %s trigger all', r.relname, act); 
    end loop;
end;
$$
language plpgsql;

If you want to disable all triggers with certain trigger function it could be:

create or replace function disable_trigger_func(a boolean, f character varying) returns void as
$$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_proc p 
        join pg_trigger t on t.tgfoid = p.oid
        join pg_class c on c.oid = t.tgrelid
        where p.proname = f
    loop
        execute format('alter table %I %s trigger all', r.relname, act); 
    end loop;
end;
$$
language plpgsql;

PostgreSQL documentation for system catalogs


There are another control options of trigger firing process:

ALTER TABLE ... ENABLE REPLICA TRIGGER ... - trigger will fire in replica mode only.

ALTER TABLE ... ENABLE ALWAYS TRIGGER ... - trigger will fire always (obviously)

mongodb: insert if not exists

1. Use Update.

Drawing from Van Nguyen's answer above, use update instead of save. This gives you access to the upsert option.

NOTE: This method overrides the entire document when found (From the docs)

var conditions = { name: 'borne' }   , update = { $inc: { visits: 1 }} , options = { multi: true };

Model.update(conditions, update, options, callback);

function callback (err, numAffected) {   // numAffected is the number of updated documents })

1.a. Use $set

If you want to update a selection of the document, but not the whole thing, you can use the $set method with update. (again, From the docs)... So, if you want to set...

var query = { name: 'borne' };  Model.update(query, ***{ name: 'jason borne' }***, options, callback)

Send it as...

Model.update(query, ***{ $set: { name: 'jason borne' }}***, options, callback)

This helps prevent accidentally overwriting all of your document(s) with { name: 'jason borne' }.

BULK INSERT with identity (auto-increment) column

My solution is to add the ID field as the LAST field in the table, thus bulk insert ignores it and it gets automatic values. Clean and simple ...

For instance, if inserting into a temp table:

CREATE TABLE #TempTable 
(field1 varchar(max), field2 varchar(max), ... 
ROW_ID int IDENTITY(1,1) NOT NULL)

Note that the ROW_ID field MUST always be specified as LAST field!

Cannot bulk load. Operating system error code 5 (Access is denied.)

Make sure the file you're using ('C:\Users\Michael\workspace\pydb\data\andrew.out.txt') is on the SQL server machine and not the client machine running MSSMS.

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.

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

It is possible to do everything you want. Aaron's answer was not quite complete.

His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.

The following code snippet grabs the first line of a file and inserts it into the table @Lines:

declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);

declare @Lines table (
    line varchar(8000)
);

declare @sql varchar(8000) = ' 
    create table #tmp (
        line varchar(8000)
    );

    bulk insert #tmp
        from '''+@filename+'''
        with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');

    select * from #tmp';

insert into @Lines
    exec(@sql);

select * from @lines

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

There is an alternative to using COPY, which is the multirow values syntax that Postgres supports. From the documentation:

INSERT INTO films (code, title, did, date_prod, kind) VALUES
    ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');

The above code inserts two rows, but you can extend it arbitrarily, until you hit the maximum number of prepared statement tokens (it might be $999, but I'm not 100% sure about that). Sometimes one cannot use COPY, and this is a worthy replacement for those situations.

Simple export and import of a SQLite database on Android

Import and Export of a SQLite database on Android

Here is my function for export database into device storage

private void exportDB(){
    String DatabaseName = "Sycrypter.db";
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "com.synnlabz.sycryptr" +"/databases/"+DatabaseName ;
    String backupDBPath = SAMPLE_DB_NAME;
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Exported !!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

Here is my function for import database from device storage into android application

private void importDB(){
    String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
    File sd = new File(dir);
    File data = Environment.getDataDirectory();
    FileChannel source = null;
    FileChannel destination = null;
    String backupDBPath = "/data/com.synnlabz.sycryptr/databases/Sycrypter.db";
    String currentDBPath = "Sycrypter.db";
    File currentDB = new File(sd, currentDBPath);
    File backupDB = new File(data, backupDBPath);

    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Imported !!", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

SQL select * from column where year = 2010

NB: Should you want the year to be based on some reference date, the code below calculates the dates for the between statement:

declare @referenceTime datetime = getutcdate()
select *
from myTable
where SomeDate 
    between dateadd(year, year(@referenceTime) - 1900, '01-01-1900')                        --1st Jan this year (midnight)
    and dateadd(millisecond, -3, dateadd(year, year(@referenceTime) - 1900, '01-01-1901'))  --31st Dec end of this year (just before midnight of the new year)

Similarly, if you're using a year value, swapping year(@referenceDate) for your reference year's value will work

declare @referenceYear int = 2010
select *
from myTable
where SomeDate 
    between dateadd(year,@referenceYear - 1900, '01-01-1900')                       --1st Jan this year (midnight)
    and dateadd(millisecond, -3, dateadd(year,@referenceYear - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)

jQuery Show-Hide DIV based on Checkbox Value

While this is old if someone comes across this again (via search). The correct answer with jQuery 1.7 onwards is now:

$('.pChk').click(function() {
    if( $(this).is(':checked')) {
        $("#ProjectListButton").show();
    } else {
        $("#ProjectListButton").hide();
    }
}); 

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

How to clamp an integer to some range?

Avoid writing functions for such small tasks, unless you apply them often, as it will clutter up your code.

for individual values:

min(clamp_max, max(clamp_min, value))

for lists of values:

map(lambda x: min(clamp_max, max(clamp_min, x)), values)

Python: IndexError: list index out of range

I think you mean to put the rolling of the random a,b,c, etc within the loop:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.

That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).

Difference between static and shared libraries?

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.

Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].

There are advantages and disadvantages in each method:

  • Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

  • Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.

Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.

Automatic login script for a website on windows machine?

I used @qwertyjones's answer to automate logging into Oracle Agile with a public password.

I saved the login page as index.html, edited all the href= and action= fields to have the full URL to the Agile server.

The key <form> line needed to change from

<form autocomplete="off" name="MainForm" method="POST"
 action="j_security_check" 
 onsubmit="return false;" target="_top">

to

<form autocomplete="off" name="MainForm" method="POST"
 action="http://my.company.com:7001/Agile/default/j_security_check"   
 onsubmit="return false;" target="_top">

I also added this snippet to the end of the <body>

<script>
function checkCookiesEnabled(){ return true; }
document.MainForm.j_username.value = "joeuser";
document.MainForm.j_password.value = "abcdef";
submitLoginForm();
</script> 

I had to disable the cookie check by redefining the function that did the check, because I was hosting this from XAMPP and I didn't want to deal with it. The submitLoginForm() call was inspired by inspecting the keyPressEvent() function.

How is "mvn clean install" different from "mvn install"?

clean is its own build lifecycle phase (which can be thought of as an action or task) in Maven. mvn clean install tells Maven to do the clean phase in each module before running the install phase for each module.

What this does is clear any compiled files you have, making sure that you're really compiling each module from scratch.

PHP: How to remove specific element from an array?

$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
        if ($value!=$remove) {
        echo $value.'<br/>';
                continue;
        }
}

Get first line of a shell command's output

I would use:

awk 'FNR <= 1' file_*.txt

As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1 may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i' to 'FNR <= i' allows to obtain the first i lines.

For example, if you have n files named file_1.txt, ... file_n.txt:

awk 'FNR <= 1' file_*.txt

hello
...
bye

But with head wildcards print the name of the file:

head -1 file_*.txt

==> file_1.csv <==
hello
...
==> file_n.csv <==
bye

Is Java's assertEquals method reliable?

In a nutshell - you can have two String objects that contain the same characters but are different objects (in different memory locations). The == operator checks to see that two references are pointing to the same object (memory location), but the equals() method checks if the characters are the same.

Usually you are interested in checking if two Strings contain the same characters, not whether they point to the same memory location.

c++ custom compare function for std::sort()

Your comparison function is not even wrong.

Its arguments should be the type stored in the range, i.e. std::pair<K,V>, not const void*.

It should return bool not a positive or negative value. Both (bool)1 and (bool)-1 are true so your function says every object is ordered before every other object, which is clearly impossible.

You need to model the less-than operator, not strcmp or memcmp style comparisons.

See StrictWeakOrdering which describes the properties the function must meet.

How do I get the path of the current executed file in Python?

import os
current_file_path=os.path.dirname(os.path.realpath('__file__'))

Unity Scripts edited in Visual studio don't provide autocomplete

This page helped me fix the issue.

Fix for Unity disconnected from Visual Studio

enter image description here

In the Unity Editor, select the Edit > Preferences menu..

Select the External Tools tab on the left.

Select unity version from drop down list on the right

Click regenerate Files

You Done

How can I switch views programmatically in a view controller? (Xcode, iPhone)

#import "YourViewController.h"

To push a view including the navigation bar and/or tab bar:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"YourStoryboard" bundle:nil];
YourViewController *viewController = (YourViewcontroller *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self.navigationController pushViewController:viewController animated:YES];

To set identifier to a view controller, Open YourStoryboard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

json.dumps vs flask.jsonify

You can do:

flask.jsonify(**data)

or

flask.jsonify(id=str(album.id), title=album.title)

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

Use the toSql() method on a QueryBuilder instance.

DB::table('users')->toSql() would return:

select * from `users`

This is easier than wiring up an event listener, and also lets you check what the query will actually look like at any point while you're building it.

Listing all permutations of a string/integer

Here is a C# answer which is a little simplified.

public static void StringPermutationsDemo()
{
    strBldr = new StringBuilder();

    string result = Permute("ABCD".ToCharArray(), 0);
    MessageBox.Show(result);
}     

static string Permute(char[] elementsList, int startIndex)
{
    if (startIndex == elementsList.Length)
    {
        foreach (char element in elementsList)
        {
            strBldr.Append(" " + element);
        }
        strBldr.AppendLine("");
    }
    else
    {
        for (int tempIndex = startIndex; tempIndex <= elementsList.Length - 1; tempIndex++)
        {
            Swap(ref elementsList[startIndex], ref elementsList[tempIndex]);

            Permute(elementsList, (startIndex + 1));

            Swap(ref elementsList[startIndex], ref elementsList[tempIndex]);
        }
    }

    return strBldr.ToString();
}

static void Swap(ref char Char1, ref char Char2)
{
    char tempElement = Char1;
    Char1 = Char2;
    Char2 = tempElement;
}

Output:

1 2 3
1 3 2

2 1 3
2 3 1

3 2 1
3 1 2

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

What you are talking about is called dot sourcing. And it's evil. But no worries, there is a better and easier way to do what you are wanting with modules (it sounds way scarier than it is). The major benefit of using modules is that you can unload them from the shell if you need to, and it keeps the variables in the functions from creeping into the shell (once you dot source a function file, try calling one of the variables from a function in the shell, and you'll see what I mean).

So first, rename the .ps1 file that has all your functions in it to MyFunctions.psm1 (you've just created a module!). Now for a module to load properly, you have to do some specific things with the file. First for Import-Module to see the module (you use this cmdlet to load the module into the shell), it has to be in a specific location. The default path to the modules folder is $home\Documents\WindowsPowerShell\Modules.

In that folder, create a folder named MyFunctions, and place the MyFunctions.psm1 file into it (the module file must reside in a folder with exactly the same name as the PSM1 file).

Once that is done, open PowerShell, and run this command:

Get-Module -listavailable

If you see one called MyFunctions, you did it right, and your module is ready to be loaded (this is just to ensure that this is set up right, you only have to do this once).

To use the module, type the following in the shell (or put this line in your $profile, or put this as the first line in a script):

Import-Module MyFunctions

You can now run your functions. The cool thing about this is that once you have 10-15 functions in there, you're going to forget the name of a couple. If you have them in a module, you can run the following command to get a list of all the functions in your module:

Get-Command -module MyFunctions

It's pretty sweet, and the tiny bit of effort that it takes to set up on the front side is WAY worth it.

Squash the first two commits in Git?

Squashing the first and second commit would result in the first commit being rewritten. If you have more than one branch that is based off the first commit, you'd cut off that branch.

Consider the following example:

a---b---HEAD
 \
  \
   '---d

Squashing a and b into a new commit "ab" would result in two distinct trees which in most cases is not desirable since git-merge and git-rebase will no longer work across the two branches.

ab---HEAD

a---d

If you really want this, it can be done. Have a look at git-filter-branch for a powerful (and dangerous) tool for history rewriting.

Unable to begin a distributed transaction

OK, so services are started, there is an ethernet path between them, name resolution works, linked servers work, and you disabled transaction authentication.

My gut says firewall issue, but a few things come to mind...

  1. Are the machines in the same domain? (yeah, shouldn't matter with disabled authentication)
  2. Are firewalls running on the the machines? DTC can be a bit of pain for firewalls as it uses a range of ports, see http://support.microsoft.com/kb/306843 For the time being, I would disable firewalls for the sake of identifying the problem
  3. What does DTC ping say? http://www.microsoft.com/download/en/details.aspx?id=2868
  4. What account is the SQL Service running as ?

Failed linking file resources

This might be useful for someone who is looking for a different answer. Go to the Gradle Panel and select your module -> Task -> Verification -> Check. This will check the project for errors and will print the log where the error occurs. Most of the time this Kind of error must be a typo present in your XML file of your project

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Tested with: log4j-ap 2.13.2, log4j-core 2.13.2.

  1. Keep XML file directly under below folder structure. src/main/java
  2. In the POM:
    <build>   
 <resources>       
             <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>             
            </resource>
 </resources>  
</build>
  1. Clean and build.

How to name and retrieve a stash by name in git?

It's unfortunate that git stash apply stash^{/<regex>} doesn't work (it doesn't actually search the stash list, see the comments under the accepted answer).

Here are drop-in replacements that search git stash list by regex to find the first (most recent) stash@{<n>} and then pass that to git stash <command>:

# standalone (replace <stash_name> with your regex)
(n=$(git stash list --max-count=1 --grep=<stash_name> | cut -f1 -d":") ; if [[ -n "$n" ]] ; then git stash show "$n" ; else echo "Error: No stash matches" ; return 1 ; fi)
(n=$(git stash list --max-count=1 --grep=<stash_name> | cut -f1 -d":") ; if [[ -n "$n" ]] ; then git stash apply "$n" ; else echo "Error: No stash matches" ; return 1 ; fi)
# ~/.gitconfig
[alias]
  sshow = "!f() { n=$(git stash list --max-count=1 --grep=$1 | cut -f1 -d":") ; if [[ -n "$n" ]] ; then git stash show "$n" ; else echo "Error: No stash matches $1" ; return 1 ; fi }; f"
  sapply = "!f() { n=$(git stash list --max-count=1 --grep=$1 | cut -f1 -d":") ; if [[ -n "$n" ]] ; then git stash apply "$n" ; else echo "Error: No stash matches $1" ; return 1 ; fi }; f"

# usage:

$ git sshow my_stash
 myfile.txt | 1 +
 1 file changed, 1 insertion(+)

$ git sapply my_stash
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   myfile.txt

no changes added to commit (use "git add" and/or "git commit -a")

Note that proper result codes are returned so you can use these commands within other scripts. This can be verified after running commands with:

echo $?

Just be careful about variable expansion exploits because I wasn't sure about the --grep=$1 portion. It should maybe be --grep="$1" but I'm not sure if that would interfere with regex delimiters (I'm open to suggestions).

Hide separator line on one UITableViewCell

I couldn't hide the separator on a specific cell except using the following workaround

- (void)layoutSubviews {
    [super layoutSubviews];
    [self hideCellSeparator];
}
// workaround
- (void)hideCellSeparator {
    for (UIView *view in  self.subviews) {
        if (![view isKindOfClass:[UIControl class]]) {
            [view removeFromSuperview];
        }
    }
}

bodyParser is deprecated express 4

In older versions of express, we had to use:

app.use(express.bodyparser()); 

because body-parser was a middleware between node and express. Now we have to use it like:

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Mockito matcher and array of primitives

I would try any(byte[].class)

How can I change the color of pagination dots of UIPageControl?

This is worked for me in iOS 7.

pageControl.pageIndicatorTintColor = [UIColor purpleColor];
pageControl.currentPageIndicatorTintColor = [UIColor magentaColor];

Executing JavaScript without a browser?

FWIW, node.js comes with a shell, try typing in:

node-repl

once you've installed node.js to see it in action. It's pretty standard to install rlwrap to get it to work nicely.

How to prevent colliders from passing through each other?

How about set the Collision Detection of rigidbody to Continuous or Continuous Dynamic?

http://unity3d.com/support/documentation/Components/class-Rigidbody.html

Difference between StringBuilder and StringBuffer

StringBuilder is not thread safe. String Buffer is. More info here.

EDIT: As for performance , after hotspot kicks in , StringBuilder is the winner. However , for small iterations , the performance difference is negligible.

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

Difference between a theta join, equijoin and natural join

Natural is a subset of Equi which is a subset of Theta.

If I use the = sign on a theta join is it exactly the same as just using a natural join???

Not necessarily, but it would be an Equi. Natural means you are matching on all similarly named columns, Equi just means you are using '=' exclusively (and not 'less than', like, etc)

This is pure academia though, you could work with relational databases for years and never hear anyone use these terms.

How the int.TryParse actually works

Just because int.TryParse gives you the value doesn't mean you need to keep it; you can quite happily do this:

int temp;
if (int.TryParse(inputString, out temp))
{
    // do stuff
}

You can ignore temp entirely if you don't need it. If you do need it, then hey, it's waiting for you when you want it.

As for the internals, as far as I remember it attempts to read the raw bytes of the string as an int and tests whether the result is valid, or something; it's not as simple as iterating through looking for non-numeric characters.

How to display Oracle schema size with SQL query?

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
    FROM DBA_SEGMENTS DS
    WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES) AND SEGMENT_NAME='YOUR_TABLE_NAME'
    GROUP BY DS.TABLESPACE_NAME, SEGMENT_NAME;

Can I pass column name as input parameter in SQL stored Procedure

As mentioned by MatBailie This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names

            CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
    (
    @fromColumnName varchar(10) ,
    @toColumnName varchar(10) , 
    @ID varchar(10)
    )
    as
    begin

    -- this is the column required for where clause 
    declare @colname varchar(50)
    set @colname=case @fromUserType
        when 'XX' then 'XX'
        when 'YY' then 'YY'
        end
        select SelectedColumnId  from (
       select 
            case @toColumnName 
            when 'XX' then tablename.XX
            when 'YY' then tablename.YY
            end as SelectedColumnId,
        From tablename
        where 
        (case @fromUserType 
            when 'XX' then XX
            when 'YY' then YY
        end)= ISNULL(@ID , @colname) 
    ) as tbl1 group by SelectedColumnId 

    end

How do I access Configuration in any class in ASP.NET Core?

Using the Options pattern in ASP.NET Core is the way to go. I just want to add, if you need to access the options within your startup.cs, I recommend to do it this way:

CosmosDbOptions.cs:

public class CosmosDbOptions
{
    public string ConnectionString { get; set; }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // This is how you can access the Connection String:
    var connectionString = Configuration.GetSection(nameof(CosmosDbOptions))[nameof(CosmosDbOptions.ConnectionString)];
}

How to set image in circle in swift

import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var image: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    image.layer.borderWidth = 1
    image.layer.masksToBounds = false
    image.layer.borderColor = UIColor.black.cgColor
    image.layer.cornerRadius = image.frame.height/2
    image.clipsToBounds = true
}

If you want it on an extension

import UIKit

extension UIImageView {

    func makeRounded() {

        self.layer.borderWidth = 1
        self.layer.masksToBounds = false
        self.layer.borderColor = UIColor.black.cgColor
        self.layer.cornerRadius = self.frame.height / 2
        self.clipsToBounds = true
    }
}

That is all you need....

What is the difference between MacVim and regular Vim?

It's all about the key bindings which one can simply achieve from .vimrc configurations. As far as clipboard is concerned you can use :set clipboard unnamed and the yank from vim will go to system clipboard. Anyways, whichever one you end up using I suggest using this vimrc config , it contains a whole lot of plugins and bindings which will make your experience smooth.

Javascript array value is undefined ... how do I test for that

try: typeof(predQuery[preId])=='undefined'
or more generally: typeof(yourArray[yourIndex])=='undefined'
You're comparing "undefined" to undefined, which returns false =)

How to change Screen buffer size in Windows Command Prompt from batch script

I was just giving a try for max lines on windows 7 i can set using mode con command and found it to be 32766 2^15-2 and you can set it with following command

mode con lines=32766

although you can set screen buffer size from the GUI too, but the max you can get is 9999.

jQuery Datepicker with text input that doesn't allow user input

I know this thread is old, but for others who encounter the same problem, that implement @Brad8118 solution (which i prefer, because if you choose to make the input readonly then the user will not be able to delete the date value inserted from datepicker if he chooses) and also need to prevent the user from pasting a value (as @ErikPhilips suggested to be needed), I let this addition here, which worked for me: $("#my_txtbox").bind('paste',function(e) { e.preventDefault(); //disable paste }); from here https://www.dotnettricks.com/learn/jquery/disable-cut-copy-and-paste-in-textbox-using-jquery-javascript and the whole specific script used by me (using fengyuanchen/datepicker plugin instead):

$('[data-toggle="datepicker"]').datepicker({
    autoHide: true,
    pick: function (e) {
        e.preventDefault();
        $(this).val($(this).datepicker('getDate', true));
    }
}).keypress(function(event) {
    event.preventDefault(); // prevent keyboard writing but allowing value deletion
}).bind('paste',function(e) {
    e.preventDefault()
}); //disable paste;

rand() between 0 and 1

This is entirely implementation specific, but it appears that in the C++ environment you're working in, RAND_MAX is equal to INT_MAX.

Because of this, RAND_MAX + 1 exhibits undefined (overflow) behavior, and becomes INT_MIN. While your initial statement was dividing (random # between 0 and INT_MAX)/(INT_MAX) and generating a value 0 <= r < 1, now it's dividing (random # between 0 and INT_MAX)/(INT_MIN), generating a value -1 < r <= 0

In order to generate a random number 1 <= r < 2, you would want

r = ((double) rand() / (RAND_MAX)) + 1

Sum all values in every column of a data.frame in R

For the sake of completion:

 apply(people[,-1], 2, function(x) sum(x))
#Height Weight 
#   199    425 

How to get value in the session in jQuery

Sessions are stored on the server and are set from server side code, not client side code such as JavaScript.

What you want is a cookie, someone's given a brilliant explanation in this Stack Overflow question here: How do I set/unset cookie with jQuery?

You could potentially use sessions and set/retrieve them with jQuery and AJAX, but it's complete overkill if Cookies will do the trick.

How do I concatenate const/literal strings in C?

Avoid using strcat in C code. The cleanest and, most importantly, the safest way is to use snprintf:

char buf[256];
snprintf(buf, sizeof buf, "%s%s%s%s", str1, str2, str3, str4);

Some commenters raised an issue that the number of arguments may not match the format string and the code will still compile, but most compilers already issue a warning if this is the case.

How to study design patterns?

I would think it is also difficult to study design patterns. You have to know more about OOP and some experiences with medium to big application development. For me, I study as a group of developers to make discussion. We follow A Learning Guide To Design Patterns that they have completed the patterns study. There are C# and JavaScript developers join together. It is fancy thing for me is the C# developer write codes in JavaScript and the JavaScript developer do the same thing for C# codes. After I leave a meeting I also research and read a few books at home to review. The better way to understand more and remember in my mind is to do blogging with examples in both C# and JavaScript in here http://tech.wowkhmer.com/category/Design-Patterns.aspx.

I would suggest first before going to each design patterns please understand the name of patterns. In addition if someone know the concept please just explain and give one example not only just programming but in the read world.

for example:

Factory Method:

Read world: I just give money $5, $10 or $20 and it will produce pizza back without knowing anything about how it produce, I just get a small, medium or big pizza depend on money input so that I can eat or do whatever.

Programming: The client just pass parameter value $5, $10 or $20 to the factory method and it will return Pizza object back. So the client can use that object without knowing how it process.

I'm not sure this can help you. It depends on knowledge level of people join in the meeting.

Is there a better way to run a command N times in bash?

You can use this command to repeat your command 10 times or more

for i in {1..10}; do **your command**; done

for example

for i in {1..10}; do **speedtest**; done

MatPlotLib: Multiple datasets on the same scatter plot

You need a reference to an Axes object to keep drawing on the same subplot.

import matplotlib.pyplot as plt

x = range(100)
y = range(100,200)
fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first')
ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')
plt.legend(loc='upper left');
plt.show()

enter image description here

Routing with multiple Get methods in ASP.NET Web API

There are lots of good answers already for this question. However nowadays Route configuration is sort of "deprecated". The newer version of MVC (.NET Core) does not support it. So better to get use to it :)

So I agree with all the answers which uses Attribute style routing. But I keep noticing that everyone repeated the base part of the route (api/...). It is better to apply a [RoutePrefix] attribute on top of the Controller class and don't repeat the same string over and over again.

[RoutePrefix("api/customers")]
public class MyController : Controller
{
 [HttpGet]
 public List<Customer> Get()
 {
   //gets all customer logic
 }

 [HttpGet]
 [Route("currentMonth")]
 public List<Customer> GetCustomerByCurrentMonth()
 {
     //gets some customer 
 }

 [HttpGet]
 [Route("{id}")]
 public Customer GetCustomerById(string id)
 {
  //gets a single customer by specified id
 }
 [HttpGet]
 [Route("customerByUsername/{username}")]
 public Customer GetCustomerByUsername(string username)
 {
    //gets customer by its username
 }
}

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

This seems to work for me.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DropDownList1.DataBind(); // get the data into the list you can set it
            DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
        }
    }

How to check if all elements of a list matches a condition?

Another way to use itertools.ifilter. This checks truthiness and process (using lambda)

Sample-

for x in itertools.ifilter(lambda x: x[2] == 0, my_list):
    print x

How to add background-image using ngStyle (angular2)?

My background image wasn't working because the URL had a space in it and thus I needed to URL encode it.

You can check if this is the issue you're having by trying a different image URL that doesn't have characters that need escaping.

You could do this to the data in the component just using Javascripts built in encodeURI() method.

Personally I wanted to create a pipe for it so that it could be used in the template.

To do this you can create a very simple pipe. For example:

src/app/pipes/encode-uri.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'encodeUri'
})
export class EncodeUriPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return encodeURI(value);
  }
}

src/app/app.module.ts

import { EncodeUriPipe } from './pipes/encode-uri.pipe';
...

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule
    ...
  ],
  exports: [
    ...
  ],
 declarations: [
    AppComponent,
    EncodeUriPipe
 ],
 bootstrap: [ AppComponent ]
})

export class AppModule { }

src/app/app.component.ts

import {Component} from '@angular/core';

@Component({
  // tslint:disable-next-line
  selector: 'body',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {
  myUrlVariable: string;
  constructor() {
    this.myUrlVariable = 'http://myimagewith space init.com';
  }
}

src/app/app.component.html

<div [style.background-image]="'url(' + (myUrlVariable | encodeUri) + ')'" ></div>

Git push error '[remote rejected] master -> master (branch is currently checked out)'

I like the idea of still having a usable repository on the remote box, but instead of a dummy branch, I like to use:

git checkout --detach

This seems to be a very new feature of Git - I'm using git version 1.7.7.4.

Transparent color of Bootstrap-3 Navbar

  1. Go to http://px64.net/
  2. mess around with opacity, add your image or choose color.
  3. copy either html or css(css is easier) the site spits out.
  4. Select your element aka the navbar.

  5. .navbar{ background-image:url(link that the site provides); background-repeat:repeat;

  6. Enjoy.

Android video streaming example

I had the same problem but finally I found the way.

Here is the walk through:

1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)

2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.

3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:

:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}

NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...

NOTE: You can see, the video codec is MP4V which is supported by android.

4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:

mVideoView = (VideoView) findViewById(R.id.surface_view);

mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));

5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...

Question: Anybody know how to reduce buffering time and play video almost live ?

Auto logout with Angularjs based on idle user

I tried out Buu's approach and couldn't get it quite right due to the sheer number of events that trigger the digester to execute, including $interval and $timeout functions executing. This leaves the application in a state where it never be idle regardless of user input.

If you actually need to track user idle time I am not sure that there is a good angular approach. I would suggest that a better approach is represented by Witoldz here https://github.com/witoldsz/angular-http-auth. This approach will prompt the user to reauthenticate when an action is taken that requires their credentials. After the user has authenticated the previous failed request is reprocessed and the application continues on as if nothing happened.

This handles the concern that you might have of letting the user's session expire while they are active since even if their authentication expires they are still able to retain the application state and not lose any work.

If you have some kind of session on your client (cookies, tokens, etc) you could watch them as well and trigger your logout process if they expire.

app.run(['$interval', function($interval) {
  $interval(function() {
    if (/* session still exists */) {
    } else {
      // log out of client
    }
  }, 1000);
}]);

UPDATE: Here is a plunk that demonstrates the concern. http://plnkr.co/edit/ELotD8W8VAeQfbYFin1W. What this demonstates is that the digester run time is updated only when the interval ticks. Once the interval reaches it max count then the digester will no longer run.

Accessing the index in 'for' loops?

Here's what you get when you're accessing index in for loops:

for i in enumerate(items): print(i)

items = [8, 23, 45, 12, 78]

for i in enumerate(items):
    print("index/value", i)

Result:

# index/value (0, 8)
# index/value (1, 23)
# index/value (2, 45)
# index/value (3, 12)
# index/value (4, 78)

for i, val in enumerate(items): print(i, val)

items = [8, 23, 45, 12, 78]

for i, val in enumerate(items):
    print("index", i, "for value", val)

Result:

# index 0 for value 8
# index 1 for value 23
# index 2 for value 45
# index 3 for value 12
# index 4 for value 78

for i, val in enumerate(items): print(i)

items = [8, 23, 45, 12, 78]

for i, val in enumerate(items):
    print("index", i)

Result:

# index 0
# index 1
# index 2
# index 3
# index 4

Html.fromHtml deprecated in Android N

Or you can use androidx.core.text.HtmlCompat:

HtmlCompat.fromHtml("<b>HTML</b>", HtmlCompat.FROM_HTML_MODE_LEGACY)

HtmlCompat docs

How to kill a thread instantly in C#?

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

How to generate unique IDs for form labels in React?

The id should be placed inside of componentWillMount (update for 2018) constructor, not render. Putting it in render will re-generate new ids unnecessarily.

If you're using underscore or lodash, there is a uniqueId function, so your resulting code should be something like:

constructor(props) {
    super(props);
    this.id = _.uniqueId("prefix-");
}

render() { 
  const id = this.id;
  return (
    <div>
        <input id={id} type="checkbox" />
        <label htmlFor={id}>label</label>
    </div>
  );
}

2019 Hooks update:

import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';

const MyComponent = (props) => {
  // id will be set once when the component initially renders, but never again
  // (unless you assigned and called the second argument of the tuple)
  const [id] = useState(_uniqueId('prefix-'));
  return (
    <div>
      <input id={id} type="checkbox" />
      <label htmlFor={id}>label</label>
    </div>
  );
}

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I modified the accepted answer and now it can get the command including primary key and foreign key in a certain schema.

declare @table varchar(100)
declare @schema varchar(100)
set @table = 'Persons' -- set table name here
set @schema = 'OT' -- set SCHEMA name here
declare @sql table(s varchar(1000), id int identity)

-- create statement
insert into  @sql(s) values ('create table ' + @table + ' (')

-- column list
insert into @sql(s)
select 
    '  '+column_name+' ' + 
    data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
    case when exists ( 
        select id from syscolumns
        where object_name(id)=@table
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
    ) then
        'IDENTITY(' + 
        cast(ident_seed(@table) as varchar) + ',' + 
        cast(ident_incr(@table) as varchar) + ')'
    else ''
    end + ' ' +
    ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
    coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','

 from information_schema.columns where table_name = @table and table_schema = @schema
 order by ordinal_position

-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='PRIMARY KEY'

if ( @pkname is not null ) begin
    insert into @sql(s) values('  PRIMARY KEY (')
    insert into @sql(s)
        select '   '+COLUMN_NAME+',' from information_schema.key_column_usage
        where constraint_name = @pkname
        order by ordinal_position
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  )')
end
else begin
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
end


-- foreign key
declare @fkname varchar(100)
select @fkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='FOREIGN KEY'

if ( @fkname is not null ) begin
    insert into @sql(s) values(',')
    insert into @sql(s) values('  FOREIGN KEY (')
    insert into @sql(s)
        select '   '+COLUMN_NAME+',' from information_schema.key_column_usage
        where constraint_name = @fkname
        order by ordinal_position
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  ) REFERENCES ')
    insert into @sql(s) 
        SELECT  
            OBJECT_NAME(fk.referenced_object_id)
        FROM 
            sys.foreign_keys fk
        INNER JOIN 
            sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
        INNER JOIN
            sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
        INNER JOIN
            sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
        where fk.name = @fkname
    insert into @sql(s) 
        SELECT  
            '('+c2.name+')'
        FROM 
            sys.foreign_keys fk
        INNER JOIN 
            sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
        INNER JOIN
            sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
        INNER JOIN
            sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
        where fk.name = @fkname
end

-- closing bracket
insert into @sql(s) values( ')' )

-- result!
select s from @sql order by id

How to change the height of a <br>?

<br /> will take as much space as text-filled row of your <p>, you can't change that. If you want larger, it means you want to separate into paragraph, so add other <p>. Don't forget to be the most semantic you can ;)

HTML CSS Button Positioning

Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block, so when one is pushed down the hole line is pushed down with him. Float fixes this:

#header button {
    float:left;
}

Here's a working jsfidle.

Changing background color of ListView items on Android

Simple code to change all in layout of item (custom listview extends baseadapter):

lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            RelativeLayout layout=(RelativeLayout) arg1.findViewById(R.id.rel_cell_left);
            layout.setBackgroundColor(Color.YELLOW);



        }
    });

How many threads is too many?

In most cases you should allow the thread pool to handle this. If you post some code or give more details it might be easier to see if there is some reason the default behavior of the thread pool would not be best.

You can find more information on how this should work here: http://en.wikipedia.org/wiki/Thread_pool_pattern

javac: invalid target release: 1.8

Most of the time, these type of issues happen due to incorrect java version. Make sure your PATH and JAVA_HOME variables are pointing to the correct version.

How to mock location on device?

I wonder if you need the elaborate Mock Location setup. In my case once I got a fix location I was calling a function to do something with that new location. In a timer create a mock location. And call the function with that location instead. Knowing all along that in a short while GPS would come up with a real current location. Which is OK. If you have the update time set sufficiently long.

mysql data directory location

Well, if yo don't know where is my.cnf (such Mac OS X installed with homebrew), or You are looking found others choices:

ps aux|grep mysql
abkrim            1160   0.0  0.2  2913068  26224   ??  R    Tue04PM   0:14.63 /usr/local/opt/mariadb/bin/mysqld --basedir=/usr/local/opt/mariadb --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/opt/mariadb/lib/plugin --bind-address=127.0.0.1 --log-error=/usr/local/var/mysql/iMac-2.local.err --pid-file=iMac-2.local.pid

You get datadir=/usr/local/var/mysql

C++ Object Instantiation

Well, the reason to use the pointer would be exactly the same that the reason to use pointers in C allocated with malloc: if you want your object to live longer than your variable!

It is even highly recommended to NOT use the new operator if you can avoid it. Especially if you use exceptions. In general it is much safer to let the compiler free your objects.

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

How to check the version before installing a package using apt-get?

As posted somewhere else, this works, too:

apt-cache madison <package_name>

Copy file remotely with PowerShell

None of the above answers worked for me. I kept getting this error:

Copy-Item : Access is denied
+ CategoryInfo          : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>   
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

So this did it for me:

netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes

Then from my host my machine in the Run box I just did this:

\\{IP address of nanoserver}\C$

PDOException “could not find driver”

I extremely recommend mysqllnd instead of mysql because of you would have a lot of problems like number converting and bit type evaluates problem with mysql extension.

on ubuntu install mysqllnd with following command:

sudo apt-get install php5-mysqlnd

asp.net mvc @Html.CheckBoxFor

Use this code:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}

Pandas: change data type of Series to String

Personally none of the above worked for me. What did:

new_str = [str(x) for x in old_obj][0]

Passive Link in Angular 2 - <a href=""> equivalent

Updated for Angular 5

import { Directive, HostListener, Input } from '@angular/core';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector : '[href]'
})
export class HrefDirective {
  @Input() public href: string | undefined;

  @HostListener('click', ['$event']) public onClick(event: Event): void {
    if (!this.href || this.href === '#' || (this.href && this.href.length === 0)) {
      event.preventDefault();
    }
  }
}

How to sort a dataFrame in python pandas by two or more columns?

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

For example:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

As commented by @renadeen

Sort isn't in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

or

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

How to print GETDATE() in SQL Server with milliseconds in time?

This is equivalent to new Date().getTime() in JavaScript :

Use the below statement to get the time in seconds.

SELECT  cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)

Use the below statement to get the time in milliseconds.

SELECT  cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)  * 1000

ORACLE IIF Statement

Two other alternatives:

  1. a combination of NULLIF and NVL2. You can only use this if emp_id is NOT NULL, which it is in your case:

    select nvl2(nullif(emp_id,1),'False','True') from employee;
    
  2. simple CASE expression (Mt. Schneiders used a so-called searched CASE expression)

    select case emp_id when 1 then 'True' else 'False' end from employee;
    

How to get first and last day of previous month (with timestamp) in SQL Server

From SQL2012, there is a new function introduced called EOMONTH. Using this function the first and last day of the last month can be easily found.

select DATEADD(DD,1,EOMONTH(Getdate(),-2)) firstdayoflastmonth, EOMONTH(Getdate(), -1) lastdayoflastmonth

In an array of objects, fastest way to find the index of an object whose attributes match a search

Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:

var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];

Clear Application's Data Programmatically

If you want a less verbose hack:

void deleteDirectory(String path) {
  Runtime.getRuntime().exec(String.format("rm -rf %s", path));
}

Change text (html) with .animate

For fadeOut => change text => fadeIn effect We need to animate the wrapper of texts we would like change.

Example below:

HTML

<div class="timeline-yeardata">
  <div class="anime">
    <div class="ilosc-sklepow-sticker">
      <span id="amount">1400</span><br>
      sklepów
    </div>

    <div class="txts-wrap">
      <h3 class="title">Some text</h3>
      <span class="desc">Lorem ipsum description</span>
    </div>

    <div class="year-bg" id="current-year">2018</div>
  </div>
</div>


<div class="ch-timeline-wrap">
  <div class="ch-timeline">
    <div class="line"></div>

    <div class="row no-gutters">
      <div class="col">
        <a href="#2009" data-amount="9" data-y="2009" class="el current">
          <span class="yr">2009</span>
          <span class="dot"></span>

          <span class="title">Lorem  asdf asdf asdf a</span>
          <span class="desc">Ww wae awer awe rawer aser as</span>
        </a>
      </div>
      <div class="col">
        <a href="#2010" data-amount="19" data-y="2010" class="el">
          <span class="yr">2010</span>
          <span class="dot"></span>

          <span class="title">Lorem brernern</span>
          <span class="desc">A sd asdkj aksjdkajskd jaksjd kajskd jaksjd akjsdk jaskjd akjsdkajskdj akjsd k</span>
        </a>
      </div>
    </div>
  </div>
</div>

JQuery JS

$(document).ready(function(){

  $('.ch-timeline .el').on('click', function(){

    $('.ch-timeline .el').removeClass('current');
    $(this).addClass('current');

    var ilosc = $(this).data('ilosc');
    var y = $(this).data('y');
    var title = $(this).find('.title').html();
    var desc = $(this).find('desc').html();

    $('.timeline-yeardata .anime').fadeOut(400, function(){
      $('#ilosc-sklepow').html(ilosc);
      $('#current-year').html(y);
      $('.timeline-yeardata .title').html(title);
      $('.timeline-yeardata .desc').html(desc);
      $(this).fadeIn(300);
    })

  });

});

Hope this will help someone.

What does LayoutInflater in Android do?

What inflater does

It takes a xml layout as input (say) and converts it to View object.

Why needed

Let us think a scenario where we need to create a custom listview. Now each row should be custom. But how can we do it. Its not possible to assign a xml layout to a row of listview. So, we create a View object. Thus we can access the elements in it (textview,imageview etc) and also assign the object as row of listview

So, whenever we need to assign view type object somewhere and we have our custom xml design we just convert it to object by inflater and use it.

In Angular, What is 'pathmatch: full' and what effect does it have?

pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path

pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.

Ref: https://angular.io/guide/router#set-up-redirects

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

pathMatch: 'prefix' means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.

urlencode vs rawurlencode?

Proof is in the source code of PHP.

I'll take you through a quick process of how to find out this sort of thing on your own in the future any time you want. Bear with me, there'll be a lot of C source code you can skim over (I explain it). If you want to brush up on some C, a good place to start is our SO wiki.

Download the source (or use http://lxr.php.net/ to browse it online), grep all the files for the function name, you'll find something such as this:

PHP 5.3.6 (most recent at time of writing) describes the two functions in their native C code in the file url.c.

RawUrlEncode()

PHP_FUNCTION(rawurlencode)
{
    char *in_str, *out_str;
    int in_str_len, out_str_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
                              &in_str_len) == FAILURE) {
        return;
    }

    out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len);
    RETURN_STRINGL(out_str, out_str_len, 0);
}

UrlEncode()

PHP_FUNCTION(urlencode)
{
    char *in_str, *out_str;
    int in_str_len, out_str_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
                              &in_str_len) == FAILURE) {
        return;
    }

    out_str = php_url_encode(in_str, in_str_len, &out_str_len);
    RETURN_STRINGL(out_str, out_str_len, 0);
}

Okay, so what's different here?

They both are in essence calling two different internal functions respectively: php_raw_url_encode and php_url_encode

So go look for those functions!

Lets look at php_raw_url_encode

PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length)
{
    register int x, y;
    unsigned char *str;

    str = (unsigned char *) safe_emalloc(3, len, 1);
    for (x = 0, y = 0; len--; x++, y++) {
        str[y] = (unsigned char) s[x];
#ifndef CHARSET_EBCDIC
        if ((str[y] < '0' && str[y] != '-' && str[y] != '.') ||
            (str[y] < 'A' && str[y] > '9') ||
            (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') ||
            (str[y] > 'z' && str[y] != '~')) {
            str[y++] = '%';
            str[y++] = hexchars[(unsigned char) s[x] >> 4];
            str[y] = hexchars[(unsigned char) s[x] & 15];
#else /*CHARSET_EBCDIC*/
        if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) {
            str[y++] = '%';
            str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4];
            str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15];
#endif /*CHARSET_EBCDIC*/
        }
    }
    str[y] = '\0';
    if (new_length) {
        *new_length = y;
    }
    return ((char *) str);
}

And of course, php_url_encode:

PHPAPI char *php_url_encode(char const *s, int len, int *new_length)
{
    register unsigned char c;
    unsigned char *to, *start;
    unsigned char const *from, *end;

    from = (unsigned char *)s;
    end = (unsigned char *)s + len;
    start = to = (unsigned char *) safe_emalloc(3, len, 1);

    while (from < end) {
        c = *from++;

        if (c == ' ') {
            *to++ = '+';
#ifndef CHARSET_EBCDIC
        } else if ((c < '0' && c != '-' && c != '.') ||
                   (c < 'A' && c > '9') ||
                   (c > 'Z' && c < 'a' && c != '_') ||
                   (c > 'z')) {
            to[0] = '%';
            to[1] = hexchars[c >> 4];
            to[2] = hexchars[c & 15];
            to += 3;
#else /*CHARSET_EBCDIC*/
        } else if (!isalnum(c) && strchr("_-.", c) == NULL) {
            /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */
            to[0] = '%';
            to[1] = hexchars[os_toascii[c] >> 4];
            to[2] = hexchars[os_toascii[c] & 15];
            to += 3;
#endif /*CHARSET_EBCDIC*/
        } else {
            *to++ = c;
        }
    }
    *to = 0;
    if (new_length) {
        *new_length = to - start;
    }
    return (char *) start;
}

One quick bit of knowledge before I move forward, EBCDIC is another character set, similar to ASCII, but a total competitor. PHP attempts to deal with both. But basically, this means byte EBCDIC 0x4c byte isn't the L in ASCII, it's actually a <. I'm sure you see the confusion here.

Both of these functions manage EBCDIC if the web server has defined it.

Also, they both use an array of chars (think string type) hexchars look-up to get some values, the array is described as such:

/* rfc1738:

   ...The characters ";",
   "/", "?", ":", "@", "=" and "&" are the characters which may be
   reserved for special meaning within a scheme...

   ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
   reserved characters used for their reserved purposes may be used
   unencoded within a URL...

   For added safety, we only leave -_. unencoded.
 */

static unsigned char hexchars[] = "0123456789ABCDEF";

Beyond that, the functions are really different, and I'm going to explain them in ASCII and EBCDIC.

Differences in ASCII:

URLENCODE:

  • Calculates a start/end length of the input string, allocates memory
  • Walks through a while-loop, increments until we reach the end of the string
  • Grabs the present character
  • If the character is equal to ASCII Char 0x20 (ie, a "space"), add a + sign to the output string.
  • If it's not a space, and it's also not alphanumeric (isalnum(c)), and also isn't and _, -, or . character, then we , output a % sign to array position 0, do an array look up to the hexchars array for a lookup for os_toascii array (an array from Apache that translates char to hex code) for the key of c (the present character), we then bitwise shift right by 4, assign that value to the character 1, and to position 2 we assign the same lookup, except we preform a logical and to see if the value is 15 (0xF), and return a 1 in that case, or a 0 otherwise. At the end, you'll end up with something encoded.
  • If it ends up it's not a space, it's alphanumeric or one of the _-. chars, it outputs exactly what it is.

RAWURLENCODE:

  • Allocates memory for the string
  • Iterates over it based on length provided in function call (not calculated in function as with URLENCODE).

Note: Many programmers have probably never seen a for loop iterate this way, it's somewhat hackish and not the standard convention used with most for-loops, pay attention, it assigns x and y, checks for exit on len reaching 0, and increments both x and y. I know, it's not what you'd expect, but it's valid code.

  • Assigns the present character to a matching character position in str.
  • It checks if the present character is alphanumeric, or one of the _-. chars, and if it isn't, we do almost the same assignment as with URLENCODE where it preforms lookups, however, we increment differently, using y++ rather than to[1], this is because the strings are being built in different ways, but reach the same goal at the end anyway.
  • When the loop's done and the length's gone, It actually terminates the string, assigning the \0 byte.
  • It returns the encoded string.

Differences:

  • UrlEncode checks for space, assigns a + sign, RawURLEncode does not.
  • UrlEncode does not assign a \0 byte to the string, RawUrlEncode does (this may be a moot point)
  • They iterate differntly, one may be prone to overflow with malformed strings, I'm merely suggesting this and I haven't actually investigated.

They basically iterate differently, one assigns a + sign in the event of ASCII 20.

Differences in EBCDIC:

URLENCODE:

  • Same iteration setup as with ASCII
  • Still translating the "space" character to a + sign. Note-- I think this needs to be compiled in EBCDIC or you'll end up with a bug? Can someone edit and confirm this?
  • It checks if the present char is a char before 0, with the exception of being a . or -, OR less than A but greater than char 9, OR greater than Z and less than a but not a _. OR greater than z (yeah, EBCDIC is kinda messed up to work with). If it matches any of those, do a similar lookup as found in the ASCII version (it just doesn't require a lookup in os_toascii).

RAWURLENCODE:

  • Same iteration setup as with ASCII
  • Same check as described in the EBCDIC version of URL Encode, with the exception that if it's greater than z, it excludes ~ from the URL encode.
  • Same assignment as the ASCII RawUrlEncode
  • Still appending the \0 byte to the string before return.

Grand Summary

  • Both use the same hexchars lookup table
  • URIEncode doesn't terminate a string with \0, raw does.
  • If you're working in EBCDIC I'd suggest using RawUrlEncode, as it manages the ~ that UrlEncode does not (this is a reported issue). It's worth noting that ASCII and EBCDIC 0x20 are both spaces.
  • They iterate differently, one may be faster, one may be prone to memory or string based exploits.
  • URIEncode makes a space into +, RawUrlEncode makes a space into %20 via array lookups.

Disclaimer: I haven't touched C in years, and I haven't looked at EBCDIC in a really really long time. If I'm wrong somewhere, let me know.

Suggested implementations

Based on all of this, rawurlencode is the way to go most of the time. As you see in Jonathan Fingland's answer, stick with it in most cases. It deals with the modern scheme for URI components, where as urlencode does things the old school way, where + meant "space."

If you're trying to convert between the old format and new formats, be sure that your code doesn't goof up and turn something that's a decoded + sign into a space by accidentally double-encoding, or similar "oops" scenarios around this space/20%/+ issue.

If you're working on an older system with older software that doesn't prefer the new format, stick with urlencode, however, I believe %20 will actually be backwards compatible, as under the old standard %20 worked, just wasn't preferred. Give it a shot if you're up for playing around, let us know how it worked out for you.

Basically, you should stick with raw, unless your EBCDIC system really hates you. Most programmers will never run into EBCDIC on any system made after the year 2000, maybe even 1990 (that's pushing, but still likely in my opinion).

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

With the Entity Framework most of the time SaveChanges() is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.

Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful.

The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.

I.e. something like this (bad):

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save and discard changes
    context1.SaveChanges();

    //Save and discard changes
    context2.SaveChanges();

    //if we get here things are looking good.
    scope.Complete();
}

If context1.SaveChanges() succeeds but context2.SaveChanges() fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1, so you can't replay or effectively log the failure.

But if you change your code to look like this:

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save Changes but don't discard yet
    context1.SaveChanges(false);

    //Save Changes but don't discard yet
    context2.SaveChanges(false);

    //if we get here things are looking good.
    scope.Complete();
    context1.AcceptAllChanges();
    context2.AcceptAllChanges();

}

While the call to SaveChanges(false) sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager if you want.

This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager somewhere.

See my blog post for more.

Can dplyr package be used for conditional mutating?

dplyr now has a function case_when that offers a vectorised if. The syntax is a little strange compared to mosaic:::derivedFactor as you cannot access variables in the standard dplyr way, and need to declare the mode of NA, but it is considerably faster than mosaic:::derivedFactor.

df %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                     a %in% c(0,1,3,4) | c == 4 ~ 3L, 
                     TRUE~as.integer(NA)))

EDIT: If you're using dplyr::case_when() from before version 0.7.0 of the package, then you need to precede variable names with '.$' (e.g. write .$a == 1 inside case_when).

Benchmark: For the benchmark (reusing functions from Arun 's post) and reducing sample size:

require(data.table) 
require(mosaic) 
require(dplyr)
require(microbenchmark)

set.seed(42) # To recreate the dataframe
DT <- setDT(lapply(1:6, function(x) sample(7, 10000, TRUE)))
setnames(DT, letters[1:6])
DF <- as.data.frame(DT)

DPLYR_case_when <- function(DF) {
  DF %>%
  mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                       a %in% c(0,1,3,4) | c==4 ~ 3L, 
                       TRUE~as.integer(NA)))
}

DT_fun <- function(DT) {
  DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
  DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
  mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
                    ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

mosa_fun <- function(DF) {
  mutate(DF, g = derivedFactor(
    "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
    "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
    .method = "first",
    .default = NA
  ))
}

perf_results <- microbenchmark(
  dt_fun <- DT_fun(copy(DT)),
  dplyr_ifelse <- DPLYR_fun(copy(DF)),
  dplyr_case_when <- DPLYR_case_when(copy(DF)),
  mosa <- mosa_fun(copy(DF)),
  times = 100L
)

This gives:

print(perf_results)
Unit: milliseconds
           expr        min         lq       mean     median         uq        max neval
         dt_fun   1.391402    1.560751   1.658337   1.651201   1.716851   2.383801   100
   dplyr_ifelse   1.172601    1.230351   1.331538   1.294851   1.390351   1.995701   100
dplyr_case_when   1.648201    1.768002   1.860968   1.844101   1.958801   2.207001   100
           mosa 255.591301  281.158350 291.391586 286.549802 292.101601 545.880702   100

How can I find whitespace in a String?

public static void main(String[] args) {
    System.out.println("test word".contains(" "));
}

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

I had same problem and it solved by defining kotlin gradle plugin version in build.gradle file.

change this

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

to

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50{or latest version}"

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

How to split a delimited string in Ruby and convert it to an array?

the simplest way to convert a string that has a delimiter like a comma is just to use the split method

"1,2,3,4".split(',') # "1", "2", "3", "4"]

you can find more info on how to use the split method in the ruby docs

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified.

If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

How to resize datagridview control when form resizes

You have to chose 'Fill' in the Dock property.

how to convert date to a format `mm/dd/yyyy`

Use CONVERT with the Value specifier of 101, whilst casting your data to date:

CONVERT(VARCHAR(10), CAST(Created_TS AS DATE), 101)

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

Check your dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SchoolApp</groupId>
  <artifactId>SchoolApp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <hibernate.version>4.2.0.Final</hibernate.version>
    <mysql.connector.version>5.1.21</mysql.connector.version>
    <spring.version>3.2.2.RELEASE</spring.version>
  </properties>

  <dependencies>
    <!-- DB related dependencies -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.connector.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.12.1.GA</version>
    </dependency>
    <!-- SPRING -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- Spring Security  -->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-core</artifactId>
      <version>3.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      <version>3.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      <version>3.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-taglibs</artifactId>
      <version>3.1.3.RELEASE</version>
    </dependency>
    <!-- CGLIB is required to process @Configuration classes -->
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>2.2.2</version>
    </dependency>
    <!-- Servlet API and JSTL -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- Test -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.7</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test-mvc</artifactId>
      <version>1.0.0.M1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <repositories>
    <repository>
      <id>spring-maven-milestone</id>
      <name>Spring Maven Milestone Repository</name>
      <url>http://maven.springframework.org/milestone</url>
    </repository>
  </repositories>

  <build>
    <finalName>spr-mvc-hib</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

How to run a SQL query on an Excel table?

You can experiment with the native DB driver for Excel in language/platform of your choice. In Java world, you can try with http://code.google.com/p/sqlsheet/ which provides a JDBC driver for working with Excel sheets directly. Similarly, you can get drivers for the DB technology for other platforms.

However, I can guarantee that you will soon hit a wall with the number of features these wrapper libraries provide. Better way will be to use Apache HSSF/POI or similar level of library but it will need more coding effort.

Can't operator == be applied to generic types in C#?

It appears that without the class constraint:

bool Compare<T> (T x, T y) where T: class
{
    return x == y;
}

One should realize that while class constrained Equals in the == operator inherits from Object.Equals, while that of a struct overrides ValueType.Equals.

Note that:

bool Compare<T> (T x, T y) where T: struct
{
    return x == y;
}

also gives out the same compiler error.

As yet I do not understand why having a value type equality operator comparison is rejected by the compiler. I do know for a fact though, that this works:

bool Compare<T> (T x, T y)
{
    return x.Equals(y);
}

How to echo text during SQL script execution in SQLPLUS

The prompt command will echo text to the output:

prompt A useful comment.
select(*) from TableA;

Will be displayed as:

SQL> A useful comment.
SQL> 
  COUNT(*)
----------
     0

ProcessStartInfo hanging on "WaitForExit"? Why?

I tried to make a class that would solve your problem using asynchronous stream read, by taking in account Mark Byers, Rob, stevejay answers. Doing so I realised that there is a bug related to asynchronous process output stream read.

I reported that bug at Microsoft: https://connect.microsoft.com/VisualStudio/feedback/details/3119134

Summary:

You can't do that:

process.BeginOutputReadLine(); process.Start();

You will receive System.InvalidOperationException : StandardOut has not been redirected or the process hasn't started yet.

============================================================================================================================

Then you have to start asynchronous output read after the process is started:

process.Start(); process.BeginOutputReadLine();

Doing so, make a race condition because the output stream can receive data before you set it to asynchronous:

process.Start(); 
// Here the operating system could give the cpu to another thread.  
// For example, the newly created thread (Process) and it could start writing to the output
// immediately before next line would execute. 
// That create a race condition.
process.BeginOutputReadLine();

============================================================================================================================

Then some people could say that you just have to read the stream before you set it to asynchronous. But the same problem occurs. There will be a race condition between the synchronous read and set the stream into asynchronous mode.

============================================================================================================================

There is no way to acheive safe asynchronous read of an output stream of a process in the actual way "Process" and "ProcessStartInfo" has been designed.

You are probably better using asynchronous read like suggested by other users for your case. But you should be aware that you could miss some information due to race condition.

Convert a character digit to the corresponding integer in C

use function: atoi for array to integer, atof for array to float type; or

char c = '5';
int b = c - 48;
printf("%d", b);

Single vs Double quotes (' vs ")

I use " as a top-tier and ' as a second tier, as I imagine most people do. For example

<a href="#" onclick="alert('Clicked!');">Click Me!</a>

In that example, you must use both, it is unavoidable.

inverting image in Python with OpenCV

You can use "tilde" operator to do it:

import cv2
image = cv2.imread("img.png")
image = ~image
cv2.imwrite("img_inv.png",image)

This is because the "tilde" operator (also known as unary operator) works doing a complement dependent on the type of object

for example for integers, its formula is:

x + (~x) = -1

but in this case, opencv use an "uint8 numpy array object" for its images so its range is from 0 to 255

so if we apply this operator to an "uint8 numpy array object" like this:

import numpy as np
x1 = np.array([25,255,10], np.uint8) #for example
x2 = ~x1
print (x2)

we will have as a result:

[230 0 245]

because its formula is:

x2 = 255 - x1

and that is exactly what we want to do to solve the problem.

How to display string that contains HTML in twig template?

if you don't need variable, you can define text in
translations/messages.en.yaml :
CiteExampleHtmlCode: "<b> my static text </b>"

then use it with twig:
templates/about/index.html.twig
… {{ 'CiteExampleHtmlCode' }}
or if you need multilangages like me:
… {{ 'CiteExampleHtmlCode' | trans }}

Let's have a look of https://symfony.com/doc/current/translation.html for more information about translations use.

What are the most common naming conventions in C?

I think those can help for beginner: Naming convention of variables in c

  1. You have to use Alphabetic Character (a-z, A-Z), Digit (0-9) and Under Score (_). It’s not allow to use any special Character like: %, $, #, @ etc. So, you can use user_name as variable but cannot use user&name.
  2. Can not use white space between words. So, you can use user_name or username or username as variable but cannot use user name.
  3. Can not start naming with digit. So, you can use user1 or user2 as variable but cannot use 1user.
  4. It is case sensitive language. Uppercase and lowercase are significant. If you use a variable like username then you cannot use USERNAME or Username for father use.
  5. You can not use any keyword (char, int, if, for, while etc) for variable declaration.
  6. ANSI standard recognizes a length of 31 characters for a variable name

Changing minDate and maxDate on the fly using jQuery DatePicker

I know you are using Datepicker, but for some people who are just using HTML5 input date like me, there is an example how you can do the same: JSFiddle Link

$('#start_date').change(function(){
  var start_date = $(this).val();
  $('#end_date').prop({
    min: start_date
  });
});


/*  prop() method works since jquery 1.6, if you are using a previus version, you can use attr() method.*/

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

How can I generate UUID in C#

I don't know about methods; however, the type to GUID can be done via:

Guid iid = System.Runtime.InteropServices.Marshal.GenerateGuidForType(typeof(IFoo));

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx

Loop through the rows of a particular DataTable

Here's the best way I found:

    For Each row As DataRow In your_table.Rows
        For Each cell As String In row.ItemArray
            'do what you want!
        Next
    Next

CreateProcess error=206, The filename or extension is too long when running main() method

In a Windows machine, there is a limitation of the jar file name/path length in the command-line, due to which you see the below error message, I tried searching a lot, even I tried applying the above solution, some reason, it didn't work, I found the working snippet for Gradle (gradle-4.10.2-all.zip)

Error:

CreateProcess error=206, The filename or extension is too long

Use this below gradle.build code snippet to fix the above problem in IntelliJ or STS, or eclipse anything.

Gradle Code Fix:

apply plugin: 'application'

task pathingJar(type: Jar) {
    dependsOn configurations.runtime
    appendix = 'pathing'

    doFirst {
        manifest {
            attributes "Class-Path": configurations.runtimeClasspath.files.collect { it.getName() }.join(' ')
        }
    }
}

task copyToLib(type: Copy) {
    into "$buildDir/libs"
    from configurations.runtime
}

bootRun {
    systemProperties = System.properties
    //This below line is for if you have different profiles prod, dev etc...
    //systemProperty 'spring.profiles.active', 'dev'
    jvmArgs('-Djava.util.logging.config.file=none')
    mainClassName = "com.xxxx.Main"
    dependsOn pathingJar
    dependsOn copyToLib
    doFirst {
        classpath = files("$buildDir/classes/java/main", "$buildDir/resources/main", pathingJar.archivePath)
    }
}

ListView item background via custom selector

The article "Why is my list black? An Android optimization" in the Android Developers Blog has a thorough explanation of why the list background turns black when scrolling. Simple answer: set cacheColorHint on your list to transparent (#00000000).

What's the difference between primitive and reference types?

Primitive Data Types :

  • Predefined by the language and named by a keyword
  • Total no = 8
    boolean
    char
    byte
    short
    integer
    long
    float
    double

Reference/Object Data Types :

  • Created using defined constructors of the classes
  • Used to access objects
  • Default value of any reference variable is null
  • Reference variable can be used to refer to any object of the declared type or any compatible type.

Check if string contains only whitespace

You want to use the isspace() method

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

That's defined on every string object. Here it is an usage example for your specific use case:

if aStr and (not aStr.isspace()):
    print aStr

How to configure Spring Security to allow Swagger URL to be accessed without authentication

if your springfox version higher than 2.5, should be add WebSecurityConfiguration as below:

@Override
public void configure(HttpSecurity http) throws Exception {
    // TODO Auto-generated method stub
    http.authorizeRequests()
        .antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll()
        .and()
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .csrf().disable();
}

How do I authenticate a WebClient request?

This helped me to call API that was using cookie authentication. I have passed authorization in header like this:

request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));

complete code:

// utility method to read the cookie value:
        public static string ReadCookie(string cookieName)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            var cookie = cookies.Get(cookieName);
            if (cookie != null)
                return cookie.Value;
            return null;
        }

// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;

// WebClient:

var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };

using (var webClient = new WebClient()) {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
      HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
      request.Method = "POST";
      request.ContentType = "application/json";                        
      request.ContentLength = requestData.Length;
      request.ContentType = "application/json";
      request.Expect = "application/json";
      request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
      request.GetRequestStream().Write(requestData, 0, requestData.Length);

      using (var response = (HttpWebResponse)request.GetResponse()) {
         var reader = new StreamReader(response.GetResponseStream());
         var objText = reader.ReadToEnd(); // objText will have the value
      }
}


Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

PHP Composer behind http proxy

iconoclast's answer did not work for me.

I upgraded my php from 5.3.* (xampp 1.7.4) to 5.5.* (xampp 1.8.3) and the problem was solved.

Try iconoclast's answer first, if it doesn't work then upgrading might solve the problem.

How can I check if a string is null or empty in PowerShell?

Personally, I do not accept a whitespace ($STR3) as being 'not empty'.

When a variable that only contains whitespaces is passed onto a parameter, it will often error that the parameters value may not be '$null', instead of saying it may not be a whitespace, some remove commands might remove a root folder instead of a subfolder if the subfolder name is a "white space", all the reason not to accept a string containing whitespaces in many cases.

I find this is the best way to accomplish it:

$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}

Empty

$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}

Empty

$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}

Empty!! :-)

$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}

Not empty

What .NET collection provides the fastest search

In the most general case, consider System.Collections.Generic.HashSet as your default "Contains" workhorse data structure, because it takes constant time to evaluate Contains.

The actual answer to "What is the fastest searchable collection" depends on your specific data size, ordered-ness, cost-of-hashing, and search frequency.

How can I profile C++ code running on Linux?

I assume you're using GCC. The standard solution would be to profile with gprof.

Be sure to add -pg to compilation before profiling:

cc -o myprog myprog.c utils.c -g -pg

I haven't tried it yet but I've heard good things about google-perftools. It is definitely worth a try.

Related question here.

A few other buzzwords if gprof does not do the job for you: Valgrind, Intel VTune, Sun DTrace.

How does Java resolve a relative path in new File()?

Relative paths can be best understood if you know how Java runs the program.

There is a concept of working directory when running programs in Java. Assuming you have a class, say, FileHelper that does the IO under /User/home/Desktop/projectRoot/src/topLevelPackage/.

Depending on the case where you invoke java to run the program, you will have different working directory. If you run your program from within and IDE, it will most probably be projectRoot.

  • In this case $ projectRoot/src : java topLevelPackage.FileHelper it will be src.

  • In this case $ projectRoot : java -cp src topLevelPackage.FileHelper it will be projectRoot.

  • In this case $ /User/home/Desktop : java -cp ./projectRoot/src topLevelPackage.FileHelper it will be Desktop.

(Assuming $ is your command prompt with standard Unix-like FileSystem. Similar correspondence/parallels with Windows system)

So, your relative path root (.) resolves to your working directory. Thus to be better sure of where to write files, it's said to consider below approach.

package topLevelPackage

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileHelper {

    // Not full implementation, just barebone stub for path
    public void createLocalFile() {

        // Explicitly get hold of working directory
        String workingDir = System.getProperty("user.dir");

        Path filePath = Paths.get(workingDir+File.separator+"sampleFile.txt");

        // In case we need specific path, traverse that path, rather using . or .. 
        Path pathToProjectRoot = Paths.get(System.getProperty("user.home"), "Desktop", "projectRoot");

        System.out.println(filePath);
        System.out.println(pathToProjectRoot);

    }
}

Hope this helps.

Object array initialization without default constructor

One way to solve is to give a static factory method to allocate the array if for some reason you want to give constructor private.

static Car*  Car::CreateCarArray(int dimensions)

But why are you keeping one constructor public and other private?

But anyhow one more way is to declare the public constructor with default value

#define DEFAULT_CAR_INIT 0
Car::Car(int _no=DEFAULT_CAR_INIT);

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes '20201231' but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME) to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:

CREATE TABLE dbo.T(D DATETIME)

--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')

Warnings in the execution plan

--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))

No warnings

Error in <my code> : object of type 'closure' is not subsettable

You don't define the vector, url, before trying to subset it. url is also a function in the base package, so url[i] is attempting to subset that function... which doesn't make sense.

You probably defined url in your prior R session, but forgot to copy that code to your script.

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

How to clear an EditText on click?

For me the easiest way... Create an public EditText, for Example "myEditText1"

public EditText myEditText1;

Then, connect it with the EditText which should get cleared

myEditText1 = (EditText) findViewById(R.id.numberfield);

After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example

@OnClick(R.id.numberfield)
        void textGone(){
            if (myEditText1.isFocused()){
                myEditText1.setText("");

        }
    }

Hope i could help you, Have a nice Day everyone

Getting the name / key of a JToken with JSON.net

The default iterator for the JObject is as a dictionary iterating over key/value pairs.

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
    Console.WriteLine (pair.Key);
}

Passing parameters in rails redirect_to

As of Rails 6, you can simply call redirect_to followed by the path you wish to redirect to such as home_path, and then pass is a hash of key-value pairs.

example:

redirect_to home_path(name: 'Jason', needs: 'help with rails', help: true)

After this, you will be able to retrieve these values from the params hash.

ex

params[:name]

to retrieve the string 'Jason'

How to hide status bar in Android

If you refer to the Google Documents you can use this method for android 4.1 and above, call this method before setContentView()

public void hideStatusBar() {
    View view = getWindow().getDecorView();
    int uiOption = View.SYSTEM_UI_FLAG_FULLSCREEN;
    view.setSystemUiVisibility(uiOption);
    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.hide();
    }
}

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

How to set the allowed url length for a nginx request (error code: 414, uri too large)

From: http://nginx.org/r/large_client_header_buffers

Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.

How do you append to an already existing string?

#!/bin/bash
message="some text"
message="$message add some more"

echo $message

some text add some more

Qt jpg image display

I want to display .jpg image in an Qt UI

The simpliest way is to use QLabel for this:

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    QLabel label("<img src='image.jpg' />");
    label.show();
    return a.exec();
}

How to discard uncommitted changes in SourceTree?

Do as follow,

  • Click on commit
  • Select all by pressing CMD+A that you want to delete or discard
  • Right click on the selected uncommitted files that you want to delete
  • Select Remove from the drop-down list

jQuery Call to WebService returns "No Transport" error

I too got this problem and all solutions given above either failed or were not applicable due to client webservice restrictions.

For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.

We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.

Hope it helps

<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
 </iframe>

//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');

//The iframe receives the data using the code:
window.onload = function () {
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    eventer(messageEvent, function (e) {
        var origin = e.origin;
        //if origin not in pre-defined list, break and return
        var messageFromParent = JSON.parse(e.data);
        var json = messageFromParent.data;

        //send json to web service using AJAX   
        //return the response back to source
        e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
    }, false);
}

Do fragments really need an empty constructor?

Yes, as you can see the support-package instantiates the fragments too (when they get destroyed and re-opened). Your Fragment subclasses need a public empty constructor as this is what's being called by the framework.

Programmatically change the height and width of a UIImageView Xcode Swift

u can use this code

var imageView = UIImageView(image: UIImage(name:"imageName"));
imageView.frame = CGrectMake(x,y imageView.frame.width*0.2,50);

or

var imageView = UIImageView(frame:CGrectMake(x,y, self.view.frame.size.width *0.2, 50)

Get value of Span Text

_x000D_
_x000D_
var span_Text = document.getElementById("span_Id").innerText;_x000D_
_x000D_
console.log(span_Text)
_x000D_
<span id="span_Id">I am the Text </span>
_x000D_
_x000D_
_x000D_

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

trigger body click with jQuery

if all things were said didn't work, go back to basics and test if this is working:

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      $('body').click(function() {
        // do something here like:
        alert('hey! The body click is working!!!')
      });
    </script>
  </body>
</html>

then tell me if its working or not.

How to make an HTTP request + basic auth in Swift

swift 4:

let username = "username"
let password = "password"
let loginString = "\(username):\(password)"

guard let loginData = loginString.data(using: String.Encoding.utf8) else {
    return
}
let base64LoginString = loginData.base64EncodedString()

request.httpMethod = "GET"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

Running Bash commands in Python

Call it with subprocess

import subprocess
subprocess.Popen("cwm --rdf test.rdf --ntriples > test.nt")

The error you are getting seems to be because there is no swap module on the server, you should install swap on the server then run the script again

Is it possible to override / remove background: none!important with jQuery?

Why does not it work? Because the background CSS with background:none!important has one #ID

A CSS selector file that contains an #id will always have a higher value than one .class

If you want to work, you need add #id on your .image-list li like this:

#an-element .image-list li {
    display: inline-block;
    background-image: url("http://placekitten.com/150/50")!important;
    padding: 1em;
    border: 1px solid blue;
}

result here

Bootstrap: How do I identify the Bootstrap version?

To check what version you currently have, you can use -v for the command line/console terminal.

bootstrap -v

https://www.npmjs.com/package/bootstrap-cli

Using ORDER BY and GROUP BY together

Just you need to desc with asc. Write the query like below. It will return the values in ascending order.

SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;

MySQL duplicate entry error even though there is no duplicate entry

For me a noop on table has been enough (was already InnoDB):

ALTER TABLE $tbl ENGINE=InnoDB;

Add a duration to a moment (moment.js)

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

UILabel - auto-size label to fit text?

@implementation UILabel (UILabel_Auto)

- (void)adjustHeight {

    if (self.text == nil) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
        return;
    }

    CGSize aSize = self.bounds.size;
    CGSize tmpSize = CGRectInfinite.size;
    tmpSize.width = aSize.width;

    tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}

@end

This is category method. You must set text first, than call this method to adjust UILabel's height.

How to Diff between local uncommitted changes and origin

Given that the remote repository has been cached via git fetch it should be possible to compare against these commits. Try the following:

$ git fetch origin
$ git diff origin/master

Validate date in dd/mm/yyyy format using JQuery Validate

I encountered a similar problem in my project. After struggling a lot, I found this solution:

if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
    // do something

You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.

Draw path between two points using Google Maps Android API v2

First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.

 public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json");
        urlString.append("?origin=");// from
        urlString.append(Double.toString(sourcelat));
        urlString.append(",");
        urlString.append(Double.toString( sourcelog));
        urlString.append("&destination=");// to
        urlString.append(Double.toString( destlat));
        urlString.append(",");
        urlString.append(Double.toString( destlog));
        urlString.append("&sensor=false&mode=driving&alternatives=true");
        urlString.append("&key=YOUR_API_KEY");
        return urlString.toString();
 }

This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public String getJSONFromUrl(String url) {

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

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

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

This parser will return us string. We will call it like that.

JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);

Now we will send this string to our drawpath function. The drawpath function is

public void drawPath(String  result) {

    try {
            //Tranform the string into a json object
           final JSONObject json = new JSONObject(result);
           JSONArray routeArray = json.getJSONArray("routes");
           JSONObject routes = routeArray.getJSONObject(0);
           JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
           String encodedString = overviewPolylines.getString("points");
           List<LatLng> list = decodePoly(encodedString);
           Polyline line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(12)
                                    .color(Color.parseColor("#05b1fb"))//Google maps blue color
                                    .geodesic(true)
                    );
           /*
           for(int z = 0; z<list.size()-1;z++){
                LatLng src= list.get(z);
                LatLng dest= list.get(z+1);
                Polyline line = mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
                .width(2)
                .color(Color.BLUE).geodesic(true));
            }
           */
    } 
    catch (JSONException e) {

    }
} 

Above code will draw the path on mMap. The code of decodePoly is

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng( (((double) lat / 1E5)),
                 (((double) lng / 1E5) ));
        poly.add(p);
    }

    return poly;
}

As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was

private class connectAsyncTask extends AsyncTask<Void, Void, String>{
    private ProgressDialog progressDialog;
    String url;
    connectAsyncTask(String urlPass){
        url = urlPass;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching route, Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }
    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        String json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);   
        progressDialog.hide();        
        if(result!=null){
            drawPath(result);
        }
    }
}

I hope it will help.

How would I find the second largest salary from the employee table?

To find second max salary from employee,

SELECT MAX(salary) FROM employee
WHERE salary NOT IN (
    SELECT MAX (salary) FROM employee
)

To find first and second max salary from employee,

SELECT salary FROM (
    SELECT DISTINCT(salary) FROM employee ORDER BY salary DESC
) WHERE rownum<=2

This queries are working fine because i have used

submit a form in a new tab

It is also possible to use the new button attribute called formtarget that was introduced with HTML5.

<form>
  <input type="submit" formtarget="_blank"/>
</form>

Loading local JSON file

If you are using a local array for JSON - as you showed in your example in the question (test.json) then you can is the parseJSON() method of JQuery ->

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

getJSON() is used for getting JSON from a remote site - it will not work locally (unless you are using a local HTTP Server)

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

How to read a text-file resource into Java unit test?

First make sure that abc.xml is being copied to your output directory. Then you should use getResourceAsStream():

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");

Once you have the InputStream, you just need to convert it into a string. This resource spells it out: http://www.kodejava.org/examples/266.html. However, I'll excerpt the relevent code:

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {        
        return "";
    }
}

How to vertically center <div> inside the parent element with CSS?

Centering the child elements in a div. It works for all screen sizes

#parent {
    padding: 5% 0;
}

#child {
    padding: 10% 0;
}

<div id="parent">
    <div id="child">Content here</div>
</div>

for more details, you can visit to this link

Select from one table where not in another

So there's loads of posts on the web that show how to do this, I've found 3 ways, same as pointed out by Johan & Sjoerd. I couldn't get any of these queries to work, well obviously they work fine it's my database that's not working correctly and those queries all ran slow.

So I worked out another way that someone else may find useful:

The basic jist of it is to create a temporary table and fill it with all the information, then remove all the rows that ARE in the other table.

So I did these 3 queries, and it ran quickly (in a couple moments).

CREATE TEMPORARY TABLE

`database1`.`newRows`

SELECT

`t1`.`id` AS `columnID`

FROM

`database2`.`table` AS `t1`

.

CREATE INDEX `columnID` ON `database1`.`newRows`(`columnID`)

.

DELETE FROM `database1`.`newRows`

WHERE

EXISTS(
    SELECT `columnID` FROM `database1`.`product_details` WHERE `columnID`=`database1`.`newRows`.`columnID`
)

Installing mcrypt extension for PHP on OSX Mountain Lion

I tend to use Homebrew on Mac. It will install and configure all the stuff for you.
http://mxcl.github.com/homebrew/

Then you should be able to install it with brew install mcrypt php53-mcrypt and it'll Just Work (tm).

You can replace the 53 with whatever version of PHP you're using, such as php56-mcrypt or php70-mcrypt. If you're not sure, use brew search php.

Do also remember that if you are using the built in Mac PHP it's installed into /usr/bin you can see which php you are using with which php at the terminal and it'll return the path.

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

Switch/toggle div (jQuery)

This is how I toggle two divs at the same time:

$('#login-form, #recover-password').toggle();

It works!

Preferred way to create a Scala list

And for simple cases:

val list = List(1,2,3) 

:)

How do I display images from Google Drive on a website?

List View

<iframe src="https://drive.google.com/embeddedfolderview?id=YOURID#list" width="700" height="500" frameborder="0"></iframe>

Grid View

<iframe src="https://drive.google.com/embeddedfolderview?id=YOURID#grid" width="700" height="500" frameborder="0"></iframe>

Read More at: https://thomas.vanhoutte.be/miniblog/embed-add-google-drive-folder-file-website/

How to iterate through property names of Javascript object?

In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj )

and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

Object.keys( obj )

I used forEach to list values and keys in obj, same as for (var key in obj) ..

Object.keys(obj).forEach(function (key) {
      console.log( key , obj[key] );
});

This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

http://developer.android.com/guide/topics/location/obtaining-user-location.html

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

How to check if an environment variable exists and get its value?

There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.

You can check if a variable is defined:

if [ -z "$a" ]
then
    echo "not defined"
else 
    echo "defined"
fi

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

Is there a way to catch the back button event in javascript?

onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.

Angular 2 - innerHTML styling

If you're trying to style dynamically added HTML elements inside an Angular component, this might be helpful:

// inside component class...
    
constructor(private hostRef: ElementRef) { }
    
getContentAttr(): string {
  const attrs = this.hostRef.nativeElement.attributes
  for (let i = 0, l = attrs.length; i < l; i++) {
    if (attrs[i].name.startsWith('_nghost-c')) {
      return `_ngcontent-c${attrs[i].name.substring(9)}`
    }
  }
}
    
ngAfterViewInit() {
  // dynamically add HTML element
  dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')
}

My guess is that the convention for this attribute is not guaranteed to be stable between versions of Angular, so that one might run into problems with this solution when upgrading to a new version of Angular (although, updating this solution would likely be trivial in that case).

ReactJS lifecycle method inside a function Component

You can make your own "lifecycle methods" using hooks for maximum nostalgia.

Utility functions:

import { useEffect, useRef } from "react";

export const useComponentDidMount = handler => {
  return useEffect(() => {
    return handler();
  }, []);
};

export const useComponentDidUpdate = (handler, deps) => {
  const isInitialMount = useRef(true);

  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;

      return;
    }

    return handler();
  }, deps);
};

Usage:

import { useComponentDidMount, useComponentDidUpdate } from "./utils";

export const MyComponent = ({ myProp }) => {
  useComponentDidMount(() => {
    console.log("Component did mount!");
  });

  useComponentDidUpdate(() => {
    console.log("Component did update!");
  });

  useComponentDidUpdate(() => {
    console.log("myProp did update!");
  }, [myProp]);
};  

Call Class Method From Another Class

You can call a function from within a class with:

A().method1()

Error in model.frame.default: variable lengths differ

Joran suggested to first remove the NAs before running the model. Thus, I removed the NAs, run the model and obtained the residuals. When I updated model2 by inclusion of the lagged residuals, the error message did not appear again.

Remove NAs

df2<-df1[complete.cases(df1),]

Run the main model

model2<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5), data=df2, family=poisson)

Obtain residuals

resid2 <- residuals(model2,type="deviance")

Update model2 by including the lag 1 residuals

model2_1 <- update(model2,.~.+ Lag(resid2,1),  na.action=na.omit)

flow 2 columns of text automatically with CSS

Automatically floating two columns next to eachother is not currently possible only with CSS/HTML. Two ways to achieve this:

Method 1: When there's no continous text, just lots of non-related paragraphs:

Float all paragraphs to the left, give them half the width of the containing element and if possible set a fixed height.

<div id="container">
  <p>This is paragraph 1. Lorem ipsum ... </p>
  <p>This is paragraph 2. Lorem ipsum ... </p>
  <p>This is paragraph 3. Lorem ipsum ... </p>
  <p>This is paragraph 4. Lorem ipsum ... </p>
  <p>This is paragraph 5. Lorem ipsum ... </p>
  <p>This is paragraph 6. Lorem ipsum ... </p>
</div>

#container { width: 600px; }
#container p { float: left; width: 300px; /* possibly also height: 300px; */ }

You can also insert clearer-divs between paragraphs to avoid having to use a fixed height. If you want two columns, add a clearer-div between two-and-two paragraphs. This will align the top of the two next paragraphs, making it look more tidy. Example:

<div id="container">
  <p>This is paragraph 1. Lorem ipsum ... </p>
  <p>This is paragraph 2. Lorem ipsum ... </p>
  <div class="clear"></div>
  <p>This is paragraph 3. Lorem ipsum ... </p>
  <p>This is paragraph 4. Lorem ipsum ... </p>
  <div class="clear"></div>
  <p>This is paragraph 5. Lorem ipsum ... </p>
  <p>This is paragraph 6. Lorem ipsum ... </p>
</div>

/* in addition to the above CSS */
.clear { clear: both; height: 0; }

Method 2: When the text is continous

More advanced, but it can be done.

<div id="container">
  <div class="contentColumn">
    <p>This is paragraph 1. Lorem ipsum ... </p>
    <p>This is paragraph 2. Lorem ipsum ... </p>
    <p>This is paragraph 3. Lorem ipsum ... </p>
  </div>
  <div class="contentColumn">
    <p>This is paragraph 4. Lorem ipsum ... </p>
    <p>This is paragraph 5. Lorem ipsum ... </p>
    <p>This is paragraph 6. Lorem ipsum ... </p>
  </div>
</div>

.contentColumn { width: 300px; float: left; }
#container { width: 600px; }

When it comes to the ease of use: none of these are really easy for a non-technical client. You might attempt to explain to him/her how to do this properly, and tell him/her why. Learning very basic HTML is not a bad idea anyways, if the client is going to be updating the web pages via a WYSIWYG-editor in the future.

Or you could try to implement some Javascript-solution that counts the total number of paragraphs, splits them in two and creates columns. This will also degrade gracefully for those who have JavaScript disabled. A third option is to have all this splitting-into-columns-action happen serverside if this is an option.

(Method 3: CSS3 Multi-column Layout Module)

You might read about the CSS3 way of doing it, but it's not really practical for a production website. Not yet, at least.

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

In general, you can't do this in any straightforward fashion. time_point is essentially just a duration from a clock-specific epoch.

If you have a std::chrono::system_clock::time_point, then you can use std::chrono::system_clock::to_time_t to convert the time_point to a time_t, and then use the normal C functions such as ctime or strftime to format it.


Example code:

std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(tp);
std::tm timetm = *std::localtime(&time);
std::cout << "output : " << std::put_time(&timetm, "%c %Z") << "+"
          << std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch()).count() % 1000 << std::endl;

joining two select statements

SELECT *
FROM
  (First_query) AS ONE
LEFT OUTER JOIN
  (Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;

Python iterating through object attributes

Iterate over an objects attributes in python:

class C:
    a = 5
    b = [1,2,3]
    def foobar():
        b = "hi"    

for attr, value in C.__dict__.iteritems():
    print "Attribute: " + str(attr or "")
    print "Value: " + str(value or "")

Prints:

python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:

Python concatenate text files

What's wrong with UNIX commands ? (given you're not working on Windows) :

ls | xargs cat | tee output.txt does the job ( you can call it from python with subprocess if you want)

Want to show/hide div based on dropdown box selection

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      //.....................^.......
      {
           $("#business_new").hide();
        $("#business").show();
      }
      else  if ( this.value == '2')
      {
          $("#business").hide();
        $("#business_new").show();
      }
       else  
      {
        $("#business").hide();
      }
    });
});
</script>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
<div style='display:none;' id='business_new'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value="1254" size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
</body>

Event when window.location.href changes

Through Jquery, just try

$(window).on('beforeunload', function () {
    //your code goes here on location change 
});

By using javascript:

window.addEventListener("beforeunload", function (event) {
   //your code goes here on location change 
});

Refer Document : https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

How can I get the values of data attributes in JavaScript code?

You can access it as

element.dataset.points

etc. So in this case: this.dataset.points

Have a fixed position div that needs to scroll if content overflows

The solutions here didn't work for me as I'm styling react components.

What worked though for the sidebar was

.sidebar{
position: sticky;
top: 0;
}

Hope this helps someone.

Python and SQLite: insert into table

#The Best way is to use `fStrings` (very easy and powerful in python3)   
#Format: f'your-string'   
#For Example:

mylist=['laks',444,'M']

cursor.execute(f'INSERT INTO mytable VALUES ("{mylist[0]}","{mylist[1]}","{mylist[2]}")')

#THATS ALL!! EASY!!
#You can use it with for loop!

How can I get the MAC and the IP address of a connected client in PHP?

Perhaps getting the Mac address is not the best approach for verifying a client's machine over the internet. Consider using a token instead which is stored in the client's browser by an administrator's login.

Therefore the client can only have this token if the administrator grants it to them through their browser. If the token is not present or valid then the client's machine is invalid.

php: check if an array has duplicates

$hasDuplicates = count($array) > count(array_unique($array)); 

Will be true if duplicates, or false if no duplicates.

Why not use tables for layout in HTML?

1: Yes, your users do care. If they use a screen reader, it will be lost. If I use any other tool which tries to extract information from the page, encountering tables that aren't used to represent tabular data is misleading.

A div or span is acceptable for separating content because that is precisely the meaning of those elements. When I, a search engine, a screen reader or anything else, encounter a table element, we expect that this means "the following is tabular data, represented in a table". When we encounter a div, we expect "this is an element used to divide my content into separate parts or areas.

2: Readability: Wrong. If all the presentation code is in css, I can read the html and I'll understand the content of the page. Or I can read the css and understand the presentation. If everything is jumbled together in the html, I have to mentally strike out all the presentation-related bits before I can even see what is content and what isn't. Moreover, I'd be scared to meet a web developer who didn't understand css, so I really don't think that is an issue.

3: Tables are slower: Yes, they are. The reason is simple: Tables have to be parsed completely, including their contents before they can be rendered. A div can be rendered when it is encountered, even before its contents have been parsed. That means divs will show up before the page has finished loading.

And then there's the bonus, that tables are much more fragile, and won't always be rendered the same in different browsers, with different fonts and font sizes and all the other factors that can cause layout to vary. Tables are an excellent way to ensure that your site will be off by a pixel or two in certain browsers, won't scale well when the user changes his font size, or changes his settings in any other way.

Of course #1 is the big one. A lot of tools and applications depend on the semantic meaning of a webpage. The usual example is screen-readers for visually impaired users. If you're a web developer, you'll find that many large companies who may otherwise hire you to work on a site, require that the site is accessible even in this case. Which means you have to think about the semantic meaning of your html. With the semantic web, or more relevantly, microformats, rss readers and other tools, your page content is no longer viewed exclusively through a browser.

The "backspace" escape character '\b': unexpected behavior?

If you want a destructive backspace, you'll need something like

"\b \b"

i.e. a backspace, a space, and another backspace.

Get year, month or day from numpy datetime64

Anon's answer works great for me, but I just need to modify the statement for days

from:

days = dates - dates.astype('datetime64[M]') + 1

to:

days = dates.astype('datetime64[D]') - dates.astype('datetime64[M]') + 1

How to obtain Telegram chat_id for a specific user?

Whenever user communicate with bot it send information like below:

$response = {
        "update_id":640046715,
        "message":{
            "message_id":1665,
            "from":{"id":108177xxxx,"is_bot":false,"first_name":"Suresh","last_name":"Kamrushi","language_code":"en"},
            "chat":{"id":108xxxxxx,"first_name":"Suresh","last_name":"Kamrushi","type":"private"},
            "date":1604381276,
            "text":"1"            
            }        
        }

So you can access chat it like:
$update["message"]["chat"]["id"]

Assuming you are using PHP.

include external .js file in node.js app

If you just want to test a library from the command line, you could do:

cat somelibrary.js mytestfile.js | node

Now() function with time trim

Dates in VBA are just floating point numbers, where the integer part represents the date and the fraction part represents the time. So in addition to using the Date function as tlayton says (to get the current date) you can also cast a date value to a integer to get the date-part from an arbitrary date: Int(myDateValue).

How to draw interactive Polyline on route google maps v2 android

I've created a couple of map tutorials that will cover what you need

Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.

Take a look at these 2 tutorials and the Github project containing the sample app.

It contains some tips to make your code cleaner and more efficient:

  • Using Google HTTP Library for more efficient API access and easy JSON handling.
  • Using google-map-utils library for maps-related functions (like decoding the polylines)
  • Animating markers