Programs & Examples On #Transactions

A set of interrelated operations that must all succeed in order for any of them to succeed. Failure of any operation results in a rollback of all operations in the transaction.

Correct use of flush() in JPA/Hibernate

Probably the exact details of em.flush() are implementation-dependent. In general anyway, JPA providers like Hibernate can cache the SQL instructions they are supposed to send to the database, often until you actually commit the transaction. For example, you call em.persist(), Hibernate remembers it has to make a database INSERT, but does not actually execute the instruction until you commit the transaction. Afaik, this is mainly done for performance reasons.

In some cases anyway you want the SQL instructions to be executed immediately; generally when you need the result of some side effects, like an autogenerated key, or a database trigger.

What em.flush() does is to empty the internal SQL instructions cache, and execute it immediately to the database.

Bottom line: no harm is done, only you could have a (minor) performance hit since you are overriding the JPA provider decisions as regards the best timing to send SQL instructions to the database.

How to debug Lock wait timeout exceeded on MySQL?

For the record, the lock wait timeout exception happens also when there is a deadlock and MySQL cannot detect it, so it just times out. Another reason might be an extremely long running query, which is easier to solve/repair, however, and I will not describe this case here.

MySQL is usually able to deal with deadlocks if they are constructed "properly" within two transactions. MySQL then just kills/rollback the one transaction that owns fewer locks (is less important as it will impact less rows) and lets the other one finish.

Now, let's suppose there are two processes A and B and 3 transactions:

Process A Transaction 1: Locks X
Process B Transaction 2: Locks Y
Process A Transaction 3: Needs Y => Waits for Y
Process B Transaction 2: Needs X => Waits for X
Process A Transaction 1: Waits for Transaction 3 to finish

(see the last two paragraph below to specify the terms in more detail)

=> deadlock 

This is a very unfortunate setup because MySQL cannot see there is a deadlock (spanned within 3 transactions). So what MySQL does is ... nothing! It just waits, since it does not know what to do. It waits until the first acquired lock exceeds the timeout (Process A Transaction 1: Locks X), then this will unblock the Lock X, which unlocks Transaction 2 etc.

The art is to find out what (which query) causes the first lock (Lock X). You will be able to see easily (show engine innodb status) that Transaction 3 waits for Transaction 2, but you will not see which transaction Transaction 2 is waiting for (Transaction 1). MySQL will not print any locks or query associated with Transaction 1. The only hint will be that at the very bottom of the transaction list (of the show engine innodb status printout), you will see Transaction 1 apparently doing nothing (but in fact waiting for Transaction 3 to finish).

The technique for how to find which SQL query causes the lock (Lock X) to be granted for a given transaction that is waiting is described here Tracking MySQL query history in long running transactions

If you are wondering what the process and the transaction is exactly in the example. The process is a PHP process. Transaction is a transaction as defined by innodb-trx-table. In my case, I had two PHP processes, in each I started a transaction manually. The interesting part was that even though I started one transaction in a process, MySQL used internally in fact two separate transactions (I don't have a clue why, maybe some MySQL dev can explain).

MySQL is managing its own transactions internally and decided (in my case) to use two transactions to handle all the SQL requests coming from the PHP process (Process A). The statement that Transaction 1 is waiting for Transaction 3 to finish is an internal MySQL thing. MySQL "knew" the Transaction 1 and Transaction 3 were actually instantiated as part of one "transaction" request (from Process A). Now the whole "transaction" was blocked because Transaction 3 (a subpart of "transaction") was blocked. Because "transaction" was not able to finish the Transaction 1 (also a subpart of the "transaction") was marked as not finished as well. This is what I meant by "Transaction 1 waits for Transaction 3 to finish".

What is a database transaction?

Transaction - is just a logically composed set of operations you want all together be either committed or rolled back.

Best way to work with transactions in MS SQL Server Management Studio

I want to add a point that you can also (and should if what you are writing is complex) add a test variable to rollback if you are in test mode. Then you can execute the whole thing at once. Often I also add code to see the before and after results of various operations especially if it is a complex script.

Example below:

USE AdventureWorks;
GO
DECLARE @TEST INT = 1--1 is test mode, use zero when you are ready to execute
BEGIN TRANSACTION;

BEGIN TRY
     IF @TEST= 1
        BEGIN
            SELECT *FROM Production.Product
                WHERE ProductID = 980;
        END    
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;

     IF @TEST= 1
        BEGIN
            SELECT *FROM Production.Product
                WHERE ProductID = 980;
            IF @@TRANCOUNT > 0
                ROLLBACK TRANSACTION;
        END    
END TRY

BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0 AND @TEST = 0
    COMMIT TRANSACTION;
GO

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

"The operation is not valid for the state of the transaction" error and transaction scope

I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

Oracle: How to find out if there is a transaction pending?

Use the query below to find out pending transaction.

If it returns a value, it means there is a pending transaction.

Here is the query:

select dbms_transaction.step_id from dual;

References:
http://www.acehints.com/2011/07/how-to-check-pending-transaction-in.html http://www.acehints.com/p/site-map.html

How to commit and rollback transaction in sql server?

Don't use @@ERROR, use BEGIN TRY/BEGIN CATCH instead. See this article: Exception handling and nested transactions for a sample procedure:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

Is there a way to list open transactions on SQL Server 2000 database?

Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0

SQL Server - transactions roll back on error?

If one of the inserts fail, or any part of the command fails, does SQL server roll back the transaction?

No, it does not.

If it does not rollback, do I have to send a second command to roll it back?

Sure, you should issue ROLLBACK instead of COMMIT.

If you want to decide whether to commit or rollback the transaction, you should remove the COMMIT sentence out of the statement, check the results of the inserts and then issue either COMMIT or ROLLBACK depending on the results of the check.

Transaction marked as rollback only: How do I find the cause

apply the below code in productRepository

@Query("update Product set prodName=:name where prodId=:id ") @Transactional @Modifying int updateMyData(@Param("name")String name, @Param("id") Integer id);

while in junit test apply below code

@Test
public void updateData()
{
  int i=productRepository.updateMyData("Iphone",102);

  System.out.println("successfully updated ... ");
  assertTrue(i!=0);

}

it is working fine for my code

What happens if you don't commit a transaction to a database (say, SQL Server)?

The behaviour is not defined, so you must explicit set a commit or a rollback:

http://docs.oracle.com/cd/B10500_01/java.920/a96654/basic.htm#1003303

"If auto-commit mode is disabled and you close the connection without explicitly committing or rolling back your last changes, then an implicit COMMIT operation is executed."

Hsqldb makes a rollback

con.setAutoCommit(false);
stmt.executeUpdate("insert into USER values ('" +  insertedUserId + "','Anton','Alaf')");
con.close();

result is

2011-11-14 14:20:22,519 main INFO [SqlAutoCommitExample:55] [AutoCommit enabled = false] 2011-11-14 14:20:22,546 main INFO [SqlAutoCommitExample:65] [Found 0# users in database]

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

After logging in, on the home page of the Server Console you should see 3 sections:

  • Information and Resources
  • Domain Configurations
  • Services Configurations

Under Services Configurations there is subsection Other Services. Click the JTA Configuration link under Other Services. The transaction timeout should be the top setting on the page displayed, labelled Timeout Seconds.

Weblogic Console screenshot

Does Spring @Transactional attribute work on a private method?

By default the @Transactional attribute works only when calling an annotated method on a reference obtained from applicationContext.

public class Bean {
  public void doStuff() {
    doTransactionStuff();
  }
  @Transactional
  public void doTransactionStuff() {

  }
}

This will open a transaction:

Bean bean = (Bean)appContext.getBean("bean");
bean.doTransactionStuff();

This will not:

Bean bean = (Bean)appContext.getBean("bean");
bean.doStuff();

Spring Reference: Using @Transactional

Note: In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!

Consider the use of AspectJ mode (see below) if you expect self-invocations to be wrapped with transactions as well. In this case, there won't be a proxy in the first place; instead, the target class will be 'weaved' (i.e. its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.

sql try/catch rollback/commit - preventing erroneous commit after rollback

Transaction counter

--@@TRANCOUNT = 0
begin try
--@@TRANCOUNT = 0
BEGIN TRANSACTION tran1
 --@@TRANCOUNT = 1

        --your code
        -- if failed  @@TRANCOUNT = 1
        -- if success @@TRANCOUNT = 0

COMMIT TRANSACTION tran1

end try

begin catch
    print 'FAILED'
end catch

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

There are a few misunderstandings in the discussion above.

First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.

As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:

 IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION @transaction

Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)

This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.

As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.

Laravel: Using try...catch with DB::transaction()

If you use PHP7, use Throwable in catch for catching user exceptions and fatal errors.

For example:

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

If your code must be compartable with PHP5, use Exception and Throwable:

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    throw $e;
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

Credit card payment gateway in PHP?

There are more than a few gateways out there, but I am not aware of a reliable gateway that is free. Most gateways like PayPal will provide you APIs that will allow you to process credit cards, as well as do things like void, charge, or refund.

The other thing you need to worry about is the coming of PCI compliance which basically says if you are not compliant, you (or the company you work for) will be liable by your Merchant Bank and/or Card Vendor for not being compliant by July of 2010. This will impose large fines on you and possibly revoke the ability for you to process credit cards.

All that being said companies like PayPal have a PHP SDK:

https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_download_sdks

Authorize.Net:

http://developer.authorize.net/samplecode/

Those are two of the more popular ones for the United States.

For PCI Info see:

https://www.pcisecuritystandards.org/

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

Error message looks like this

Error message => ORA-00001: unique constraint (schema.unique_constraint_name) violated

ORA-00001 occurs when: "a query tries to insert a "duplicate" row in a table". It makes an unique constraint to fail, consequently query fails and row is NOT added to the table."

Solution:

Find all columns used in unique_constraint, for instance column a, column b, column c, column d collectively creates unique_constraint and then find the record from source data which is duplicate, using following queries:

-- to find <<owner of the table>> and <<name of the table>> for unique_constraint

select *
from DBA_CONSTRAINTS
where CONSTRAINT_NAME = '<unique_constraint_name>';

Then use Justin Cave's query (pasted below) to find all columns used in unique_constraint:

  SELECT column_name, position
  FROM all_cons_columns
  WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

    -- to find duplicates

    select column a, column b, column c, column d
    from table
    group by column a, column b, column c, column d
    having count (<any one column used in constraint > ) > 1;

you can either delete that duplicate record from your source data (which was a select query in my particular case, as I experienced it with "Insert into select") or modify to make it unique or change the constraint.

Correct use of transactions in SQL Server

Easy approach:

CREATE TABLE T
(
    C [nvarchar](100) NOT NULL UNIQUE,
);

SET XACT_ABORT ON -- Turns on rollback if T-SQL statement raises a run-time error.
SELECT * FROM T; -- Check before.
BEGIN TRAN
    INSERT INTO T VALUES ('A');
    INSERT INTO T VALUES ('B');
    INSERT INTO T VALUES ('B');
    INSERT INTO T VALUES ('C');
COMMIT TRAN
SELECT * FROM T; -- Check after.
DELETE T;

Transactions in .net

protected void Button1_Click(object sender, EventArgs e)
   {


       using (SqlConnection connection1 = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"))
       {
           connection1.Open();

           // Start a local transaction.
           SqlTransaction sqlTran = connection1.BeginTransaction();

           // Enlist a command in the current transaction.
           SqlCommand command = connection1.CreateCommand();
           command.Transaction = sqlTran;

           try
           {
               // Execute two separate commands.
               command.CommandText =
                "insert into [doctor](drname,drspecialization,drday) values ('a','b','c')";
               command.ExecuteNonQuery();
               command.CommandText =
                "insert into [doctor](drname,drspecialization,drday) values ('x','y','z')";
               command.ExecuteNonQuery();

               // Commit the transaction.
               sqlTran.Commit();
               Label3.Text = "Both records were written to database.";
           }
           catch (Exception ex)
           {
               // Handle the exception if the transaction fails to commit.
               Label4.Text = ex.Message;


               try
               {
                   // Attempt to roll back the transaction.
                   sqlTran.Rollback();
               }
               catch (Exception exRollback)
               {
                   // Throws an InvalidOperationException if the connection 
                   // is closed or the transaction has already been rolled 
                   // back on the server.
                   Label5.Text = exRollback.Message;

               }
           }
       }


   }

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

I had this problem when trying to delete a certain group of records (using MS Access 2007 with an ODBC connection to MySQL on a web server). Typically I would delete certain records from MySQL then replace with updated records (cascade delete several related records, this streamlines deleting all related records for a single record deletion).

I tried to run through the operations available in phpMyAdmin for the table (optimize,flush, etc), but I was getting a need permission to RELOAD error when I tried to flush. Since my database is on a web server, I couldn't restart the database. Restoring from a backup was not an option.

I tried running delete query for this group of records on the cPanel mySQL access on the web. Got same error message.

My solution: I used Sun's (Oracle's) free MySQL Query Browser (that I previously installed on my computer) and ran the delete query there. It worked right away, Problem solved. I was then able to once again perform the function using the Access script using the ODBC Access to MySQL connection.

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

I was also facing same issue.

Here is the cause and solution.

http://blogs.msdn.com/b/cbiyikoglu/archive/2006/11/21/mars-transactions-and-sql-error-3997-3988-or-3983.aspx

Make sure before firing data manipulation commands like inserts, updates, you have closed all previous active SQL readers.

Most common error is functions that read data from db and return values. For e.g functions like isRecordExist.

In this case we immediately return from the function if we found the record and forget to close the reader.

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
//OR    
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
//OR    
SET autocommit = ON;

Is there an API to get bank transaction and bank balance?

I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.

Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.

In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.

This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.

OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory

Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx

Spring @Transactional read-only propagation

It seem to ignore the settings for the current active transaction, it only apply settings to a new transaction:

org.springframework.transaction.PlatformTransactionManager
TransactionStatus getTransaction(TransactionDefinition definition)
                         throws TransactionException
Return a currently active transaction or create a new one, according to the specified propagation behavior.
Note that parameters like isolation level or timeout will only be applied to new transactions, and thus be ignored when participating in active ones.
Furthermore, not all transaction definition settings will be supported by every transaction manager: A proper transaction manager implementation should throw an exception when unsupported settings are encountered.
An exception to the above rule is the read-only flag, which should be ignored if no explicit read-only mode is supported. Essentially, the read-only flag is just a hint for potential optimization.

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

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

When to use SELECT ... FOR UPDATE?

Short answers:

Q1: Yes.

Q2: Doesn't matter which you use.

Long answer:

A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

Another way of looking at it, it is as if the following two statements are executed atomically:

select * from my_table where my_condition;

update my_table set my_column = my_column where my_condition;

Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.

PHP + MySQL transactions examples

<?php

// trans.php
function begin(){
    mysql_query("BEGIN");
}

function commit(){
    mysql_query("COMMIT");
}

function rollback(){
    mysql_query("ROLLBACK");
}

mysql_connect("localhost","Dude1", "SuperSecret") or die(mysql_error());

mysql_select_db("bedrock") or die(mysql_error());

$query = "INSERT INTO employee (ssn,name,phone) values ('123-45-6789','Matt','1-800-555-1212')";

begin(); // transaction begins

$result = mysql_query($query);

if(!$result){
    rollback(); // transaction rolls back
    echo "transaction rolled back";
    exit;
}else{
    commit(); // transaction is committed
    echo "Database transaction was successful";
}

?>

How do ACID and database transactions work?

I slightly modified the printer example to make it more explainable

1 document which had 2 pages content was sent to printer

Transaction - document sent to printer

  • atomicity - printer prints 2 pages of a document or none
  • consistency - printer prints half page and the page gets stuck. The printer restarts itself and prints 2 pages with all content
  • isolation - while there were too many print outs in progress - printer prints the right content of the document
  • durability - while printing, there was a power cut- printer again prints documents without any errors

Hope this helps someone to get the hang of the concept of ACID

Where does the @Transactional annotation belong?

@Transactional Annotations should be placed around all operations that are inseparable. Using @Transactional transaction propagation are handled automatically.In this case if another method is called by current method,then that method will have the option of joining the ongoing transaction.

So lets take example:

We have 2 model's i.e. Country and City. Relational Mapping of Country and City model is like one Country can have multiple Cities so mapping is like,

@OneToMany(fetch = FetchType.LAZY, mappedBy="country")
private Set<City> cities;

Here Country mapped to multiple cities with fetching them Lazily. So here comes role of @Transactinal when we retrieve Country object from database then we will get all the data of Country object but will not get Set of cities because we are fetching cities LAZILY.

//Without @Transactional
public Country getCountry(){
   Country country = countryRepository.getCountry();
   //After getting Country Object connection between countryRepository and database is Closed 
}

When we want to access Set of Cities from country object then we will get null values in that Set because object of Set created only this Set is not initialize with there data to get values of Set we use @Transactional i.e.,

//with @Transactional
@Transactional
public Country getCountry(){
   Country country = countryRepository.getCountry();
   //below when we initialize cities using object country so that directly communicate with database and retrieve all cities from database this happens just because of @Transactinal
   Object object = country.getCities().size();   
}

So basically @Transactional is Service can make multiple call in single transaction without closing connection with end point.

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,

BEGIN

    .. Declare statements ..

    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
          .. set any flags etc  eg. SET @flag = 0; ..
          ROLLBACK;
    END;

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;
    .. eg. SET @flag = 1; ..

END

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

This is for others (like me :) ). Don't forget to add the spring tx jar/maven dependency. Also correct configuration in appctx is:

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

, by mistake wrong configuration which others may have

xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

i.e., extra "/spring-tx-3.1.xsd"

xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

in other words what is there in xmlns(namespace) should have proper mapping in schemaLocation (namespace vs schema).

namespace here is : http://www.springframework.org/schema/tx

schema Doc Of namespace is : http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

this schema of namespace later is mapped in jar to locate the path of actual xsd located in org.springframework.transaction.config

how to automatically scroll down a html page?

Use document.scrollTop to change the position of the document. Set the scrollTop of the document equal to the bottom of the featured section of your site

How do I perform query filtering in django templates

I just add an extra template tag like this:

@register.filter
def in_category(things, category):
    return things.filter(category=category)

Then I can do:

{% for category in categories %}
  {% for thing in things|in_category:category %}
    {{ thing }}
  {% endfor %}
{% endfor %}

iPhone SDK on Windows (alternative solutions)

I looked into this before buying a Mac Mini. The answer is, essentially, no. You pretty much have to buy a Leopard Mac to do iPhone SDK development for apps that run on non-jailbroken iPhones.

Not that it's 100% impossible, but it's 99.99% unreasonable. Like changing light bulbs with your feet.

Not only do you have to be in Xcode, but you have to get certificates into the Keychain manager to be able to have Xcode and the iPhone communicate. And you have to set all kinds of setting in Xcode just right.

How to remove the first Item from a list?

With list slicing, see the Python tutorial about lists for more details:

>>> l = [0, 1, 2, 3, 4]
>>> l[1:]
[1, 2, 3, 4]

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

Determine if 2 lists have the same elements, regardless of order?

As mentioned in comments above, the general case is a pain. It is fairly easy if all items are hashable or all items are sortable. However I have recently had to try solve the general case. Here is my solution. I realised after posting that this is a duplicate to a solution above that I missed on the first pass. Anyway, if you use slices rather than list.remove() you can compare immutable sequences.

def sequences_contain_same_items(a, b):
    for item in a:
        try:
            i = b.index(item)
        except ValueError:
            return False
        b = b[:i] + b[i+1:]
    return not b

How can I implement the Iterable interface?

Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.

So I would at least change it to:

public class ProfileCollection implements Iterable<Profile> { 
    private ArrayList<Profile> m_Profiles;

    public Iterator<Profile> iterator() {        
        Iterator<Profile> iprof = m_Profiles.iterator();
        return iprof; 
    }

    ...

    public Profile GetActiveProfile() {
        return (Profile)m_Profiles.get(m_ActiveProfile);
    }
}

and this should work:

for (Profile profile : m_PC) {
    // do stuff
}

Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:

for (Object profile : m_PC) {
    // do stuff
}

This is a pretty obscure corner case of Java generics.

If not, please provide some more info about what's going on.

How do I reformat HTML code using Sublime Text 2?

HTML-CSS-JS Prettify - Hands down the best.

  1. Install Package Control
  2. ? + left shift + p (or ctrl + alt + left shift + p) -> Package Control: Install Package
  3. Enter HTML-CSS-JS Prettify
  4. Install node
  5. Restart Sublime Text

Enjoy.

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

First, set customErrors = "Off" in the web.config and redeploy to get a more detailed error message that will help us diagnose the problem. You could also RDP into the instance and browse to the site from IIS locally to view the errors.

<system.web>
      <customErrors mode="Off" />

First guess though - you have some references (most likely Azure SDK references) that are not set to Copy Local = true. So, all your dependencies are not getting deployed.

Get to the detailed error first and update your question.

UPDATE: A second option now available in VS2013 is Remote Debugging a Cloud Service or Virtual Machine.

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

How do I count cells that are between two numbers in Excel?

If you have Excel 2007 or later use COUNTIFS with an "S" on the end, i.e.

=COUNTIFS(B2:B292,">10",B2:B292,"<10000")

You may need to change commas , to semi-colons ;

In earlier versions of excel use SUMPRODUCT like this

=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))

Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=

How to find pg_config path

To summarize -- PostgreSQL installs its files (including its binary or executable files) in different locations, depending on the version number and the installation method.

Some of the possibilities:

/usr/local/bin/
/Library/PostgreSQL/9.2/bin/
/Applications/Postgres93.app/Contents/MacOS/bin/
/Applications/Postgres.app/Contents/Versions/9.3/bin/

No wonder people get confused!

Also, if your $PATH environment variable includes a path to the directory that includes an executable file (to confirm this, use echo $PATH on the command line) then you can run which pg_config, which psql, etc. to find out where the file is located.

Integer.valueOf() vs. Integer.parseInt()

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.

How can I change image source on click with jQuery?

You need to use preventDefault() to make it so the link does not go through when u click on it:

fiddle: http://jsfiddle.net/maniator/Sevdm/

$(function() {
 $('.menulink').click(function(e){
     e.preventDefault();
   $("#bg").attr('src',"img/picture1.jpg");
 });
});

Is there a date format to display the day of the week in java?

I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:

new SimpleDateFormat("u").format(new Date());

returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.

How to convert Varchar to Int in sql server 2008?

There are two type of convert method in SQL.

CAST and CONVERT have similar functionality. CONVERT is specific to SQL Server, and allows for a greater breadth of flexibility when converting between date and time values, fractional numbers, and monetary signifiers. CAST is the more ANSI-standard of the two functions.

Using Convert

Select convert(int,[Column1])

Using Cast

Select cast([Column1] as int)

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msgs) {
        //write your code hear which give error
        }
        }

new Thread(new Runnable() {
    @Override
    public void run() {
    handler.sendEmptyMessage(1);
        //this will call handleMessage function and hendal all error
    }
    }).start();

Calculating percentile of dataset column

Using {dplyr}:

library(dplyr)

# percentiles
infert %>% 
  mutate(PCT = ntile(age, 100))

# quartiles
infert %>% 
  mutate(PCT = ntile(age, 4))

# deciles
infert %>% 
  mutate(PCT = ntile(age, 10))

Does Java support structs?

With Project JUnion you can use structs in Java by annotating a class with @Struct annotation

@Struct
class Member {
  string FirstName; 
  string LastName;  
  int BirthYear; 
}

More info at the project's website: https://tehleo.github.io/junion/

Difference between os.getenv and os.environ.get

One difference observed (Python27):

os.environ raises an exception if the environmental variable does not exist. os.getenv does not raise an exception, but returns None

what is .subscribe in angular?

.subscribe is not an Angular2 thing.

It's a method that comes from rxjs library which Angular is using internally.

If you can imagine yourself subscribing to a newsletter, every time there is a new newsletter, they will send it to your home (the method inside subscribe gets called).

That's what happens when you subscribing to a source of magazines ( which is called an Observable in rxjs library)

All the AJAX calls in Angular are using rxjs internally and in order to use any of them, you've got to use the method name, e.g get, and then call subscribe on it, because get returns and Observable.

Also, when writing this code <button (click)="doSomething()">, Angular is using Observables internally and subscribes you to that source of event, which in this case is a click event.

Back to our analogy of Observables and newsletter stores, after you've subscribed, as soon as and as long as there is a new magazine, they'll send it to you unless you go and unsubscribe from them for which you have to remember the subscription number or id, which in rxjs case it would be like :

 let subscription = magazineStore.getMagazines().subscribe(
   (newMagazine)=>{

         console.log('newMagazine',newMagazine);

    }); 

And when you don't want to get the magazines anymore:

   subscription.unsubscribe();

Also, the same goes for

 this.route.paramMap

which is returning an Observable and then you're subscribing to it.

My personal view is rxjs was one of the greatest things that were brought to JavaScript world and it's even better in Angular.

There are 150~ rxjs methods ( very similar to lodash methods) and the one that you're using is called switchMap

How to retrieve the dimensions of a view?

You should rather look at View lifecycle: http://developer.android.com/reference/android/view/View.html Generally you should not know width and height for sure until your activity comes to onResume state.

Setting up SSL on a local xampp/apache server

Apache part - enabling you to open https://localhost/xyz

There is the config file xampp/apache/conf/extra/httpd-ssl.conf which contains all the ssl specific configuration. It's fairly well documented, so have a read of the comments and take look at http://httpd.apache.org/docs/2.2/ssl/. The files starts with <IfModule ssl_module>, so it only has an effect if the apache has been started with its mod_ssl module.

Open the file xampp/apache/conf/httpd.conf in an editor and search for the line

#LoadModule ssl_module modules/mod_ssl.so

remove the hashmark, save the file and re-start the apache. The webserver should now start with xampp's basic/default ssl confguration; good enough for testing but you might want to read up a bit more about mod_ssl in the apache documentation.


PHP part - enabling adldap to use ldap over ssl

adldap needs php's openssl extension to use "ldap over ssl" connections. The openssl extension ships as a dll with xampp. You must "tell" php to load this dll, e.g. by having an extension=nameofmodule.dll in your php.ini
Run

echo 'ini: ', get_cfg_var('cfg_file_path');

It should show you which ini file your php installation uses (may differ between the php-apache-module and the php-cli version).
Open this file in an editor and search for

;extension=php_openssl.dll

remove the semicolon, save the file and re-start the apache.

see also: http://docs.php.net/install.windows.extensions

Editing specific line in text file in Python

If your text contains only one individual:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def roplo(file_name,what):
    patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
    with open(file_name,'rb+') as f:
        ch = f.read()
        f.seek(0)
        f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')


# after treatment
with open('pers.txt','rb') as h:
    print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If your text contains several individuals:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim  \n  dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def ripli(file_name,who,what):
    with open(file_name,'rb+') as f:
        ch = f.read()
        x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
        f.seek(x)
        f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')


# after treatment
with open('pers.txt','rb') as h:
    print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual: that’s the same idea as senderle’s one.

But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:

from cPickle import dump, load

with open('cards','wb') as f:
    dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)

with open('cards','rb') as g:
    id_cards = load(g)
print 'id_cards before change==',id_cards

id_cards['Jim'][0] = 'Wizard'

with open('cards','w') as h:
    dump(id_cards,h)

with open('cards') as e:
    id_cards = load(e)
print '\nid_cards after change==',id_cards

How to delete a folder in C++?

My own implementation based off hB0 that also allows you to view the number of files in each folder also with a little performance boost.

#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <windows.h>
#include <conio.h>

union seperated {
  struct {
    unsigned int low;
    unsigned int high;
  } uint;
  unsigned long long ull;
};

unsigned long long num_dirs  = 1;
unsigned long long num_files = 0;
seperated size_files;

int DeleteDirectory( char* refRootDirectory );      //predeclare it

int DeleteDirectory( char* refRootDirectory ) {
    HANDLE      hFile;              // Handle to directory
    std::string strFilePath;            // Filepath
    WIN32_FIND_DATA FileInformation;    // File information
    int     dwError;            // Folder deleting error
    std::string strPattern;         // Pattern

    strPattern = (std::string)(refRootDirectory) + "\\*.*";
    hFile = ::FindFirstFile( strPattern.c_str(), &FileInformation );

    if( hFile != INVALID_HANDLE_VALUE )
    {
        do {
            if( FileInformation.cFileName[0] != '.' ) {
                strFilePath.erase();
                strFilePath = std::string(refRootDirectory) + "\\" + FileInformation.cFileName;

                if( FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
                    DeleteDirectory( (char*)strFilePath.c_str() );

                    dwError = ::GetLastError();
                    if( dwError != ERROR_NO_MORE_FILES ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return dwError;
                    } else {
                        // Set directory attributes
                        if( ! ::SetFileAttributes(refRootDirectory,FILE_ATTRIBUTE_NORMAL) ) {
                            std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                            return ::GetLastError();
                        }

                        // Delete directory
                        if( ! ::RemoveDirectory(refRootDirectory) ) {
                            std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                            return ::GetLastError();
                        }
                    }

                    ++num_dirs;
                } else {

                    // Set file attributes
                    if( ! ::SetFileAttributes(strFilePath.c_str(),FILE_ATTRIBUTE_NORMAL) ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return ::GetLastError();
                    }

                    // Delete file
                    if ( ! ::DeleteFile(strFilePath.c_str()) ) {
                        std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
                        return ::GetLastError();
                    }

                    size_files.ull       += FileInformation.nFileSizeLow;
                    size_files.uint.high += FileInformation.nFileSizeHigh;

                    ++num_files;
                }
            }
        } while( ::FindNextFile(hFile,&FileInformation) );

        // Close handle
        ::FindClose( hFile  );
    }

    return 0;
}

unsigned long long num_files_total=0;
unsigned long long num_dirs_total=0;
unsigned long long total_size_files=0;

void my_del_directory( char* dir_name ) {
    int iRC = DeleteDirectory( dir_name );
    //int iRC=0;

    std::cout << "\"" << dir_name << "\""
             "\n    Folders: " << num_dirs
          << "\n    Files:   " << num_files
          << "\n    Size:    " << size_files.ull << " Bytes";
    if(iRC)
    {
        std::cout << "\n!ERROR!: " << iRC;
    }
    std::cout << "\n\n";

    num_dirs_total   += num_dirs;
    num_files_total  += num_files;
    total_size_files += size_files.ull;
    num_dirs  = 1;
    num_files = 0;
    size_files.ull = 0ULL;
    return;
}

int main( void )
{
    size_files.ull = 0ULL;

    my_del_directory( (char*)"C:\Windows\temp"      );
        // This will clear out the System temporary directory on windows systems

    std::cout << "\n\nResults" << "\nTotal Folders: " << num_dirs_total
                   << "\nTotal Files:   " << num_files_total
                   << "\nTotal Size:    " << total_size_files << " Bytes\n";

    return 0;
}

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Swing vs JavaFx for desktop applications

I don't think there's any one right answer to this question, but my advice would be to stick with SWT unless you are encountering severe limitations that require such a massive overhaul.

Also, SWT is actually newer and more actively maintained than Swing. (It was originally developed as a replacement for Swing using native components).

Get free disk space

I wanted a similar method for my project but in my case the input paths were either from local disk volumes or clustered storage volumes (CSVs). So DriveInfo class did not work for me. CSVs have a mount point under another drive, typically C:\ClusterStorage\Volume*. Note that C: will be a different Volume than C:\ClusterStorage\Volume1

This is what I finally came up with:

    public static ulong GetFreeSpaceOfPathInBytes(string path)
    {
        if ((new Uri(path)).IsUnc)
        {
            throw new NotImplementedException("Cannot find free space for UNC path " + path);
        }

        ulong freeSpace = 0;
        int prevVolumeNameLength = 0;

        foreach (ManagementObject volume in
                new ManagementObjectSearcher("Select * from Win32_Volume").Get())
        {
            if (UInt32.Parse(volume["DriveType"].ToString()) > 1 &&                             // Is Volume monuted on host
                volume["Name"] != null &&                                                       // Volume has a root directory
                path.StartsWith(volume["Name"].ToString(), StringComparison.OrdinalIgnoreCase)  // Required Path is under Volume's root directory 
                )
            {
                // If multiple volumes have their root directory matching the required path,
                // one with most nested (longest) Volume Name is given preference.
                // Case: CSV volumes monuted under other drive volumes.

                int currVolumeNameLength = volume["Name"].ToString().Length;

                if ((prevVolumeNameLength == 0 || currVolumeNameLength > prevVolumeNameLength) &&
                    volume["FreeSpace"] != null
                    )
                {
                    freeSpace = ulong.Parse(volume["FreeSpace"].ToString());
                    prevVolumeNameLength = volume["Name"].ToString().Length;
                }
            }
        }

        if (prevVolumeNameLength > 0)
        {
            return freeSpace;
        }

        throw new Exception("Could not find Volume Information for path " + path);
    }

How to generate .env file for laravel?

Just tried both ways and in both ways I got generated .env file:

enter image description here

Composer should automatically create .env file. In the post-create-project-cmd section of the composer.json you can find:

"post-create-project-cmd": [
  "php -r \"copy('.env.example', '.env');\"",
  "php artisan key:generate"
]

Both ways use the same composer.json file, so there shoudn't be any difference.

I suggest you to update laravel/installer to the last version: 1.2 and try again:

composer global require "laravel/installer=~1.2"

You can always generate .env file manually by running:

cp .env.example .env
php artisan key:generate

How to use jQuery to show/hide divs based on radio button selection?

<script type="text/javascript">
$(function() {
    $("[name=toggler]").click(function(){
            $('.toHide').hide();
            $("#blk-"+$(this).val()).show('slow');
    });
 });
</script>
</head>
<body>
<label><input id="rdb1" type="radio" name="toggler" value="1" />Book</label>
<label><input id="rdb2" type="radio" name="toggler" value="2" />Non-Book</label>

<div id="blk-1" class="toHide" style="display:none">

    <form action="success1.html">

        Name1:<input type="text" name="name">
             <input type="submit" name="submit">

    </form>

</div>
<div id="blk-2" class="toHide" style="display:none">

    <form action="success1.html">

        Name2:<input type="text" name="name">
             <input type="submit" name="submit">

    </form>
</div>

How to stop BackgroundWorker correctly

In my case, I had to pool database for payment confirmation to come in and then update WPF UI.

Mechanism that spins up all the processes:

public void Execute(object parameter)
        {
            try
            {
                var url = string.Format("{0}New?transactionReference={1}", Settings.Default.PaymentUrlWebsite, "transactionRef");
                Process.Start(new ProcessStartInfo(url));
                ViewModel.UpdateUiWhenDoneWithPayment = new BackgroundWorker {WorkerSupportsCancellation = true};
                ViewModel.UpdateUiWhenDoneWithPayment.DoWork += ViewModel.updateUiWhenDoneWithPayment_DoWork;
                ViewModel.UpdateUiWhenDoneWithPayment.RunWorkerCompleted += ViewModel.updateUiWhenDoneWithPayment_RunWorkerCompleted;
                ViewModel.UpdateUiWhenDoneWithPayment.RunWorkerAsync();
            }
            catch (Exception e)
            {
                ViewModel.Log.Error("Failed to navigate to payments", e);
                MessageBox.Show("Failed to navigate to payments");
            }
        }

Mechanism that does checking for completion:

 private void updateUiWhenDoneWithPayment_DoWork(object sender, DoWorkEventArgs e)
    {
        Thread.Sleep(30000);
        while (string.IsNullOrEmpty(GetAuthToken()) && !((BackgroundWorker)sender).CancellationPending)
        {
            Thread.Sleep(5000);
        }

        //Plug in pooling mechanism
        this.AuthCode = GetAuthToken();
    }

Mechanism that cancels if window gets closed:

private void PaymentView_OnUnloaded(object sender, RoutedEventArgs e)
    {
        var context = DataContext as PaymentViewModel;
        if (context.UpdateUiWhenDoneWithPayment != null && context.UpdateUiWhenDoneWithPayment.WorkerSupportsCancellation && context.UpdateUiWhenDoneWithPayment.IsBusy)
            context.UpdateUiWhenDoneWithPayment.CancelAsync();
    }

How to deal with http status codes other than 200 in Angular 2

Include required imports and you can make ur decision in handleError method Error status will give the error code

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model'; 

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side or network error occurred. Handle it accordingly.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend returned an unsuccessful response code.
  // The response body may contain clues as to what went wrong,
  console.error(
    `Backend returned code ${error.status}, ` +
    `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
  };

  getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
  catchError(this.handleError)
);
  }

How to insert current datetime in postgresql insert query

timestamp (or date or time columns) do NOT have "a format".

Any formatting you see is applied by the SQL client you are using.


To insert the current time use current_timestamp as documented in the manual:

INSERT into "Group" (name,createddate) 
VALUES ('Test', current_timestamp);

To display that value in a different format change the configuration of your SQL client or format the value when SELECTing the data:

select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"

For psql (the default command line client) you can configure the display format through the configuration parameter DateStyle: https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE

std::string length() and size() member functions

length of string ==how many bits that string having, size==size of those bits, In strings both are same if the editor allocates size of character is 1 byte

OpenCV - DLL missing, but it's not?

I followed instructions on http://opencv.willowgarage.com/wiki/VisualC%2B%2B_VS2010 but was still stuck on exactly the same problem, so here's how I resolved it.

  1. Fetched MSVC 2010 express edition.

  2. Fetched Win 32 OpenCV 2.2 binaries and installed in default location.

  3. Created new project.

  4. Project setup

    Project -> OpenCV_Helloworld Properties...Configuration Properties -> VC++ Directories

    Include Directories... add: C:\OpenCV2.2\include\;

    Library Directories... add: C:\OpenCV2.2\lib;C:\OpenCV2.2\bin;

    Source Directories... add:

    C:\OpenCV2.2\modules\calib3d\src;C:\OpenCV2.2\modules\contrib\src;C:\OpenCV2.2\modules\core\src;C:\OpenCV2.2\modules\features2d\src;C:\OpenCV2.2\modules\flann\src;C:\OpenCV2.2\modules\gpu\src;C:\OpenCV2.2\modules\gpu\src;C:\OpenCV2.2\modules\highgui\src;C:\OpenCV2.2\modules\imgproc\src;C:\OpenCV2.2\modules\legacy\src;C:\OpenCV2.2\modules\ml\src;C:\OpenCV2.2\modules\objdetect\src;C:\OpenCV2.2\modules\video\src;
    

    Linker -> Input -> Additional Dependencies...

    For Debug Builds... add:

    opencv_calib3d220d.lib;opencv_contrib220d.lib;opencv_core220d.lib;opencv_features2d220d.lib;opencv_ffmpeg220d.lib;opencv_flann220d.lib;opencv_gpu220d.lib;opencv_highgui220d.lib;opencv_imgproc220d.lib;opencv_legacy220d.lib;opencv_ml220d.lib;opencv_objdetect220d.lib;opencv_video220d.lib;
    

At this point I thought I was done, but ran into the problem you described when running the exe in debug mode. The final step is obvious once you see it, select:

Linker -> General ... Set 'Use Library Dependency Inputs' to 'Yes'

Hope this helps.

How to get nth jQuery element

If you already have the jquery object in a variable, you can also just treat it as a normal indexed array, without the use of jquery:

var all_rows = $("tr");
for(var i=0; i < all_rows.length; i++){
   var row = all_rows[i];
   //additionally, you can use it again in a jquery selector
   $(row).css("background-color","black");
}

Although the above example is not useful in any way, it is representing how you can treat objects created by jquery as indexed arrays.

How to only get file name with Linux 'find'?

If you want to run some action against the filename only, using basename can be tough.

For example this:

find ~/clang+llvm-3.3/bin/ -type f -exec echo basename {} \; 

will just echo basename /my/found/path. Not what we want if we want to execute on the filename.

But you can then xargs the output. for example to kill the files in a dir based on names in another dir:

cd dirIwantToRMin;
find ~/clang+llvm-3.3/bin/ -type f -exec basename {} \; | xargs rm

Debugging in Maven?

I thought I would expand on these answers for OSX and Linux folks (not that they need it):

I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.

$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found

DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.

I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)

Let's see:

$ which mvn
/usr/local/bin/mvn

There you are... you little b@stard.

Now where did you get installed to:

$ ls -l /usr/local/bin/mvn

lrwxr-xr-x  1 root  wheel  39 Oct 31 13:00 /
                  /usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn

Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...

Do you have your little buddy mvnDebug with you?

$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug 
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug

Good. Good. Very good. All going as planned.

Now move that little b@stard where I can remember him more easily.

$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
  ln: /usr/local/bin/mvnDebug: Permission denied

Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!

$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug

Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)

$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000

Internally mvnDebug uses this:

MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE  \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"

So you could modify it (I usually debug on port 9090).

This blog explains how to setup Eclipse remote debugging (shudder)

http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html

Ditto Netbeans

https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a

Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html

Here is some good docs on the -Xdebug command in general.

http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."

"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."

-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp

Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.

How to check if a process is running via a batch script

The answer provided by Matt Lacey works for Windows XP. However, in Windows Server 2003 the line

 tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

returns

INFO: No tasks are running which match the specified criteria.

which is then read as the process is running.

I don't have a heap of batch scripting experience, so my soulution is to then search for the process name in the search.log file and pump the results into another file and search that for any output.

tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

FINDSTR notepad.exe search.log > found.log

FOR /F %%A IN (found.log) DO IF %%~zA EQU 0 GOTO end

start notepad.exe

:end

del search.log
del found.log

I hope this helps someone else.

How to use sessions in an ASP.NET MVC 4 application?

You can store any kind of data in a session using:

Session["VariableName"]=value;

This variable will last 20 mins or so.

Hexadecimal To Decimal in Shell Script

Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.

One more that's not on his list:

[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816

But if all you want to do is subtract, why bother changing the input to base 10?

[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$ 

The dc command is "desk calc". It will also take input from stdin, like bc, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.

In the commands above we've got the following:

  • 16i -- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.
  • BFCA3000 -- your initial number
  • 17FF -- a random hex number I picked to subtract from your initial number
  • - -- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stack
  • p -- print the last item on the stack. This doesn't change the stack, so...
  • 10o -- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".
  • p -- print the last item on the stack again ... this time in hex.

You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.

PHP - Check if two arrays are equal

Short solution that works even with arrays which keys are given in different order:

public static function arrays_are_equal($array1, $array2)
{
    array_multisort($array1);
    array_multisort($array2);
    return ( serialize($array1) === serialize($array2) );
}

Response.Redirect to new window

I just found the answer and it works :)

You need to add the following to your server side link/button:

OnClientClick="aspnetForm.target ='_blank';"

My entire button code looks something like:

<asp:LinkButton ID="myButton" runat="server" Text="Click Me!" 
                OnClick="myButton_Click" 
                OnClientClick="aspnetForm.target ='_blank';"/>

In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window.

The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.

<script type="text/javascript">
    function fixform() {
        if (opener.document.getElementById("aspnetForm").target != "_blank") return;
        opener.document.getElementById("aspnetForm").target = "";
        opener.document.getElementById("aspnetForm").action = opener.location.href;
    }
</script>

and

<body onload="fixform()">

Programmatically get height of navigation bar

iOS 14

For me, view.window is null on iOS 14.

extension UIViewController {
    var topBarHeight: CGFloat {
        var top = self.navigationController?.navigationBar.frame.height ?? 0.0
        if #available(iOS 13.0, *) {
            top += UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
        } else {
            top += UIApplication.shared.statusBarFrame.height
        }
        return top
    }
}

How to get selected value of a dropdown menu in ReactJS

You can handle it all within the same function as following

_x000D_
_x000D_
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>_x000D_
_x000D_
  <option value="5">5 dollars</option>_x000D_
  <option value="10">10 dollars</option>_x000D_
                                         _x000D_
</select>
_x000D_
_x000D_
_x000D_

as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!

Increment a Integer's int value?

All the primitive wrapper objects are immutable.

I'm maybe late to the question but I want to add and clarify that when you do playerID++, what really happens is something like this:

playerID = Integer.valueOf( playerID.intValue() + 1);

Integer.valueOf(int) will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

How to convert timestamps to dates in Bash?

While not pure bash, the following script will convert timestamps of length 13 in a string to their equivalent date in your local timezone using perl

timestamp_to_date.sh

#!/usr/bin/env bash
IT=$(cat /dev/stdin)
re='(.*)([0-9]{13})(.*)'
while [[ $IT =~ $re ]]; do
  TIMESTAMP=${BASH_REMATCH[2]}
  AS_DATE=$(echo "$TIMESTAMP" | perl -pe 's/([\d]{10})([\d]{3})/localtime $1/eg;')
  IT="${IT/$TIMESTAMP/$AS_DATE}"    
done
echo "$IT"

input

{"timestamp":"1573121629939","level":"DEBUG","thread":"http-nio-15372-exec-3","logger":"org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor"}

output

$ cat input | timestamp_to_date.sh

{"timestamp":"Thu Nov  7 06:13:49 2019","level":"DEBUG","thread":"http-nio-15372-exec-3","logger":"org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor"}

Encode a FileStream to base64 with c#

An easy one as an extension method

public static class Extensions
{
    public static Stream ConvertToBase64(this Stream stream)
    {
        byte[] bytes;
        using (var memoryStream = new MemoryStream())
        {
            stream.CopyTo(memoryStream);
            bytes = memoryStream.ToArray();
        }

        string base64 = Convert.ToBase64String(bytes);
        return new MemoryStream(Encoding.UTF8.GetBytes(base64));
    }
}

How to open a web server port on EC2 instance

Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".

Go to the "Network & Security" -> Security Group settings in the left hand navigation

enter image description here Find the Security Group that your instance is apart of Click on Inbound Rules enter image description here Use the drop down and add HTTP (port 80) enter image description here Click Apply and enjoy

Chrome desktop notification example

Notify.js is a wrapper around the new webkit notifications. It works pretty well.

http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/

Command to delete all pods in all kubernetes namespaces

You can use kubectl delete pods -l dev-lead!=carisa or what label you have.

Proper use of the IDisposable interface

IDisposable is often used to exploit the using statement and take advantage of an easy way to do deterministic cleanup of managed objects.

public class LoggingContext : IDisposable {
    public Finicky(string name) {
        Log.Write("Entering Log Context {0}", name);
        Log.Indent();
    }
    public void Dispose() {
        Log.Outdent();
    }

    public static void Main() {
        Log.Write("Some initial stuff.");
        try {
            using(new LoggingContext()) {
                Log.Write("Some stuff inside the context.");
                throw new Exception();
            }
        } catch {
            Log.Write("Man, that was a heavy exception caught from inside a child logging context!");
        } finally {
            Log.Write("Some final stuff.");
        }
    }
}

Get fragment (value after hash '#') from a URL in php

You can't get the text after the hash mark. It is not sent to the server in a request.

Howto? Parameters and LIKE statement SQL

Your visual basic code would look something like this:

Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')")

cmd.Parameters.Add("@query", searchString)

How to copy a row from one SQL Server table to another

Jarrett's answer creates a new table.

Scott's answer inserts into an existing table with the same structure.

You can also insert into a table with different structure:

INSERT Table2
(columnX, columnY)
SELECT column1, column2 FROM Table1
WHERE [Conditions]

Count number of objects in list

Let's create an empty list (not required, but good to know):

> mylist <- vector(mode="list")

Let's put some stuff in it - 3 components/indexes/tags (whatever you want to call it) each with differing amounts of elements:

> mylist <- list(record1=c(1:10),record2=c(1:5),record3=c(1:2))

If you are interested in just the number of components in a list use:

> length(mylist)
[1] 3

If you are interested in the length of elements in a specific component of a list use: (both reference the same component here)

length(mylist[[1]])
[1] 10
length(mylist[["record1"]]
[1] 10

If you are interested in the length of all elements in all components of the list use:

> sum(sapply(mylist,length))
[1] 17

insert multiple rows into DB2 database

UPDATE - Even less wordy version

INSERT INTO tableName (col1, col2, col3, col4, col5) 
VALUES ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5')

The following also works for DB2 and is slightly less wordy

INSERT INTO tableName (col1, col2, col3, col4, col5) 
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5')

Jquery Chosen plugin - dynamically populate list by Ajax

var object = $("#lstValue_chosen").find('.chosen-choices').find('input[type="text"]')[0];
var _KeyCode = event.which || event.keyCode;
if (_KeyCode != 37 && _KeyCode != 38 && _KeyCode != 39 && _KeyCode != 40) { 

    if (object.value != "") {
        var SelectedObjvalue = object.value;
        if (SelectedObjvalue.length > 0) {
            var obj = { value: SelectedObjvalue };
            var SelectedListValue = $('#lstValue').val();
            var Uniqueid = $('#uniqueid').val();

            $.ajax({
                url: '/Admin/GetUserListBox?SelectedValue=' + SelectedListValue + '&Uniqueid=' + Uniqueid,
                data: { value: SelectedObjvalue },
                type: 'GET',
                async: false,
                success: function (response) {
                    if (response.length > 0) {
                        $('#lstValue').html('');
                        var options = '';                            
                        $.each(response, function (i, obj) {
                            options += '<option value="' + obj.Value + '">' + obj.Text + '</option>';
                        });
                        $('#lstValue').append(options);
                        $('#lstValue').val(SelectedListValue);
                        $('#lstValue').trigger("chosen:updated");
                        object.value = SelectedObjvalue;
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    //jAlert("Error. Please, check the data.", " Deactivate User");
                    alert(error.StatusText);
                }
            });
        }
    }
}

Is there an R function for finding the index of an element in a vector?

A small note about the efficiency of abovementioned methods:

 library(microbenchmark)

  microbenchmark(
    which("Feb" == month.abb)[[1]],
    which(month.abb %in% "Feb"))

  Unit: nanoseconds
   min     lq    mean median     uq  max neval
   891  979.0 1098.00   1031 1135.5 3693   100
   1052 1175.5 1339.74   1235 1390.0 7399  100

So, the best one is

    which("Feb" == month.abb)[[1]]

Including a .js file within a .js file

A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.

Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.

You may then want to run the resulting concatenation through a minification tool like jsmin to have it minified.

Invalid character in identifier

The error SyntaxError: invalid character in identifier means you have some character in the middle of a variable name, function, etc. that's not a letter, number, or underscore. The actual error message will look something like this:

  File "invalchar.py", line 23
    values =  list(analysis.values ())
                ^
SyntaxError: invalid character in identifier

That tells you what the actual problem is, so you don't have to guess "where do I have an invalid character"? Well, if you look at that line, you've got a bunch of non-printing garbage characters in there. Take them out, and you'll get past this.

If you want to know what the actual garbage characters are, I copied the offending line from your code and pasted it into a string in a Python interpreter:

>>> s='    values ??=  list(analysis.values ??())'
>>> s
'    values \u200b\u200b=  list(analysis.values \u200b\u200b())'

So, that's \u200b, or ZERO WIDTH SPACE. That explains why you can't see it on the page. Most commonly, you get these because you've copied some formatted (not plain-text) code off a site like StackOverflow or a wiki, or out of a PDF file.

If your editor doesn't give you a way to find and fix those characters, just delete and retype the line.

Of course you've also got at least two IndentationErrors from not indenting things, at least one more SyntaxError from stay spaces (like = = instead of ==) or underscores turned into spaces (like analysis results instead of analysis_results).

The question is, how did you get your code into this state? If you're using something like Microsoft Word as a code editor, that's your problem. Use a text editor. If not… well, whatever the root problem is that caused you to end up with these garbage characters, broken indentation, and extra spaces, fix that, before you try to fix your code.

Remove all special characters except space from a string using JavaScript

Try this:

const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);

CSS: Set Div height to 100% - Pixels

Alternatively, you can just use position:absolute:

#content
{
    position:absolute;
    top: 111px;
    bottom: 0px;
}

However, IE6 doesn't like top and bottom declarations. But web developers don't like IE6.

how to pass parameters to query in SQL (Excel)

This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.

This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.

So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.

Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))

What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.

First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:

[Picture of a cell of prompt (label) text, an empty cell, then a button.]

Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.

Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).

Sub RefreshQuery()
 Dim queryPreText As String
 Dim queryPostText As String
 Dim valueToFilter As String
 Dim paramPosition As Integer
 valueToFilter = "DB_TABLE_NAME.Field_Name ="

 With ActiveWorkbook.Connections("Connection name").OLEDBConnection
     queryPreText = .CommandText
     paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
     queryPreText = Left(queryPreText, paramPosition)
     queryPostText = .CommandText
     queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
     queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
     .CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
 End With
 ActiveWorkbook.Connections("Connection name").Refresh
End Sub

Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).

Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).

Save and close the VBA editor.

Enter your parameter in the appropriate cell.

Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!

Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".

This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.

Compiling/Executing a C# Source File in Command Prompt

Another way to compile C# programs (without using Visual Studio or without having it installed) is to create a user variable in environment variables, namely "PATH".

Copy the following path in this variable:

"C:\Windows\Microsoft.NET\Framework\v4.0.30319"

or depending upon which .NET your PC have.

So you don't have to mention the whole path every time you compile a code. Simply use

"C:\Users\UserName\Desktop>csc [options] filename.cs"

or wherever the path of your code is.

Now you are good to go.

Using :before CSS pseudo element to add image to modal

Content and before are both highly unreliable across browsers. I would suggest sticking with jQuery to accomplish this. I'm not sure what you're doing to figure out if this carrot needs to be added or not, but you should get the overall idea:

$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");

What is output buffering?

The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

http://php.net/manual/en/book.outcontrol.php

More Resources:

Output Buffering With PHP

Right click to select a row in a Datagridview and show a menu to delete it

I finally solved it:

  • In Visual Studio, create a ContextMenuStrip with an item called "DeleteRow"

  • Then at the DataGridView link the ContextMenuStrip

Using the code below helped me getting it work.

this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);

Here is the cool part

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        var hti = MyDataGridView.HitTest(e.X, e.Y);
        MyDataGridView.ClearSelection();
        MyDataGridView.Rows[hti.RowIndex].Selected = true;
    }
}

private void DeleteRow_Click(object sender, EventArgs e)
{
    Int32 rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
    MyDataGridView.Rows.RemoveAt(rowToDelete);
    MyDataGridView.ClearSelection();
}

Extracting extension from filename in Python

With splitext there are problems with files with double extension (e.g. file.tar.gz, file.tar.bz2, etc..)

>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension 
'.gz'

but should be: .tar.gz

The possible solutions are here

get the data of uploaded file in javascript

The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.

<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>

  <body onload="init()">
    <input id="fileInput" type="file" name="file" />
    <pre id="fileContent"></pre>
  </body>
</html>

script.js

function init(){
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(event){
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])
}

function handleFileLoad(event){
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
}

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Check your JNI/native code. One of my references was null, but it was intermittent, so it wasn't very obvious.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.

You should pass your connection object in as a dependency, eg

function getPosts(mysqli $con) {
    // etc

I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");

getPosts($con);

How to define constants in Visual C# like #define in C?

in c language: #define (e.g. #define counter 100)

in assembly language: equ (e.g. counter equ 100)

in c# language: according to msdn refrence: You use #define to define a symbol. When you use the symbol as the expression that's passed to the #if directive, the expression will evaluate to true, as the following example shows:

# define DEBUG

The #define directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.

Service Reference Error: Failed to generate code for the service reference

face same issue, resolved by running Visual Studio in Admin mode

Named capturing groups in JavaScript regex?

While you can't do this with vanilla JavaScript, maybe you can use some Array.prototype function like Array.prototype.reduce to turn indexed matches into named ones using some magic.

Obviously, the following solution will need that matches occur in order:

_x000D_
_x000D_
// @text Contains the text to match_x000D_
// @regex A regular expression object (f.e. /.+/)_x000D_
// @matchNames An array of literal strings where each item_x000D_
//             is the name of each group_x000D_
function namedRegexMatch(text, regex, matchNames) {_x000D_
  var matches = regex.exec(text);_x000D_
_x000D_
  return matches.reduce(function(result, match, index) {_x000D_
    if (index > 0)_x000D_
      // This substraction is required because we count _x000D_
      // match indexes from 1, because 0 is the entire matched string_x000D_
      result[matchNames[index - 1]] = match;_x000D_
_x000D_
    return result;_x000D_
  }, {});_x000D_
}_x000D_
_x000D_
var myString = "Hello Alex, I am John";_x000D_
_x000D_
var namedMatches = namedRegexMatch(_x000D_
  myString,_x000D_
  /Hello ([a-z]+), I am ([a-z]+)/i, _x000D_
  ["firstPersonName", "secondPersonName"]_x000D_
);_x000D_
_x000D_
alert(JSON.stringify(namedMatches));
_x000D_
_x000D_
_x000D_

Tomcat 7: How to set initial heap size correctly?

Use following command to increase java heap size for tomcat7 (linux distributions) correctly:

echo 'export CATALINA_OPTS="-Xms512M -Xmx1024M"' > /usr/share/tomcat7/bin/setenv.sh

How to stop docker under Linux

In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:

sudo snap stop docker
sudo snap remove docker

... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:

sudo apt purge snap

:-)

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The only difference is that CHARACTER VARYING is more human friendly than VARCHAR

POST unchecked HTML checkboxes

Copy this directly

_x000D_
_x000D_
  _x000D_
_x000D_
_x000D_
$(document).on('change', "input[type=checkbox]", function () {_x000D_
       _x000D_
        var checkboxVal = (this.checked) ? 1 : 0;_x000D_
_x000D_
      _x000D_
        if (checkboxVal== 1) {_x000D_
           _x000D_
            $(this).prop("checked", true);_x000D_
            $(this).val("true");_x000D_
        }_x000D_
        else {_x000D_
         _x000D_
            $(this).prop("checked", false);_x000D_
            $(this).val("false");_x000D_
        }_x000D_
    });
_x000D_
_x000D_
_x000D_

How to make a cross-module variable?

I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__ module, it will be accessible as if a global from any other module that includes __builtin__ -- which is all of them, by default.

a.py contains

print foo

b.py contains

import __builtin__
__builtin__.foo = 1
import a

The result is that "1" is printed.

Edit: The __builtin__ module is available as the local symbol __builtins__ -- that's the reason for the discrepancy between two of these answers. Also note that __builtin__ has been renamed to builtins in python3.

dotnet ef not found in .NET Core 3

Run PowerShell or command prompt as Administrator and run below command.

dotnet tool install --global dotnet-ef --version 3.1.3

How do I represent a time only value in .NET?

If that empty Date really bugs you, you can also to create a simpler Time structure:

// more work is required to make this even close to production ready
class Time
{
    // TODO: don't forget to add validation
    public int Hours   { get; set; }
    public int Minutes { get; set; }
    public int Seconds { get; set; }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }
}

Or, why to bother: if you don't need to do any calculation with that information, just store it as String.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Android Home should be the root folder of SDK.

export ANDROID_HOME="$HOME/android-sdk-linux"

EDIT: Open terminal and type these commands. (yes, on a ternimal , not in bashrc file)

export ANDROID_HOME=~/android-sdk-macosx
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools    

and then in the same terminal just type android. If configured you would be able to use build commands from this terminal. (it's a temporary solution)

what is the use of Eval() in asp.net

While binding a databound control, you can evaluate a field of the row in your data source with eval() function.

For example you can add a column to your gridview like that :

<asp:BoundField DataField="YourFieldName" />

And alternatively, this is the way with eval :

<asp:TemplateField>
<ItemTemplate>
        <asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
        </asp:Label>
</ItemTemplate>
</asp:TemplateField>

It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :

<asp:TemplateField>
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server" 
          NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>' 
          Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

Assigning a function to a variable

When you assign a function to a variable you don't use the () but simply the name of the function.

In your case given def x(): ..., and variable silly_var you would do something like this:

silly_var = x

and then you can call the function either with

x()

or

silly_var()

What is a blob URL and why it is used?

Blob URLs (ref W3C, official name) or Object-URLs (ref. MDN and method name) are used with a Blob or a File object.

src="blob:https://crap.crap" I opened the blob url that was in src of video it gave a error and i can't open but was working with the src tag how it is possible?

Blob URLs can only be generated internally by the browser. URL.createObjectURL() will create a special reference to the Blob or File object which later can be released using URL.revokeObjectURL(). These URLs can only be used locally in the single instance of the browser and in the same session (ie. the life of the page/document).

What is blob url?
Why it is used?

Blob URL/Object URL is a pseudo protocol to allow Blob and File objects to be used as URL source for things like images, download links for binary data and so forth.

For example, you can not hand an Image object raw byte-data as it would not know what to do with it. It requires for example images (which are binary data) to be loaded via URLs. This applies to anything that require an URL as source. Instead of uploading the binary data, then serve it back via an URL it is better to use an extra local step to be able to access the data directly without going via a server.

It is also a better alternative to Data-URI which are strings encoded as Base-64. The problem with Data-URI is that each char takes two bytes in JavaScript. On top of that a 33% is added due to the Base-64 encoding. Blobs are pure binary byte-arrays which does not have any significant overhead as Data-URI does, which makes them faster and smaller to handle.

Can i make my own blob url on a server?

No, Blob URLs/Object URLs can only be made internally in the browser. You can make Blobs and get File object via the File Reader API, although BLOB just means Binary Large OBject and is stored as byte-arrays. A client can request the data to be sent as either ArrayBuffer or as a Blob. The server should send the data as pure binary data. Databases often uses Blob to describe binary objects as well, and in essence we are talking basically about byte-arrays.

if you have then Additional detail

You need to encapsulate the binary data as a BLOB object, then use URL.createObjectURL() to generate a local URL for it:

var blob = new Blob([arrayBufferWithPNG], {type: "image/png"}),
    url = URL.createObjectURL(blob),
    img = new Image();

img.onload = function() {
    URL.revokeObjectURL(this.src);     // clean-up memory
    document.body.appendChild(this);   // add image to DOM
}

img.src = url;                         // can now "stream" the bytes

Note that URL may be prefixed in webkit-browsers, so use:

var url = (URL || webkitURL).createObjectURL(...);

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

The Best way(Recommended) is use of java.util.Concurrent package . By using this package you can easily avoid this Exception . refer Modified Code

public static void main(String[] args) {
    Collection<Integer> l = new CopyOnWriteArrayList<Integer>();

    for (int i=0; i < 10; ++i) {
        l.add(new Integer(4));
        l.add(new Integer(5));
        l.add(new Integer(6));
    }

    for (Integer i : l) {
        if (i.intValue() == 5) {
            l.remove(i);
        }
    }

    System.out.println(l);
}

Merge Cell values with PHPExcel - PHP

$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p)); for dynamic merging of cells

How do I get the calling method name and type using reflection?

public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

Now let's say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name will be "Call" and type will be "Caller"

UPDATE Two years later since I'm still getting upvotes on this

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute

Going with the previous example:

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}

C# How to determine if a number is a multiple of another?

I don't get that part about the string stuff, but why don't you use the modulo operator (%) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.

It goes like that:

   int a = 10; int b = 5;

   // is a a multiple of b 
   if ( a % b == 0 )  ....

Checking Value of Radio Button Group via JavaScript?

If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.

<form name="myForm">
    <input type="radio" id="genderm" name="gender" value="male" />
    <label for="genderm">Male</label>
    <input type="radio" id="genderf" name="gender" value="female" />
    <label for="genderf">Female</label>
</form>

<script>
    var selected = document.forms.myForm.gender.value;
</script>

What is the equivalent to getch() & getche() in Linux?

#include <unistd.h>
#include <termios.h>

char getch(void)
{
    char buf = 0;
    struct termios old = {0};
    fflush(stdout);
    if(tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if(tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if(read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    printf("%c\n", buf);
    return buf;
 }

Remove the last printf if you don't want the character to be displayed.

How to get the current user's Active Directory details in C#

Add reference to COM "Active DS Type Library"


            Int32 nameTypeNT4               = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4;
            Int32 nameTypeDN                = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_1779;
            Int32 nameTypeUserPrincipalName = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_USER_PRINCIPAL_NAME;

            ActiveDs.NameTranslate nameTranslate = new ActiveDs.NameTranslate();

            // Convert NT name DOMAIN\User into AD distinguished name 
            // "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com"
            nameTranslate.Set(nameTypeNT4, ntUser);

            String distinguishedName = nameTranslate.Get(nameTypeDN);

            Console.WriteLine(distinguishedName);

            // Convert AD distinguished name "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com" 
            // into NT name DOMAIN\User
            ntUser = String.Empty;
            nameTranslate.Set(nameTypeDN, distinguishedName);
            ntUser = nameTranslate.Get(nameTypeNT4);
            Console.WriteLine(ntUser);

            // Convert NT name DOMAIN\User into AD UserPrincipalName [email protected]
            nameTranslate.Set(nameTypeNT4, ntUser);
            String userPrincipalName = nameTranslate.Get(nameTypeUserPrincipalName);

            Console.WriteLine(userPrincipalName);

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

What's wrong with:

clob.getSubString(1, (int) clob.length());

?

For example Oracle oracle.sql.CLOB performs getSubString() on internal char[] which defined in oracle.jdbc.driver.T4CConnection and just System.arraycopy() and next wrap to String... You never get faster reading than System.arraycopy().

UPDATE Get driver ojdbc6.jar, decompile CLOB implementation, and study which case could be faster based on the internals knowledge.

Retrieving values from nested JSON Object

You can see that JSONObject extends a HashMap, so you can simply use it as a HashMap:

JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Using HTML data-attribute to set CSS background-image url

For those who want a dumb down answer like me

Something like how to steps as 1, 2, 3

Here it is what I did

First create the HTML markup

<div class="thumb" data-image-src="images/img.jpg"></div>

Then before your ending body tag, add this script

I included the ending body on the code below as an example

So becareful when you copy

<script>
var list = document.getElementsByClassName('thumb');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-image-src');
  list[i].style.backgroundImage="url('" + src + "')";
}
</script>

</body>

Android Material Design Button Styles

With the stable release of Android Material Components in Nov 2018, Google has moved the material components from namespace android.support.design to com.google.android.material.
Material Component library is replacement for Android’s Design Support Library.

Add the dependency to your build.gradle:

dependencies { implementation ‘com.google.android.material:material:1.0.0’ }

Then add the MaterialButton to your layout:

<com.google.android.material.button.MaterialButton
        style="@style/Widget.MaterialComponents.Button.OutlinedButton" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        app:strokeColor="@color/colorAccent"
        app:strokeWidth="6dp"
        app:layout_constraintStart_toStartOf="parent"
        app:shapeAppearance="@style/MyShapeAppearance"
   />

You can check the full documentation here and API here.

To change the background color you have 2 options.

  1. Using the backgroundTint attribute.

Something like:

<style name="MyButtonStyle"
 parent="Widget.MaterialComponents.Button">
    <item name="backgroundTint">@color/button_selector</item>
    //..
</style>
  1. It will be the best option in my opinion. If you want to override some theme attributes from a default style then you can use new materialThemeOverlay attribute.

Something like:

<style name="MyButtonStyle"
 parent="Widget.MaterialComponents.Button">
   <item name=“materialThemeOverlay”>@style/GreenButtonThemeOverlay</item>
</style>

<style name="GreenButtonThemeOverlay">
  <!-- For filled buttons, your theme's colorPrimary provides the default background color of the component --> 
  <item name="colorPrimary">@color/green</item>
</style>

The option#2 requires the 'com.google.android.material:material:1.1.0'.

enter image description hereenter image description here

OLD Support Library:

With the new Support Library 28.0.0, the Design Library now contains the MaterialButton.

You can add this button to our layout file with:

<android.support.design.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="YOUR TEXT"
    android:textSize="18sp"
    app:icon="@drawable/ic_android_white_24dp" />

By default this class will use the accent colour of your theme for the buttons filled background colour along with white for the buttons text colour.

You can customize the button with these attributes:

  • app:rippleColor: The colour to be used for the button ripple effect
  • app:backgroundTint: Used to apply a tint to the background of the button. If you wish to change the background color of the button, use this attribute instead of background.

  • app:strokeColor: The color to be used for the button stroke

  • app:strokeWidth: The width to be used for the button stroke
  • app:cornerRadius: Used to define the radius used for the corners of the button

angular-cli server - how to proxy API requests to another server?

  1. add in proxy.conf.json, all request to /api will be redirect to htt://targetIP:targetPort/api.
{
  "/api": {
    "target": "http://targetIP:targetPort",
    "secure": false,
    "pathRewrite": {"^/api" : targeturl/api},
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
  1. in package.json, make "start": "ng serve --proxy-config proxy.conf.json"

  2. in code let url = "/api/clnsIt/dev/78"; this url will be translated to http://targetIP:targetPort/api/clnsIt/dev/78.

  3. You can also force rewrite by filling the pathRewrite. This is the link for details cmd/NPM console will log something like "Rewriting path from "/api/..." to "http://targeturl:targetPort/api/..", while browser console will log "http://loclahost/api"

Detect touch press vs long press vs movement?

GestureDetector.SimpleOnGestureListener has methods to help in these 3 cases;

   GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {

        //for single click event.
        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            return true;
        }

        //for detecting a press event. Code for drag can be added here.
        @Override
        public void onShowPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("..", "...");
            clipboardManager.setPrimaryClip(clipData);

            ConceptDragShadowBuilder dragShadowBuilder = new CustomDragShadowBuilder(child);
            // drag child view.
            child.startDrag(clipData, dragShadowBuilder, child, 0);
        }

        //for detecting longpress event
        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
        }
    });

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

Bootstrap datetimepicker is not a function

Below is the right code. Include JS files in following manner:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(function() {_x000D_
    $('#datetimepicker6').datetimepicker();_x000D_
    $('#datetimepicker7').datetimepicker({_x000D_
      useCurrent: false //Important! See issue #1075_x000D_
    });_x000D_
    $("#datetimepicker6").on("dp.change", function(e) {_x000D_
      $('#datetimepicker7').data("DateTimePicker").minDate(e.date);_x000D_
    });_x000D_
    $("#datetimepicker7").on("dp.change", function(e) {_x000D_
      $('#datetimepicker6').data("DateTimePicker").maxDate(e.date);_x000D_
    });_x000D_
  });_x000D_
});
_x000D_
<html>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
  <div class="container">_x000D_
    <div class='col-md-5'>_x000D_
      <div class="form-group">_x000D_
        <div class='input-group date' id='datetimepicker6'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class='col-md-5'>_x000D_
      <div class="form-group">_x000D_
        <div class='input-group date' id='datetimepicker7'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to auto-reload files in Node.js?

A good, up to date alternative to supervisor is nodemon:

Monitor for any changes in your node.js application and automatically restart the server - perfect for development

To use nodemon:

$ npm install nodemon -g
$ nodemon app.js

JQuery Validate Dropdown list

I have modified your code a little. Here's a working version (for me):

    <select name="dd1" id="dd1">
       <option value="none">None</option>
       <option value="o1">option 1</option>
       <option value="o2">option 2</option>
       <option value="o3">option 3</option>
    </select>  
    <div style="color:red;" id="msg_id"></div>

<script>
    $('#everything').submit(function(e){ 
        var department = $("#msg_id");
        var msg = "Please select Department";
            if ($('#dd1').val() == "") {
                department.append(msg);
                e.preventDefault();
                return false;
            }
        });
 </script>

How to capture Curl output to a file?

For those of you want to copy the cURL output in the clipboard instead of outputting to a file, you can use pbcopy by using the pipe | after the cURL command.

Example: curl https://www.google.com/robots.txt | pbcopy. This will copy all the content from the given URL to your clipboard.

Inserting created_at data with Laravel

$data = array();
$data['created_at'] =new \DateTime();
DB::table('practice')->insert($data);

How do I print an IFrame from javascript in Safari/Chrome

Use firefox window.frames but also add the name property because that uses the iframe in firefox

IE:

window.frames[id]

Firefox:

window.frames[name]

<img src="print.gif"  onClick="javascript: window.frames['factura'].focus(); parent['factura'].print();">
<iframe src="factura.html" width="100%" height="400" id="factura" name="factura"></iframe>

Rails - How to use a Helper Inside a Controller

In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController.

Mongoose and multiple database in single node.js project

Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.

In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:

mongoose.connect('mongodb://localhost/default');

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('connected');
});

which is just how it is described in the docs. And then in your model files, do something like the following:

import mongoose, { Schema } from 'mongoose';

const userInfoSchema = new Schema({
  createdAt: {
    type: Date,
    required: true,
    default: new Date(),
  },
  // ...other fields
});

const myDB = mongoose.connection.useDb('myDB');

const UserInfo = myDB.model('userInfo', userInfoSchema);

export default UserInfo;

Where myDB is your database name.

How to get a value of an element by name instead of ID

$('[name=whatever]').val()

The jQuery documentation is your friend.

Fixed position but relative to container

When you use position:fixed CSS rule and try to apply top/left/right/bottom it position the element relative to window.

A workaround is to use margin properties instead of top/left/right/bottom

How to call a PHP file from HTML or Javascript

As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:

$.post("yourfile.php", {data : "This can be as long as you want"});

And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.

Toggle display:none style with JavaScript

Give the UL an ID and use the getElementById function:

<html>
<body>
    <script>
    function toggledisplay(elementID)
    {
        (function(style) {
            style.display = style.display === 'none' ? '' : 'none';
        })(document.getElementById(elementID).style);
    }
    </script>

<a href="#" title="Show Tags" onClick="toggledisplay('changethis');">Show All Tags</a>
<ul class="subforums" id="changethis" style="overflow-x: visible; overflow-y: visible; ">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

</body>
</html>

Can the Unix list command 'ls' output numerical chmod permissions?

@The MYYN

wow, nice awk! But what about suid, sgid and sticky bit?

You have to extend your filter with s and t, otherwise they will not count and you get the wrong result. To calculate the octal number for this special flags, the procedure is the same but the index is at 4 7 and 10. the possible flags for files with execute bit set are ---s--s--t amd for files with no execute bit set are ---S--S--T

ls -l | awk '{
    k = 0
    s = 0
    for( i = 0; i <= 8; i++ )
    {
        k += ( ( substr( $1, i+2, 1 ) ~ /[rwxst]/ ) * 2 ^( 8 - i ) )
    }
    j = 4 
    for( i = 4; i <= 10; i += 3 )
    {
        s += ( ( substr( $1, i, 1 ) ~ /[stST]/ ) * j )
        j/=2
    }
    if ( k )
    {
        printf( "%0o%0o ", s, k )
    }
    print
}'  

For test:

touch blah
chmod 7444 blah

will result in:

7444 -r-Sr-Sr-T 1 cheko cheko   0 2009-12-05 01:03 blah

and

touch blah
chmod 7555 blah

will give:

7555 -r-sr-sr-t 1 cheko cheko   0 2009-12-05 01:03 blah

How can you find out which process is listening on a TCP or UDP port on Windows?

Use the below batch script which takes a process name as an argument and gives netstat output for the process.

@echo off
set procName=%1
for /f "tokens=2 delims=," %%F in ('tasklist /nh /fi "imagename eq %1" /fo csv') do call :Foo %%~F
goto End

:Foo
set z=%1
echo netstat for : "%procName%" which had pid "%1"
echo ----------------------------------------------------------------------

netstat -ano |findstr %z%
goto :eof

:End

@try - catch block in Objective-C

Now I've found the problem.

Removing the obj_exception_throw from my breakpoints solved this. Now it's caught by the @try block and also, NSSetUncaughtExceptionHandler will handle this if a @try block is missing.

How to save password when using Subversion from the console

It depends on the protocol you're using. If you're using SVN + SSH, the SVN client can't save your password because it never touches it - the SSH client prompts you for it directly. In this case, you can use an SSH key and ssh-agent to avoid the constant prompts. If you're using the svnserve protocol or HTTP(S), then the SSH client is handling your password and can save it.

Sorting an Array of int using BubbleSort

public class SortingArray {
public static void main(String[] args) {

int[] a={3,7,9,5,1,4,0,2,8,6};
int temp=0;

boolean isSwapped=true;


System.out.println(" before sorting the array: ");

for(int i=0;i<a.length;i++)
{
    System.out.print(a[i]);
}
System.out.println("");

do
{

isSwapped=false;

for(int i=0;i<a.length-1;i++)

{

    if(a[i]>a[i+1])

    {

        temp=a[i];

        a[i]=a[i+1];

        a[i+1]=temp;

    }



}


}while(isSwapped);


System.out.println("after sorting the array: ");

    for(int array:a)

    {

        System.out.print(array);


    }
  }
}

Reset the Value of a Select Box

neRok touched on this answer above and I'm just expanding on it.

According to the slightly dated, but handy O'Reilly reference book, Javascript: The Definitive Guide:

The selectedIndex property of the Select object is an integer that specifies the index of the selected option within the Select object. If no option is selected, selectedIndex is -1.

As such, the following javascript code will "reset" the Select object to no options selected:

select_box = document.getElementById("myselectbox");
select_box.selectedIndex = -1;

Note that changing the selection in this way does not trigger the onchange() event handler.

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

Multi-line string with extra space (preserved indentation)

If you're trying to get the string into a variable, another easy way is something like this:

USAGE=$(cat <<-END
    This is line one.
    This is line two.
    This is line three.
END
)

If you indent your string with tabs (i.e., '\t'), the indentation will be stripped out. If you indent with spaces, the indentation will be left in.

NOTE: It is significant that the last closing parenthesis is on another line. The END text must appear on a line by itself.

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I resolved this issue by downgrading my Firefox to an older version that had previously worked well with Selenium-WebDriver. In my case, I had to downgrade back to Firefox 18 and this version worked with Selenium 2.27

Here is the link to get older versions of firefox: https://ftp.mozilla.org/pub/mozilla.org/firefox/releases/

What are the retransmission rules for TCP?

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

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

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

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

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

Get Image Height and Width as integer values?

list($width, $height) = getimagesize($filename)

Or,

$data = getimagesize($filename);
$width = $data[0];
$height = $data[1];

Running multiple commands with xargs

With GNU Parallel you can do:

cat a.txt | parallel 'command1 {}; command2 {}; ...; '

Watch the intro videos to learn more: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

For security reasons it is recommended you use your package manager to install. But if you cannot do that then you can use this 10 seconds installation.

The 10 seconds installation will try to do a full installation; if that fails, a personal installation; if that fails, a minimal installation.

$ (wget -O - pi.dk/3 || lynx -source pi.dk/3 || curl pi.dk/3/ || \
   fetch -o - http://pi.dk/3 ) > install.sh
$ sha1sum install.sh | grep 67bd7bc7dc20aff99eb8f1266574dadb
12345678 67bd7bc7 dc20aff9 9eb8f126 6574dadb
$ md5sum install.sh | grep b7a15cdbb07fb6e11b0338577bc1780f
b7a15cdb b07fb6e1 1b033857 7bc1780f
$ sha512sum install.sh | grep 186000b62b66969d7506ca4f885e0c80e02a22444
6f25960b d4b90cf6 ba5b76de c1acdf39 f3d24249 72930394 a4164351 93a7668d
21ff9839 6f920be5 186000b6 2b66969d 7506ca4f 885e0c80 e02a2244 40e8a43f
$ bash install.sh

How to assign multiple classes to an HTML container?

To assign multiple classes to an html element, include both class names within the quotations of the class attribute and have them separated by a space:

<article class="column wrapper"> 

In the above example, column and wrapper are two separate css classes, and both of their properties will be applied to the article element.

Determine the line of code that causes a segmentation fault?

All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.

If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.

It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)

Returning unique_ptr from functions

I think it's perfectly explained in item 25 of Scott Meyers' Effective Modern C++. Here's an excerpt:

The part of the Standard blessing the RVO goes on to say that if the conditions for the RVO are met, but compilers choose not to perform copy elision, the object being returned must be treated as an rvalue. In effect, the Standard requires that when the RVO is permitted, either copy elision takes place or std::move is implicitly applied to local objects being returned.

Here, RVO refers to return value optimization, and if the conditions for the RVO are met means returning the local object declared inside the function that you would expect to do the RVO, which is also nicely explained in item 25 of his book by referring to the standard (here the local object includes the temporary objects created by the return statement). The biggest take away from the excerpt is either copy elision takes place or std::move is implicitly applied to local objects being returned. Scott mentions in item 25 that std::move is implicitly applied when the compiler choose not to elide the copy and the programmer should not explicitly do so.

In your case, the code is clearly a candidate for RVO as it returns the local object p and the type of p is the same as the return type, which results in copy elision. And if the compiler chooses not to elide the copy, for whatever reason, std::move would've kicked in to line 1.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

go to Start->Run and type cmd this starts the Command Prompt (also available from Start->Programs->Accessories->Command Prompt)

type cd .. and press return type cd .. and press return again (keep doing this until the prompt shows :> )

now you need to go to a special folder which might be c:\windows\system32 or it might be c:\winnt\system32 or it might be c:\windows\sysWOW64 try typing each of these eg cd c:\windows\sysWOW64 (if it says The system cannot find the path specified, try the next one) cd c:\windows\system32 cd c:\winnt\system32 when one of those doesn't cause an error, stop, you've found the correct folder.

now you need to register the OLE DB 4.0 DLLs by typing these commands and pressing return after each

regsvr32 Msjetoledb40.dll regsvr32 Msjet40.dll regsvr32 Mswstr10.dll regsvr32 Msjter40.dll regsvr32 Msjint40.dll

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

Tips for debugging .htaccess rewrite rules

Don't forget that in .htaccess files it is a relative URL that is matched.

In a .htaccess file the following RewriteRule will never match:

RewriteRule ^/(.*)     /something/$s

How to get disk capacity and free space of remote computer

PowerShell Fun

Get-WmiObject win32_logicaldisk -Computername <ServerName> -Credential $(get-credential) | Select DeviceID,VolumeName,FreeSpace,Size | where {$_.DeviceID -eq "C:"}

PHP/MySQL Insert null values

For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.

For example:

mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");

Bootstrap DatePicker, how to set the start date for tomorrow?

1) use for tommorow's date startDate: '+1d'

2) use for yesterday's date startDate: '-1d'

3) use for today's date startDate: new Date()

What is boilerplate code?

From Wikipedia:

In computer programming, boilerplate is the term used to describe sections of code that have to be included in many places with little or no alteration. It is more often used when referring to languages that are considered verbose, i.e. the programmer must write a lot of code to do minimal jobs.

So basically you can consider boilerplate code as a text that is needed by a programming language very often all around the programs you write in that language.

Modern languages are trying to reduce it, but also the older language which has specific type-checkers (for example OCaml has a type-inferrer that allows you to avoid so many declarations that would be boilerplate code in a more verbose language like Java)

How to Create Multiple Where Clause Query Using Laravel Eloquent?

public function search()
{
    if (isset($_GET) && !empty($_GET))
    {
        $prepareQuery = '';
        foreach ($_GET as $key => $data)
        {
            if ($data)
            {
                $prepareQuery.=$key . ' = "' . $data . '" OR ';
            }
        }
        $query = substr($prepareQuery, 0, -3);
        if ($query)
            $model = Businesses::whereRaw($query)->get();
        else
            $model = Businesses::get();

        return view('pages.search', compact('model', 'model'));
    }
}

matplotlib: how to draw a rectangle on image

There is no need for subplots, and pyplot can display PIL images, so this can be simplified further:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from PIL import Image

im = Image.open('stinkbug.png')

# Display the image
plt.imshow(im)

# Get the current reference
ax = plt.gca()

# Create a Rectangle patch
rect = Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none')

# Add the patch to the Axes
ax.add_patch(rect)

Or, the short version:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from PIL import Image

# Display the image
plt.imshow(Image.open('stinkbug.png'))

# Add the patch to the Axes
plt.gca().add_patch(Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none'))

How do you remove the title text from the Android ActionBar?

Got it. You have to override

android:actionBarStyle

and then in your custom style you have to override

android:titleTextStyle

Here's a sample.

In my themes.xml:

<style name="CustomActionBar" parent="android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/CustomActionBarStyle</item>
</style>

And in my styles.xml:

<style name="CustomActionBarStyle" parent="android:style/Widget.Holo.ActionBar">
        <item name="android:titleTextStyle">@style/NoTitleText</item>
        <item name="android:subtitleTextStyle">@style/NoTitleText</item>
</style>

<style name="NoTitleText">
        <item name="android:textSize">0sp</item>
        <item name="android:textColor">#00000000</item>
</style>

I'm not sure why setting the textSize to zero didn't do the trick (it shrunk the text, but didn't make it go away), but setting the textColor to transparent works.

How do I include a pipe | in my linux find -exec command?

If you are looking for a simple alternative, this can be done using a loop:

for i in $(find -name 'file_*' -follow -type f); do
  zcat $i | agrep -dEOE 'grep'
done

or, more general and easy to understand form:

for i in $(YOUR_FIND_COMMAND); do
  YOUR_EXEC_COMMAND_AND_PIPES
done

and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES

Environment variables in Mac OS X

For 2020 Mac OS X Catalina users:

Forget about other useless answers, here only two steps needed:

  1. Create a file with the naming convention: priority-appname. Then copy-paste the path you want to add to PATH.

    E.g. 80-vscode with content /Applications/Visual Studio Code.app/Contents/Resources/app/bin/ in my case.

  2. Move that file to /etc/paths.d/. Don't forget to open a new tab(new session) in the Terminal and type echo $PATH to check that your path is added!

Notice: this method only appends your path to PATH.

How can I find out which server hosts LDAP on my windows domain?

If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):

    mokey 0 /home/jj33 > nslookup example.ad
    Server:         172.16.2.10
    Address:        172.16.2.10#53

    Non-authoritative answer:
    Name:   example.ad
    Address: 172.16.6.2
    Name:   example.ad
    Address: 172.16.141.160
    Name:   example.ad
    Address: 172.16.7.9
    Name:   example.ad
    Address: 172.19.1.14
    Name:   example.ad
    Address: 172.19.1.3
    Name:   example.ad
    Address: 172.19.1.11
    Name:   example.ad
    Address: 172.16.3.2

Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.

I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Just just using Transformers It did not work for me I was getting type cast exception.

sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class)) did notwork because I was getting Array of Object in the return list element not the fixed MYEngityName type of list element.

It worked for me when I make following changes When I have added sqlQuery.addScalar(-) each selected column and its type and for specific String type column we dont have to map its type. like addScalar("langCode");

And I have join MYEngityName with NextEnity we cant just select * in the Query it will give array of Object in the return list.

Below code sample :

session = ht.getSessionFactory().openSession();
                String sql = new StringBuffer("Select txnId,nft.mId,count,retryReason,langCode FROM  MYEngityName nft INNER JOIN NextEntity m on nft.mId  =  m.id where nft.txnId < ").append(lastTxnId)
                       .append(StringUtils.isNotBlank(regionalCountryOfService)? " And  m.countryOfService in ( "+ regionalCountryOfService +" )" :"")
                       .append(" order by nft.txnId desc").toString();
                SQLQuery sqlQuery = session.createSQLQuery(sql);
                sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class));
                sqlQuery.addScalar("txnId",Hibernate.LONG)
                        .addScalar("merchantId",Hibernate.INTEGER)
                        .addScalar("count",Hibernate.BYTE)
                        .addScalar("retryReason")
                        .addScalar("langCode");
                sqlQuery.setMaxResults(maxLimit);
                return sqlQuery.list();

It might help some one. in this way work for me.

Getting reference to the top-most view/window in iOS application

Whenever I want to display some overlay on top of everything else, I just add it on top of the Application Window directly:

[[[UIApplication sharedApplication] keyWindow] addSubview:someView]

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Thought this might help to someone, it happens because "When the number of data queries is greater than 1".reference

Bootstrap center heading

Bootstrap comes with many pre-build classes and one of them is class="text-left". Please call this class whenever needed. :-)

Jackson - Deserialize using generic class

You can wrap it in another class which knows the type of your generic type.

Eg,

class Wrapper {
 private Data<Something> data;
}
mapper.readValue(jsonString, Wrapper.class);

Here Something is a concrete type. You need a wrapper per reified type. Otherwise Jackson does not know what objects to create.

How to sort by column in descending order in Spark SQL?

It's in org.apache.spark.sql.DataFrame for sort method:

df.sort($"col1", $"col2".desc)

Note $ and .desc inside sort for the column to sort the results by.

Get the difference between two dates both In Months and days in sql

MsSql Syntax : DATEDIFF ( datepart , startdate , enddate )

Oracle: This will returns number of days

    select
  round(Second_date - First_date)  as Diff_InDays,round ((Second_date - First_date) / (30),1)  as Diff_InMonths,round ((Second_date - First_date) * (60*24),2)  as TimeIn_Minitues
from
  (
  select
    to_date('01/01/2012 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as First_date
   ,to_date('05/02/2012 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as Second_date
  from
    dual
  ) result;

Demo : http://sqlfiddle.com/#!4/c26e8/36

How to delete last character from a string using jQuery?

You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).

Rename master branch for both local and remote Git repositories

The closest thing to renaming is deleting and then re-creating on the remote. For example:

git branch -m master master-old
git push remote :master         # delete master
git push remote master-old      # create master-old on remote

git checkout -b master some-ref # create a new local master
git push remote master          # create master on remote

However this has a lot of caveats. First, no existing checkouts will know about the rename - git does not attempt to track branch renames. If the new master doesn't exist yet, git pull will error out. If the new master has been created. the pull will attempt to merge master and master-old. So it's generally a bad idea unless you have the cooperation of everyone who has checked out the repository previously.

Note: Newer versions of git will not allow you to delete the master branch remotely by default. You can override this by setting the receive.denyDeleteCurrent configuration value to warn or ignore on the remote repository. Otherwise, if you're ready to create a new master right away, skip the git push remote :master step, and pass --force to the git push remote master step. Note that if you're not able to change the remote's configuration, you won't be able to completely delete the master branch!

This caveat only applies to the current branch (usually the master branch); any other branch can be deleted and recreated as above.

Already defined in .obj - no double inclusions

I do recomend doing it in 2 filles (.h .cpp) But if u lazy just add inline before the function So it will look something like this

inline void functionX() 
{ }

more about inline functions:

The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.

more info here

How to specify the JDK version in android studio?

You can use cmd + ; for Mac or Ctrl + Alt + Shift + S for Windows/Linux to pull up the Project Structure dialog. In there, you can set the JDK location as well as the Android SDK location.

Project Structure Dialog

To get your JDK location, run /usr/libexec/java_home -v 1.7 in terminal. Send 1.7 for Java 7 or 1.8 for Java 8.

Subtract two dates in Java

Assuming that you're constrained to using Date, you can do the following:

Date diff = new Date(d2.getTime() - d1.getTime());

Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date).

How to use OAuth2RestTemplate?

I have different approach if you want access token and make call to other resource system with access token in header

Spring Security comes with automatic security: oauth2 properties access from application.yml file for every request and every request has SESSIONID which it reads and pull user info via Principal, so you need to make sure inject Principal in OAuthUser and get accessToken and make call to resource server

This is your application.yml, change according to your auth server:

security:
  oauth2:
    client:
      clientId: 233668646673605
      clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
      accessTokenUri: https://graph.facebook.com/oauth/access_token
      userAuthorizationUri: https://www.facebook.com/dialog/oauth
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://graph.facebook.com/me

@Component
public class OAuthUser implements Serializable {

private static final long serialVersionUID = 1L;

private String authority;

@JsonIgnore
private String clientId;

@JsonIgnore
private String grantType;
private boolean isAuthenticated;
private Map<String, Object> userDetail = new LinkedHashMap<String, Object>();

@JsonIgnore
private String sessionId;

@JsonIgnore
private String tokenType;

@JsonIgnore
private String accessToken;

@JsonIgnore
private Principal principal;

public void setOAuthUser(Principal principal) {
    this.principal = principal;
    init();
}

public Principal getPrincipal() {
    return principal;
}

private void init() {
    if (principal != null) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
        if (oAuth2Authentication != null) {
            for (GrantedAuthority ga : oAuth2Authentication.getAuthorities()) {
                setAuthority(ga.getAuthority());
            }
            setClientId(oAuth2Authentication.getOAuth2Request().getClientId());
            setGrantType(oAuth2Authentication.getOAuth2Request().getGrantType());
            setAuthenticated(oAuth2Authentication.getUserAuthentication().isAuthenticated());

            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) oAuth2Authentication
                    .getDetails();
            if (oAuth2AuthenticationDetails != null) {
                setSessionId(oAuth2AuthenticationDetails.getSessionId());
                setTokenType(oAuth2AuthenticationDetails.getTokenType());

            // This is what you will be looking for 
                setAccessToken(oAuth2AuthenticationDetails.getTokenValue());
            }

    // This detail is more related to Logged-in User
            UsernamePasswordAuthenticationToken userAuthenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
            if (userAuthenticationToken != null) {
                LinkedHashMap<String, Object> detailMap = (LinkedHashMap<String, Object>) userAuthenticationToken.getDetails();
                if (detailMap != null) {
                    for (Map.Entry<String, Object> mapEntry : detailMap.entrySet()) {
                        //System.out.println("#### detail Key = " + mapEntry.getKey());
                        //System.out.println("#### detail Value = " + mapEntry.getValue());
                        getUserDetail().put(mapEntry.getKey(), mapEntry.getValue());
                    }

                }

            }

        }

    }
}


public String getAuthority() {
    return authority;
}

public void setAuthority(String authority) {
    this.authority = authority;
}

public String getClientId() {
    return clientId;
}

public void setClientId(String clientId) {
    this.clientId = clientId;
}

public String getGrantType() {
    return grantType;
}

public void setGrantType(String grantType) {
    this.grantType = grantType;
}

public boolean isAuthenticated() {
    return isAuthenticated;
}

public void setAuthenticated(boolean isAuthenticated) {
    this.isAuthenticated = isAuthenticated;
}

public Map<String, Object> getUserDetail() {
    return userDetail;
}

public void setUserDetail(Map<String, Object> userDetail) {
    this.userDetail = userDetail;
}

public String getSessionId() {
    return sessionId;
}

public void setSessionId(String sessionId) {
    this.sessionId = sessionId;
}

public String getTokenType() {
    return tokenType;
}

public void setTokenType(String tokenType) {
    this.tokenType = tokenType;
}

public String getAccessToken() {
    return accessToken;
}

public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
}

@Override
public String toString() {
    return "OAuthUser [clientId=" + clientId + ", grantType=" + grantType + ", isAuthenticated=" + isAuthenticated
            + ", userDetail=" + userDetail + ", sessionId=" + sessionId + ", tokenType="
            + tokenType + ", accessToken= " + accessToken + " ]";
}

@RestController
public class YourController {

@Autowired
OAuthUser oAuthUser;

// In case if you want to see Profile of user then you this 
@RequestMapping(value = "/profile", produces = MediaType.APPLICATION_JSON_VALUE)
public OAuthUser user(Principal principal) {
    oAuthUser.setOAuthUser(principal);

    // System.out.println("#### Inside user() - oAuthUser.toString() = " + oAuthUser.toString());

    return oAuthUser;
}


@RequestMapping(value = "/createOrder",
        method = RequestMethod.POST,
        headers = {"Content-type=application/json"},
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public FinalOrderDetail createOrder(@RequestBody CreateOrder createOrder) {

    return postCreateOrder_restTemplate(createOrder, oAuthUser).getBody();
}


private ResponseEntity<String> postCreateOrder_restTemplate(CreateOrder createOrder, OAuthUser oAuthUser) {

String url_POST = "your post url goes here";

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Authorization", String.format("%s %s", oAuthUser.getTokenType(), oAuthUser.getAccessToken()));
    headers.add("Content-Type", "application/json");

    RestTemplate restTemplate = new RestTemplate();
    //restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpEntity<String> request = new HttpEntity<String>(createOrder, headers);

    ResponseEntity<String> result = restTemplate.exchange(url_POST, HttpMethod.POST, request, String.class);
    System.out.println("#### post response = " + result);

    return result;
}


}

How to pass arguments from command line to gradle

I have written a piece of code that puts the command line arguments in the format that gradle expects.

// this method creates a command line arguments
def setCommandLineArguments(commandLineArgs) {
    // remove spaces 
    def arguments = commandLineArgs.tokenize()

            // create a string that can be used by Eval 
            def cla = "["
            // go through the list to get each argument
            arguments.each {
                    cla += "'" + "${it}" + "',"
            }

    // remove last "," add "]" and set the args 
    return cla.substring(0, cla.lastIndexOf(',')) + "]"
}

my task looks like this:

task runProgram(type: JavaExec) {
    if ( project.hasProperty("commandLineArgs") ) {
            args Eval.me( setCommandLineArguments(commandLineArgs) )
    }
}

To pass the arguments from the command line you run this:

gradle runProgram -PcommandLineArgs="arg1 arg2 arg3 arg4"    

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

How often should you use git-gc?

Recent versions of git run gc automatically when required, so you shouldn't have to do anything. See the Options section of man git-gc(1): "Some git commands run git gc --auto after performing operations that could create many loose objects."

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

Compression/Decompression string with C#

This is an updated version for .NET 4.5 and newer using async/await and IEnumerables:

public static class CompressionExtensions
{
    public static async Task<IEnumerable<byte>> Zip(this object obj)
    {
        byte[] bytes = obj.Serialize();

        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(mso, CompressionMode.Compress))
                await msi.CopyToAsync(gs);

            return mso.ToArray().AsEnumerable();
        }
    }

    public static async Task<object> Unzip(this byte[] bytes)
    {
        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(msi, CompressionMode.Decompress))
            {
                // Sync example:
                //gs.CopyTo(mso);

                // Async way (take care of using async keyword on the method definition)
                await gs.CopyToAsync(mso);
            }

            return mso.ToArray().Deserialize();
        }
    }
}

public static class SerializerExtensions
{
    public static byte[] Serialize<T>(this T objectToWrite)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);

            return stream.GetBuffer();
        }
    }

    public static async Task<T> _Deserialize<T>(this byte[] arr)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            await stream.WriteAsync(arr, 0, arr.Length);
            stream.Position = 0;

            return (T)binaryFormatter.Deserialize(stream);
        }
    }

    public static async Task<object> Deserialize(this byte[] arr)
    {
        object obj = await arr._Deserialize<object>();
        return obj;
    }
}

With this you can serialize everything BinaryFormatter supports, instead only of strings.

Edit:

In case, you need take care of Encoding, you could just use Convert.ToBase64String(byte[])...

Take a look at this answer if you need an example!

Replace contents of factor column in R dataframe

You can use the function revalue from the package plyr to replace values in a factor vector.

In your example to replace the factor virginica by setosa:

 data(iris)
 library(plyr)
 revalue(iris$Species, c("virginica" = "setosa")) -> iris$Species

What's the most efficient way to erase duplicates and sort a vector?

std::unique only works on consecutive runs of duplicate elements, so you'd better sort first. However, it is stable, so your vector will remain sorted.

How to encode the plus (+) symbol in a URL

Just to add this to the list:

Uri.EscapeUriString("Hi there+Hello there") // Hi%20there+Hello%20there
Uri.EscapeDataString("Hi there+Hello there") // Hi%20there%2BHello%20there

See https://stackoverflow.com/a/34189188/98491

Usually you want to use EscapeDataString which does it right.

How to get the difference between two arrays in JavaScript?

I fall into this question, which was to get the difference of two simple arrays

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

// need ["c", "d"]

and I don't see why not go with the basic for loops :

for(var i=0; i < a1.length; i++) {
  for(var j=0; j < a2.length; j++) {
    if(a1[i] == a2[j]) {
      a2.splice(j, 1);
    }
  }
}

which would return the needed ["c", "d"]

[edit] proposed right above, seen to late.

Anyway, any good reason to avoid this simple solution ?

How do I read all classes from a Java package in the classpath?

You could use the Reflections Project described here

It's quite complete and easy to use.

Brief description from the above website:

Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.

Example:

Reflections reflections = new Reflections(
    new ConfigurationBuilder()
        .setUrls(ClasspathHelper.forJavaClassPath())
);
Set<Class<?>> types = reflections.getTypesAnnotatedWith(Scannable.class);

How do I rename a Git repository?

In a new repository, for instance, after a $ git init, the .git directory will contain the file .git/description.

Which looks like this:

Unnamed repository; edit this file 'description' to name the repository.

Editing this on the local repository will not change it on the remote.

Google Maps API - Get Coordinates of address

Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps

https://nominatim.openstreetmap.org/search?q=Mumbai&format=json

Here is the API documentation for reference.

Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.

How do I get my C# program to sleep for 50 msec?

Thread.Sleep(50);

The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.

This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.

Thread.Join

What's "this" in JavaScript onclick?

It refers to the element in the DOM to which the onclick attribute belongs:

<script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
function func(e) {
  $(e).text('there');
}
</script>
<a onclick="func(this)">here</a>

(This example uses jQuery.)

Chosen Jquery Plugin - getting selected values

$("#select-id").chosen().val()

this is the right answer, I tried, and the value passed is the values separated by ","

Plot 3D data in R

Adding to the solutions of others, I'd like to suggest using the plotly package for R, as this has worked well for me.

Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(plotly)
plot_ly(x=x,y=y,z=z, type="surface")

enter image description here

The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.

You can also try it with the built-in volcano dataset from R:

plot_ly(z=volcano, type="surface")

enter image description here

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If the problem is that a known root CA is missing and when you are using ubuntu or debian, then you can solve the problem with this one line:

sudo apt-get install ca-certificates

In Java, how do I parse XML as a String instead of a file?

I have this function in my code base, this should work for you.

public static Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

also see this similar question

How to remove first 10 characters from a string?

str = str.Remove(0,10); Removes the first 10 characters

or

str = str.Substring(10); Creates a substring starting at the 11th character to the end of the string.

For your purposes they should work identically.

Get list of certificates from the certificate store in C#

Yes -- the X509Store.Certificates property returns a snapshot of the X.509 certificate store.

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

The number of rows of a list of lists would be: len(A) and the number of columns len(A[0]) given that all rows have the same number of columns, i.e. all lists in each index are of the same size.

Document directory path of Xcode Device Simulator

on my computer, the path is:

~/Library/Developer/CoreSimulator/Devices/1A8DF360-B0A6-4815-95F3-68A6AB0BCC78/data/Container/Data/Application/

NOTE: probably those long IDs (i.e UDIDs) are different on your computer.

Can (domain name) subdomains have an underscore "_" in it?

Most answers given here are false. It is perfectly legal to have an underscore in a domain name. Let me quote the standard, RFC 2181, section 11, "Name syntax":

The DNS itself places only one restriction on the particular labels that can be used to identify resource records. That one restriction relates to the length of the label and the full name. [...] Implementations of the DNS protocols must not place any restrictions on the labels that can be used. In particular, DNS servers must not refuse to serve a zone because it contains labels that might not be acceptable to some DNS client programs.

See also the original DNS specification, RFC 1034, section 3.5 "Preferred name syntax" but read it carefully.

Domains with underscores are very common in the wild. Check _jabber._tcp.gmail.com or _sip._udp.apnic.net.

Other RFC mentioned here deal with different things. The original question was for domain names. If the question is for host names (or for URLs, which include a host name), then this is different, the relevant standard is RFC 1123, section 2.1 "Host Names and Numbers" which limits host names to letters-digits-hyphen.

Explaining Python's '__enter__' and '__exit__'

In addition to the above answers to exemplify invocation order, a simple run example

class myclass:
    def __init__(self):
        print("__init__")

    def __enter__(self): 
        print("__enter__")

    def __exit__(self, type, value, traceback):
        print("__exit__")

    def __del__(self):
        print("__del__")

with myclass(): 
    print("body")

Produces the output:

__init__
__enter__
body
__exit__
__del__

A reminder: when using the syntax with myclass() as mc, variable mc gets the value returned by __enter__(), in the above case None! For such use, need to define return value, such as:

def __enter__(self): 
    print('__enter__')
    return self

jquery .live('click') vs .click()

"live" is needed when you dynamically generate code. Just look the below example :

_x000D_
_x000D_
$("#div1").find('button').click(function() {_x000D_
    $('<button />')_x000D_
     .text('BUTTON')_x000D_
     .appendTo('#div1')_x000D_
})_x000D_
$("#div2").find('button').live("click", function() {_x000D_
    $('<button />')_x000D_
     .text('BUTTON')_x000D_
     .appendTo('#div2')_x000D_
})
_x000D_
button {_x000D_
  margin: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
  <button>Click</button>_x000D_
</div>_x000D_
<div id="div2">_x000D_
  <button>Live</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

without "live" the click-event occurs only when you click the first button, with "live" the click-event occurs also for the dynamically generated buttons

subsetting a Python DataFrame

Just for someone looking for a solution more similar to R:

df[(df.Product == p_id) & (df.Time> start_time) & (df.Time < end_time)][['Time','Product']]

No need for data.loc or query, but I do think it is a bit long.

Removing Data From ElasticSearch

#list all index:       curl -XGET http://localhost:9200/_cat/indices?v 

enter image description here

#delete index:         curl -XDELETE 'localhost:9200/index_name'
#delete all indices:   curl -XDELETE 'localhost:9200/_all'
#delete document   :   curl -XDELETE 'localhost:9200/index_name/type_name/document_id'

Install kibana. Kibana has a smarter dev tool which helps to build query easily.

enter image description here

How do you serve a file for download with AngularJS or Javascript?

Would just like to add that in case it doesn't download the file because of unsafe:blob:null... when you hover over the download button, you have to sanitize it. For instance,

var app = angular.module('app', []);

app.config(function($compileProvider){

$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);

The order of keys in dictionaries

Just sort the list when you want to use it.

l = sorted(d.keys())

Change :hover CSS properties with JavaScript

If you use lightweight html ux lang, check here an example, write:

div root
 .onmouseover = ev => {root.style.backgroundColor='red'}
 .onmouseleave = ev => {root.style.backgroundColor='initial'}

The code above performes the css :hover metatag.

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

jQuery: count number of rows in a table

If you use <tbody> or <tfoot> in your table, you'll have to use the following syntax or you'll get a incorrect value:

var rowCount = $('#myTable >tbody >tr').length;

How can I close a dropdown on click outside?

I would like to complement @Tony answer, since the event is not being removed after the click outside the component. Complete receipt:

  • Mark your main element with #container

    @ViewChild('container') container;
    
    _dropstatus: boolean = false;
    get dropstatus() { return this._dropstatus; }
    set dropstatus(b: boolean) 
    {
        if (b) { document.addEventListener('click', this.offclickevent);}
        else { document.removeEventListener('click', this.offclickevent);}
        this._dropstatus = b;
    }
    offclickevent: any = ((evt:any) => { if (!this.container.nativeElement.contains(evt.target)) this.dropstatus= false; }).bind(this);
    
  • On the clickable element, use:

    (click)="dropstatus=true"
    

Now you can control your dropdown state with the dropstatus variable, and apply proper classes with [ngClass]...

How to set shadows in React Native for android?

In short, you can't do that in android, because if you see the docs about shadow only Support IOS see doc

The best option you can install 3rd party react-native-shadow

target input by type and name (selector)

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

React: "this" is undefined inside a component function

If you are using babel, you bind 'this' using ES7 bind operator https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding

export default class SignupPage extends React.Component {
  constructor(props) {
    super(props);
  }

  handleSubmit(e) {
    e.preventDefault(); 

    const data = { 
      email: this.refs.email.value,
    } 
  }

  render() {

    const {errors} = this.props;

    return (
      <div className="view-container registrations new">
        <main>
          <form id="sign_up_form" onSubmit={::this.handleSubmit}>
            <div className="field">
              <input ref="email" id="user_email" type="email" placeholder="Email"  />
            </div>
            <div className="field">
              <input ref="password" id="user_password" type="new-password" placeholder="Password"  />
            </div>
            <button type="submit">Sign up</button>
          </form>
        </main>
      </div>
    )
  }

}

RecyclerView vs. ListView

Advantages of RecyclerView over listview :

  1. Contains ViewHolder by default.

  2. Easy animations.

  3. Supports horizontal , grid and staggered layouts

Advantages of listView over recyclerView :

  1. Easy to add divider.

  2. Can use inbuilt arrayAdapter for simple plain lists

  3. Supports Header and footer .

  4. Supports OnItemClickListner .

Deleting all files from a folder using PHP?

foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

Failed to authenticate on SMTP server error using gmail

I had the same problem and I've already tried everything and nothing seemed to work until I just changed the 'host' value in config.php to:

 'host' => env('smtp.mailtrap.io'),

When I changed that it worked nicely, somehow it was using the default host " smtp.mailtrap.org" and ignoring the .env variable I was setting.

After making some test I realize that if I placed the env variable in this order it would worked as it shoulded:

MAIL_HOST=smtp.mailtrap.io

?MAIL_DRIVER=smtp

?MAIL_PORT=2525?

MAIL_USERNAME=xxxx

?MAIL_PASSWORD=xxx

?MAIL_ENCRYPTION=null

UnicodeEncodeError: 'charmap' codec can't encode characters

I was getting the same UnicodeEncodeError when saving scraped web content to a file. To fix it I replaced this code:

with open(fname, "w") as f:
    f.write(html)

with this:

import io
with io.open(fname, "w", encoding="utf-8") as f:
    f.write(html)

Using io gives you backward compatibility with Python 2.

If you only need to support Python 3 you can use the builtin open function instead:

with open(fname, "w", encoding="utf-8") as f:
    f.write(html)

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

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);