Programs & Examples On #Nsfetchrequest

On macOS 10.4+ and iOS 3.0+, an instance of NSFetchRequest describes the search criteria used to retrieve data from a persistent store. It is a class in the Apple Core Data Framework.

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

At this point in your code the view controller's view has only been created but not added to any view hierarchy. If you want to present from that view controller as soon as possible you should do it in viewDidAppear to be safest.

PHP How to fix Notice: Undefined variable:

You should initialize your variables outside the while loop. Outside the while loop, they currently have no scope. You are just relying on the good graces of php to let the values carry over outside the loop

           $hn = "";
           $pid = "";
           $datereg = "";
           $prefix = "";
           $fname = "";
           $lname = "";
           $age = "";
           $sex = "";
           while (...){}

alternatively, it looks like you are just expecting a single row back. so you could just say

$row = pg_fetch_array($result);
if(!row) {
    return array();
}
$hn = $row["patient_hn"];
$pid = $row["patient_id"];
$datereg = $row["patient_date_register"];
$prefix = $row["patient_prefix"];
$fname = $row["patient_fname"];
$lname = $row["patient_lname"];
$age = $row["patient_age"];
$sex = $row["patient_sex"];

return array($hn,$pid,$datereg,$prefix,$fname,$lname,$age,$sex) ;

How to get JSON from webpage into Python script

you can use json.dumps:

import json

# Hier comes you received data

data = json.dumps(response)

print(data)

for loading json and write it on file the following code is useful:

data = json.loads(json.dumps(Response, sort_keys=False, indent=4))
with open('data.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=False, indent=4)

Postgresql SQL: How check boolean field with null and True,False Value?

On PostgreSQL you can use:

SELECT * FROM table_name WHERE (boolean_column IS NULL OR NOT boolean_column)

How to update two tables in one statement in SQL Server 2005?

From my perspective you can do this, its one to one update of two tables in SQL SERVER:

 BEGIN TRANSACTION

      DECLARE @CNSREQ VARCHAR(30)
      DECLARE @ID INT
      DECLARE @CNSRQDT VARCHAR(30)
      DECLARE @ID2 INT

      DECLARE @IDCNSREQ INT
      DECLARE @FINALCNSREQ VARCHAR(30)
      DECLARE @FINALCNSRQDT VARCHAR(30)
      DECLARE @IDCNSRQDT INT


      SET @CNSREQ=(SELECT MIN(REQUISICIONESDT.CNSREQ) FROM REQUISICIONESDT
          INNER JOIN 
              REQUISICIONES
                ON REQUISICIONESDT.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
           AND REQUISICIONES.CNSREQ = REQUISICIONESDT.CNSREQ AND REQUISICIONESDT.IDREQ = REQUISICIONES.ID
        WHERE REQUISICIONES.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID)

      SELECT REQUISICIONES.CNSREQ, REQUISICIONES.ID, REQUISICIONES.CNSRQDT FROM REQUISICIONES
       INNER JOIN 
          REQUISICIONESDT
              ON REQUISICIONESDT.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
               AND REQUISICIONES.CNSREQ = REQUISICIONESDT.CNSREQ AND REQUISICIONESDT.IDREQ = REQUISICIONES.ID
        WHERE REQUISICIONES.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
    AND REQUISICIONES.CNSREQ = @CNSREQ

        UPDATE REQUISICIONESDT SET  REQUISICIONESDT.CNSREQ=NULL, REQUISICIONESDT.IDREQ=NULL
          FROM REQUISICIONES INNER JOIN REQUISICIONESDT
             ON REQUISICIONESDT.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
       WHERE REQUISICIONES.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
      AND REQUISICIONES.CNSREQ = @CNSREQ

        UPDATE REQUISICIONES SET REQUISICIONES.CNSRQDT=NULL, REQUISICIONES.IDRQDT=NULL
          FROM REQUISICIONES INNER JOIN REQUISICIONESDT
          ON REQUISICIONESDT.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
       WHERE REQUISICIONES.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
     AND REQUISICIONES.CNSREQ = @CNSREQ

       SET @ID2=(SELECT MIN(REQUISICIONESDT.ID) FROM REQUISICIONESDT
        WHERE ISNULL(REQUISICIONESDT.IDREQ,0)<>0)
     DELETE FROM REQUISICIONESDT WHERE REQUISICIONESDT.ID=@ID2


      SET @IDCNSREQ=(SELECT MIN (REQUISICIONES.ID)FROM REQUISICIONES
          INNER JOIN REQUISICIONESDT ON
        REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
         WHERE REQUISICIONES.CNSRQDT IS NULL AND REQUISICIONES.IDRQDT IS NULL)

        SET @FINALCNSREQ=(SELECT MIN (REQUISICIONES.CNSREQ)FROM REQUISICIONES
            INNER JOIN REQUISICIONESDT ON
        REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
         WHERE REQUISICIONES.CNSRQDT IS NULL AND REQUISICIONES.IDRQDT IS NULL)

         SET @FINALCNSRQDT=(SELECT MIN(REQUISICIONESDT.CNSRQDT) FROM REQUISICIONES
           INNER JOIN REQUISICIONESDT ON
          REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
           WHERE REQUISICIONES.CNSRQDT IS NULL AND REQUISICIONES.IDRQDT IS NULL)

          SET @IDCNSRQDT=(SELECT MIN (REQUISICIONESDT.ID)FROM REQUISICIONES
           INNER JOIN REQUISICIONESDT ON
         REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD  
         WHERE REQUISICIONES.CNSRQDT IS NULL AND REQUISICIONES.IDRQDT IS NULL)

           UPDATE REQUISICIONES SET REQUISICIONES.CNSRQDT = @FINALCNSRQDT, REQUISICIONES.IDRQDT=@IDCNSRQDT FROM REQUISICIONES
            INNER JOIN REQUISICIONESDT ON
             REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
            WHERE REQUISICIONESDT.CNSRQDT = @FINALCNSRQDT AND REQUISICIONESDT.ID = @IDCNSRQDT 


ROLLBACK TRANSACTION

Datepicker: How to popup datepicker when click on edittext

I thought it better to override the EditText class...

public class EditTextDP extends android.support.v7.widget.AppCompatEditText implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
    public EditTextDP(Context context) {
        super(context);
        setOnClickListener(this);
        setFocusable(false);
    }

    public EditTextDP(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(this);
        setFocusable(false);
    }

    public EditTextDP(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnClickListener(this);
        setFocusable(false);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        setText(new StringBuilder().append(dayOfMonth).append("/").append(monthOfYear + 1).append("/").append(year));
    }

    @Override
    public void onClick(View v) {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        DatePickerDialog dialog = new DatePickerDialog(getContext(), this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }
}

And use that in the XML instead...

            <*.*.*.EditTextDP
                android:id="@+id/c1_dob_hm"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/round_edittext_white"
                android:ems="10"
                android:padding="8dp">

            </*.*.*.EditTextDP>

Java Reflection: How to get the name of a variable?

You can do like this:

Field[] fields = YourClass.class.getDeclaredFields();
//gives no of fields
System.out.println(fields.length);         
for (Field field : fields) {
    //gives the names of the fields
    System.out.println(field.getName());   
}

Styling Form with Label above Inputs

You could try something like

<form name="message" method="post">
    <section>
    <div>
      <label for="name">Name</label>
      <input id="name" type="text" value="" name="name">
    </div>
    <div>
      <label for="email">Email</label>
      <input id="email" type="text" value="" name="email">
    </div>
    </section>
    <section>
    <div>
      <label for="subject">Subject</label>
      <input id="subject" type="text" value="" name="subject">
    </div>
    <div class="full">
      <label for="message">Message</label>
      <input id="message" type="text" value="" name="message">
    </div>
    </section>
</form>

and then css it like

form { width: 400px; }
form section div { float: left; }
form section div.full { clear: both; }
form section div label { display: block; }

Docker is in volume in use, but there aren't any Docker containers

I am pretty sure that those volumes are actually mounted on your system. Look in /proc/mounts and you will see them there. You will likely need to sudo umount <path> or sudo umount -f -n <path>. You should be able to get the mounted path either in /proc/mounts or through docker volume inspect

How do I search a Perl array for a matching string?

#!/usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;

my @bar = qw(aaa bbb);
my @foo = grep {/aAa/i} @bar;

print Dumper \@foo;

How to display a confirmation dialog when clicking an <a> link?

USING PHP, HTML AND JAVASCRIPT for prompting

Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.

<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>

the reason i used php code in the middle is because i cant use it from the beginning..

the code below doesnt work for me:-

echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";

and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.

How to escape braces (curly brackets) in a format string in .NET

My objective:

I needed to assign the value "{CR}{LF}" to a string variable delimiter.

Code c#:

string delimiter= "{{CR}}{{LF}}";

Note: To escape special characters normally you have to use . For opening curly bracket {, use one extra like {{. For closing curly bracket }, use one extra }}.

How to see query history in SQL Server Management Studio

Query history can be viewed using the system views:

  1. sys.dm_exec_query_stats
  2. sys.dm_exec_sql_text
  3. sys.dm_exec_query_plan

For example, using the following query:

select  top(100)
        creation_time,
        last_execution_time,
        execution_count,
        total_worker_time/1000 as CPU,
        convert(money, (total_worker_time))/(execution_count*1000)as [AvgCPUTime],
        qs.total_elapsed_time/1000 as TotDuration,
        convert(money, (qs.total_elapsed_time))/(execution_count*1000)as [AvgDur],
        total_logical_reads as [Reads],
        total_logical_writes as [Writes],
        total_logical_reads+total_logical_writes as [AggIO],
        convert(money, (total_logical_reads+total_logical_writes)/(execution_count + 0.0)) as [AvgIO],
        [sql_handle],
        plan_handle,
        statement_start_offset,
        statement_end_offset,
        plan_generation_num,
        total_physical_reads,
        convert(money, total_physical_reads/(execution_count + 0.0)) as [AvgIOPhysicalReads],
        convert(money, total_logical_reads/(execution_count + 0.0)) as [AvgIOLogicalReads],
        convert(money, total_logical_writes/(execution_count + 0.0)) as [AvgIOLogicalWrites],
        query_hash,
        query_plan_hash,
        total_rows,
        convert(money, total_rows/(execution_count + 0.0)) as [AvgRows],
        total_dop,
        convert(money, total_dop/(execution_count + 0.0)) as [AvgDop],
        total_grant_kb,
        convert(money, total_grant_kb/(execution_count + 0.0)) as [AvgGrantKb],
        total_used_grant_kb,
        convert(money, total_used_grant_kb/(execution_count + 0.0)) as [AvgUsedGrantKb],
        total_ideal_grant_kb,
        convert(money, total_ideal_grant_kb/(execution_count + 0.0)) as [AvgIdealGrantKb],
        total_reserved_threads,
        convert(money, total_reserved_threads/(execution_count + 0.0)) as [AvgReservedThreads],
        total_used_threads,
        convert(money, total_used_threads/(execution_count + 0.0)) as [AvgUsedThreads],
        case 
            when sql_handle IS NULL then ' '
            else(substring(st.text,(qs.statement_start_offset+2)/2,(
                case
                    when qs.statement_end_offset =-1 then len(convert(nvarchar(MAX),st.text))*2      
                    else qs.statement_end_offset    
                end - qs.statement_start_offset)/2  ))
        end as query_text,
        db_name(st.dbid) as database_name,
        object_schema_name(st.objectid, st.dbid)+'.'+object_name(st.objectid, st.dbid) as [object_name],
        sp.[query_plan]
from sys.dm_exec_query_stats as qs with(readuncommitted)
cross apply sys.dm_exec_sql_text(qs.[sql_handle]) as st
cross apply sys.dm_exec_query_plan(qs.[plan_handle]) as sp
WHERE st.[text] LIKE '%query%'

Current running queries can be seen using the following script:

select ES.[session_id]
      ,ER.[blocking_session_id]
      ,ER.[request_id]
      ,ER.[start_time]
      ,DateDiff(second, ER.[start_time], GetDate()) as [date_diffSec]
      , COALESCE(
                    CAST(NULLIF(ER.[total_elapsed_time] / 1000, 0) as BIGINT)
                   ,CASE WHEN (ES.[status] <> 'running' and isnull(ER.[status], '')  <> 'running') 
                            THEN  DATEDIFF(ss,0,getdate() - nullif(ES.[last_request_end_time], '1900-01-01T00:00:00.000'))
                    END
                ) as [total_time, sec]
      , CAST(NULLIF((CAST(ER.[total_elapsed_time] as BIGINT) - CAST(ER.[wait_time] AS BIGINT)) / 1000, 0 ) as bigint) as [work_time, sec]
      , CASE WHEN (ER.[status] <> 'running' AND ISNULL(ER.[status],'') <> 'running') 
                THEN  DATEDIFF(ss,0,getdate() - nullif(ES.[last_request_end_time], '1900-01-01T00:00:00.000'))
        END as [sleep_time, sec] --????? ??? ? ???
      , NULLIF( CAST((ER.[logical_reads] + ER.[writes]) * 8 / 1024 as numeric(38,2)), 0) as [IO, MB]
      , CASE  ER.transaction_isolation_level
        WHEN 0 THEN 'Unspecified'
        WHEN 1 THEN 'ReadUncommited'
        WHEN 2 THEN 'ReadCommited'
        WHEN 3 THEN 'Repetable'
        WHEN 4 THEN 'Serializable'
        WHEN 5 THEN 'Snapshot'
        END as [transaction_isolation_level_desc]
      ,ER.[status]
      ,ES.[status] as [status_session]
      ,ER.[command]
      ,ER.[percent_complete]
      ,DB_Name(coalesce(ER.[database_id], ES.[database_id])) as [DBName]
      , SUBSTRING(
                    (select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle]))
                  , ER.[statement_start_offset]/2+1
                  , (
                        CASE WHEN ((ER.[statement_start_offset]<0) OR (ER.[statement_end_offset]<0))
                                THEN DATALENGTH ((select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle])))
                             ELSE ER.[statement_end_offset]
                        END
                        - ER.[statement_start_offset]
                    )/2 +1
                 ) as [CURRENT_REQUEST]
      ,(select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle])) as [TSQL]
      ,(select top(1) [objectid] from sys.dm_exec_sql_text(ER.[sql_handle])) as [objectid]
      ,(select top(1) [query_plan] from sys.dm_exec_query_plan(ER.[plan_handle])) as [QueryPlan]
      ,NULL as [event_info]--(select top(1) [event_info] from sys.dm_exec_input_buffer(ES.[session_id], ER.[request_id])) as [event_info]
      ,ER.[wait_type]
      ,ES.[login_time]
      ,ES.[host_name]
      ,ES.[program_name]
      ,cast(ER.[wait_time]/1000 as decimal(18,3)) as [wait_timeSec]
      ,ER.[wait_time]
      ,ER.[last_wait_type]
      ,ER.[wait_resource]
      ,ER.[open_transaction_count]
      ,ER.[open_resultset_count]
      ,ER.[transaction_id]
      ,ER.[context_info]
      ,ER.[estimated_completion_time]
      ,ER.[cpu_time]
      ,ER.[total_elapsed_time]
      ,ER.[scheduler_id]
      ,ER.[task_address]
      ,ER.[reads]
      ,ER.[writes]
      ,ER.[logical_reads]
      ,ER.[text_size]
      ,ER.[language]
      ,ER.[date_format]
      ,ER.[date_first]
      ,ER.[quoted_identifier]
      ,ER.[arithabort]
      ,ER.[ansi_null_dflt_on]
      ,ER.[ansi_defaults]
      ,ER.[ansi_warnings]
      ,ER.[ansi_padding]
      ,ER.[ansi_nulls]
      ,ER.[concat_null_yields_null]
      ,ER.[transaction_isolation_level]
      ,ER.[lock_timeout]
      ,ER.[deadlock_priority]
      ,ER.[row_count]
      ,ER.[prev_error]
      ,ER.[nest_level]
      ,ER.[granted_query_memory]
      ,ER.[executing_managed_code]
      ,ER.[group_id]
      ,ER.[query_hash]
      ,ER.[query_plan_hash]
      ,EC.[most_recent_session_id]
      ,EC.[connect_time]
      ,EC.[net_transport]
      ,EC.[protocol_type]
      ,EC.[protocol_version]
      ,EC.[endpoint_id]
      ,EC.[encrypt_option]
      ,EC.[auth_scheme]
      ,EC.[node_affinity]
      ,EC.[num_reads]
      ,EC.[num_writes]
      ,EC.[last_read]
      ,EC.[last_write]
      ,EC.[net_packet_size]
      ,EC.[client_net_address]
      ,EC.[client_tcp_port]
      ,EC.[local_net_address]
      ,EC.[local_tcp_port]
      ,EC.[parent_connection_id]
      ,EC.[most_recent_sql_handle]
      ,ES.[host_process_id]
      ,ES.[client_version]
      ,ES.[client_interface_name]
      ,ES.[security_id]
      ,ES.[login_name]
      ,ES.[nt_domain]
      ,ES.[nt_user_name]
      ,ES.[memory_usage]
      ,ES.[total_scheduled_time]
      ,ES.[last_request_start_time]
      ,ES.[last_request_end_time]
      ,ES.[is_user_process]
      ,ES.[original_security_id]
      ,ES.[original_login_name]
      ,ES.[last_successful_logon]
      ,ES.[last_unsuccessful_logon]
      ,ES.[unsuccessful_logons]
      ,ES.[authenticating_database_id]
      ,ER.[sql_handle]
      ,ER.[statement_start_offset]
      ,ER.[statement_end_offset]
      ,ER.[plan_handle]
      ,NULL as [dop]--ER.[dop]
      ,coalesce(ER.[database_id], ES.[database_id]) as [database_id]
      ,ER.[user_id]
      ,ER.[connection_id]
from sys.dm_exec_requests ER with(readuncommitted)
right join sys.dm_exec_sessions ES with(readuncommitted)
on ES.session_id = ER.session_id 
left join sys.dm_exec_connections EC  with(readuncommitted)
on EC.session_id = ES.session_id
where ER.[status] in ('suspended', 'running', 'runnable')
or exists (select top(1) 1 from sys.dm_exec_requests as ER0 where ER0.[blocking_session_id]=ES.[session_id])

This request displays all active requests and all those requests that explicitly block active requests.

All these and other useful scripts are implemented as representations in the SRV database, which is distributed freely. For example, the first script came from the view [inf].[vBigQuery], and the second came from view [inf].[vRequests].

There are also various third-party solutions for query history. I use Query Manager from Dbeaver: enter image description here and Query Execution History from SQL Tools, which is embedded in SSMS: enter image description here

What is the use of static synchronized method in java?

In general, synchronized methods are used to protect access to resources that are accessed concurrently. When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized instance method; when the resource belongs to all instances (i.e. when it is in a static variable) then you use a synchronized static method to access it.

For example, you could make a static factory method that keeps a "registry" of all objects that it has produced. A natural place for such registry would be a static collection. If your factory is used from multiple threads, you need to make the factory method synchronized (or have a synchronized block inside the method) to protect access to the shared static collection.

Note that using synchronized without a specific lock object is generally not the safest choice when you are building a library to be used in code written by others. This is because malicious code could synchronize on your object or a class to block your own methods from executing. To protect your code against this, create a private "lock" object, instance or static, and synchronize on that object instead.

POST request via RestTemplate in JSON

I've been using rest template with JSONObjects as follow:

// create request body
JSONObject request = new JSONObject();
request.put("username", name);
request.put("password", password);

// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);

// send request and parse result
ResponseEntity<String> loginResponse = restTemplate
  .exchange(urlString, HttpMethod.POST, entity, String.class);
if (loginResponse.getStatusCode() == HttpStatus.OK) {
  JSONObject userJson = new JSONObject(loginResponse.getBody());
} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
  // nono... bad credentials
}

Enterprise app deployment doesn't work on iOS 7.1

After reading this post I had still a problem with downloading my app. Problem was because of self signed SSL certificate.

I've found a solution for this problem. You need to upload your certificate file with extension '.crt' on the web and type address of it in your mobile safari. System ask you about adding your certificate to the list of trusted certificates. After this operation you will be able to install your ad-hoc app.

What is the difference between join and merge in Pandas?

  • Join: Default Index (If any same column name then it will throw an error in default mode because u have not defined lsuffix or rsuffix))
df_1.join(df_2)
  • Merge: Default Same Column Names (If no same column name it will throw an error in default mode)
df_1.merge(df_2)
  • on parameter has different meaning in both cases
df_1.merge(df_2, on='column_1')

df_1.join(df_2, on='column_1') // It will throw error
df_1.join(df_2.set_index('column_1'), on='column_1')

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

How to create a sub array from another array in Java?

The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:

java -version

I'm guessing that you are not running 1.6

PHP split alternative?

You can use the easier function preg_match instead, It's better and faster than all of the other ones.

$var = "<tag>Get this var</tag>";
preg_match("/<tag>(.*)<\/tag>/", $var , $new_var);
echo $new_var['1']; 

Output: Get this var

Java Web Service client basic authentication

The JAX-WS way for basic authentication is

Service s = new Service();
Port port = s.getPort();

BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");

port.call();

What are all the different ways to create an object in Java?

Within the Java language, the only way to create an object is by calling its constructor, be it explicitly or implicitly. Using reflection results in a call to the constructor method, deserialization uses reflection to call the constructor, factory methods wrap the call to the constructor to abstract the actual construction and cloning is similarly a wrapped constructor call.

Add disabled attribute to input element using Javascript

Since the question was asking how to do this with JS I'm providing a vanilla JS implementation.

_x000D_
_x000D_
var element = document.querySelector(".your-element-class-goes-here");
// it's a good idea to check whether the element exists
if (element != null && element != undefined) {
  element.disabled = "disabled";
}
_x000D_
_x000D_
_x000D_

Handling onchange event in HTML.DropDownList Razor MVC

Description

You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

Sample

@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })

More Information

When do I have to use interfaces instead of abstract classes?

You can't achieve multiple inheritance with abstract class, that is why Sun Microsystems provide interfaces.

You cannot extend two classes but you can implement multiple interfaces.

Git reset --hard and push to remote repository

The whole git resetting business looked far to complicating for me.

So I did something along the lines to get my src folder in the state i had a few commits ago

# reset the local state
git reset <somecommit> --hard 
# copy the relevant part e.g. src (exclude is only needed if you specify .)
tar cvfz /tmp/current.tgz --exclude .git  src
# get the current state of git
git pull
# remove what you don't like anymore
rm -rf src
# restore from the tar file
tar xvfz /tmp/current.tgz
# commit everything back to git
git commit -a
# now you can properly push
git push

This way the state of affairs in the src is kept in a tar file and git is forced to accept this state without too much fiddling basically the src directory is replaced with the state it had several commits ago.

How to define custom exception class in Java, the easiest way?

and don't forget the easiest way to throw an exception (you don't need to create a class)

if (rgb > MAX) throw new RuntimeException("max color exceeded");

Uses of Action delegate in C#

For an example of how Action<> is used.

Console.WriteLine has a signature that satisifies Action<string>.

    static void Main(string[] args)
    {
        string[] words = "This is as easy as it looks".Split(' ');

        // Passing WriteLine as the action
        Array.ForEach(words, Console.WriteLine);         
    }

Hope this helps

Jquery UI tooltip does not support html content

To avoid placing HTML tags in the title attribute, another solution is to use markdown. For instance, you could use [br] to represent a line break, then perform a simple replace in the content function.

In title attribute:

"Sample Line 1[br][br]Sample Line 2"

In your content function:

content: function () {
    return $(this).attr('title').replace(/\[br\]/g,"<br />");
}

How to prevent long words from breaking my div?

Do you mean that, in browsers that support it, word-wrap: break-word does not work ?

If included in the body definition of the stylesheet, it should works throughout the entire document.

If overflow is not a good solution, only a custom javascript could artificially break up long word.

Note: there is also this <wbr> Word Break tag. This gives the browser a spot where it can split the line up. Unfortunately, the <wbr> tag doesn't work in all browsers, only Firefox and Internet Explorer (and Opera with a CSS trick).

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

nVarchar2 is a Unicode-only storage.

Though both data types are variable length String datatypes, you can notice the difference in how they store values. Each character is stored in bytes. As we know, not all languages have alphabets with same length, eg, English alphabet needs 1 byte per character, however, languages like Japanese or Chinese need more than 1 byte for storing a character.

When you specify varchar2(10), you are telling the DB that only 10 bytes of data will be stored. But, when you say nVarchar2(10), it means 10 characters will be stored. In this case, you don't have to worry about the number of bytes each character takes.

How can I display an RTSP video stream in a web page?

I know that this post is old but I was looking for something very similar the other day (view my IP cam's RTSP video feed on a simple html page without any fancy ActiveX plugins). Lucky me, I found a solution! It is based on ffmpeg, NodeJS, NGINX (not mandatory but useful) and Node Media Server.

The description in the link is detailed and easy to follow, but I still had some tweaks to deal with before I got it to work (regarding endpoints on the NodeJS server). I made an own question for it and got a good and working answer.

How do I add all new files to SVN

svn status | grep "^\?" | awk '{ printf("\""); for (f=2; f <= NF; f++) { printf("%s", $f); if (f<NF) printf(" "); } printf("\"\n");}' | xargs svn add

This was based on markb's answer... and a little hunting on the internet. It looks ugly, but it seems to work for me on OS X (including files with spaces).

Passing data to a jQuery UI Dialog

In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.

I agree with mausch, you should really look at using POST for these actions, which will add a <form> tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).

How to replace a substring of a string

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

from javadoc.

Combine two columns of text in pandas dataframe

The method cat() of the .str accessor works really well for this:

>>> import pandas as pd
>>> df = pd.DataFrame([["2014", "q1"], 
...                    ["2015", "q3"]],
...                   columns=('Year', 'Quarter'))
>>> print(df)
   Year Quarter
0  2014      q1
1  2015      q3
>>> df['Period'] = df.Year.str.cat(df.Quarter)
>>> print(df)
   Year Quarter  Period
0  2014      q1  2014q1
1  2015      q3  2015q3

cat() even allows you to add a separator so, for example, suppose you only have integers for year and period, you can do this:

>>> import pandas as pd
>>> df = pd.DataFrame([[2014, 1],
...                    [2015, 3]],
...                   columns=('Year', 'Quarter'))
>>> print(df)
   Year Quarter
0  2014       1
1  2015       3
>>> df['Period'] = df.Year.astype(str).str.cat(df.Quarter.astype(str), sep='q')
>>> print(df)
   Year Quarter  Period
0  2014       1  2014q1
1  2015       3  2015q3

Joining multiple columns is just a matter of passing either a list of series or a dataframe containing all but the first column as a parameter to str.cat() invoked on the first column (Series):

>>> df = pd.DataFrame(
...     [['USA', 'Nevada', 'Las Vegas'],
...      ['Brazil', 'Pernambuco', 'Recife']],
...     columns=['Country', 'State', 'City'],
... )
>>> df['AllTogether'] = df['Country'].str.cat(df[['State', 'City']], sep=' - ')
>>> print(df)
  Country       State       City                   AllTogether
0     USA      Nevada  Las Vegas      USA - Nevada - Las Vegas
1  Brazil  Pernambuco     Recife  Brazil - Pernambuco - Recife

Do note that if your pandas dataframe/series has null values, you need to include the parameter na_rep to replace the NaN values with a string, otherwise the combined column will default to NaN.

Object not found! The requested URL was not found on this server. localhost

Is the Config/setup.php file actually in /test/content/home/ or is in your document root? it is best to make all references relative to your document root.

include $_SERVER['DOCUMENT_ROOT'] . "Config/setup.php";

Your current code assumes that the location of setup.php is in /text/content/home/Config/setup.php, is this correct?

How can I reload .emacs after changing it?

Beside commands like M-x eval-buffer or M-x load-file you can restart a fresh emacs from the command line:

emacs -q --load "init.el"

Usage example stackoverflow.com/questions/44959535/company-backends-in-gnu-emacs/

Calling a Sub in VBA

For anyone still coming to this post, the other option is to simply omit the parentheses:

Sub SomeOtherSub(Stattyp As String)
    'Daty and the other variables are defined here

    CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2

End Sub

The Call keywords is only really in VBA for backwards compatibilty and isn't actually required.

If however, you decide to use the Call keyword, then you have to change your syntax to suit.

'// With Call
Call Foo(Bar)

'// Without Call
Foo Bar

Both will do exactly the same thing.


That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call keyword and the parentheses

HashMap and int as key

For somebody who is interested in a such map because you want to reduce footprint of autoboxing in Java of wrappers over primitives types, I would recommend to use Eclipse collections. Trove isn't supported any more, and I believe it is quite unreliable library in this sense (though it is quite popular anyway) and couldn't be compared with Eclipse collections.

import org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap;

public class Check {
    public static void main(String[] args) {
        IntObjectHashMap map = new IntObjectHashMap();

        map.put(5,"It works");
        map.put(6,"without");
        map.put(7,"boxing!");

        System.out.println(map.get(5));
        System.out.println(map.get(6));
        System.out.println(map.get(7));
    }
}

In this example above IntObjectHashMap.

As you need int->object mapping, also consider usage of YourObjectType[] array or List<YourObjectType> and access values by index, as map is, by nature, an associative array with int type as index.

Why do multiple-table joins produce duplicate rows?

Ok in this example you are getting duplicates because you are joining both D and S onto M. I assume you should be joining D.id onto S.id like below:

SELECT *
FROM M
INNER JOIN S
    on M.Id = S.Id
INNER JOIN D
    ON S.Id = D.Id
INNER JOIN H
    ON D.Id = H.Id

How to trigger jQuery change event in code

for me $('#element').val('...').change() is the best way.

How to open URL in Microsoft Edge from the command line?

It will do more or less the same thing in good old dos script fashion

set add=%1
if %add%$ ==$ set add="about:blank" && goto launch

rem http://
set test=%add:~0, 7%
if %test% == http:// goto launch

rem ftp:// 
set test=%add:~0, 6%
if %test% == ftp:// goto launch

rem https://
set test=%add:~0, 8%
if %test% == https:// goto launch

rem add http
set add=http://%add%

:launch
start microsoft-edge:%add%

Pandas group-by and sum

If you want to keep the original columns Fruit and Name, use reset_index(). Otherwise Fruit and Name will become part of the index.

df.groupby(['Fruit','Name'])['Number'].sum().reset_index()

Fruit   Name       Number
Apples  Bob        16
Apples  Mike        9
Apples  Steve      10
Grapes  Bob        35
Grapes  Tom        87
Grapes  Tony       15
Oranges Bob        67
Oranges Mike       57
Oranges Tom        15
Oranges Tony        1

As seen in the other answers:

df.groupby(['Fruit','Name'])['Number'].sum()

               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

see if two files have the same content in python

I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.

There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can

  • Compare file sizes first, discarding all which doesn't match
  • If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file

Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)

Test method is inconclusive: Test wasn't run. Error?

In my case i got this error because of 'Release' mode where build of UnitTests project was simply switched off. Switching back to 'Debug' mode fixed it.

It's really surprising that ReSharper cannot say anything in case it cannot find UnitTests library at all. Seriously, it's a shame;)

Hope it will help somebody

How to grep recursively, but only in files with certain extensions?

The easiest way is

find . -type  f -name '*.extension' 2>/dev/null | xargs grep -i string 

Edit: add 2>/dev/null to kill the error output

To include more file extensions and grep for password throughout the system:

find / -type  f \( -name '*.conf' -o -name "*.log" -o -name "*.bak" \) 2>/dev/null |
xargs grep -i password

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table) and the candidate key-> the same as Primary key but the Primary Key chosen by DB administrator's prospective for example(the primary key the least candidate key in size)

How to send a model in jQuery $.ajax() post request to MVC controller method

If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

In our app, we do this with an extension method:

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

On the view, we use it to render the model:

<script type="javascript">
  var model = <%= Model.ToJson() %>
</script>

You can then pass the model variable into your $.ajax call.

What are the safe characters for making URLs?

To quote section 2.3 of RFC 3986:

Characters that are allowed in a URI, but do not have a reserved purpose, are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.

  ALPHA  DIGIT  "-" / "." / "_" / "~"

Note that RFC 3986 lists fewer reserved punctuation marks than the older RFC 2396.

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Why do I have ORA-00904 even when the column is present?

Have you compared the table definitions in Prod and Dev?

And when you are running it in SQL Developer, are you running the query in Prod (same database as the application) and with the same user?

If there are some additional columns that you are adding (using an alter command) and these changes are not yet promoted to prod, this issue is possible.

Can you post the definition of the table and your actual Query?

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

It means that the standard now defines multi-threading, and it defines what happens in the context of multiple threads. Of course, people used varying implementations, but that's like asking why we should have a std::string when we could all be using a home-rolled string class.

When you're talking about POSIX threads or Windows threads, then this is a bit of an illusion as actually you're talking about x86 threads, as it's a hardware function to run concurrently. The C++0x memory model makes guarantees, whether you're on x86, or ARM, or MIPS, or anything else you can come up with.

show/hide html table columns using css

if you're looking for a simple column hide you can use the :nth-child selector as well.

#tableid tr td:nth-child(3),
#tableid tr th:nth-child(3) {
    display: none;
}

I use this with the @media tag sometimes to condense wider tables when the screen is too narrow.

How to resolve compiler warning 'implicit declaration of function memset'

Try to add next define at start of your .c file:

#define _GNU_SOURCE

It helped me with pipe2 function.

How to set 24-hours format for date on java?

Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);

HH will return 0-23 for hours.

kk will return 1-24 for hours.

See more here: Customizing Formats

use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.

How to remove items from a list while iterating?

You might want to use filter() available as the built-in.

For more details check here

How to add anything in <head> through jquery/javascript?

Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:

var temp = document.createElement('div');

temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
               + '<script src="foobar.js"><\/script> ';

var head = document.head;

while (temp.firstChild) {
    head.appendChild(temp.firstChild);
}

Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.

Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().

How to convert time milliseconds to hours, min, sec format in JavaScript?

The above snippets don't work for cases with more than 1 day (They are simply ignored).

For this you can use:

function convertMS(ms) {
    var d, h, m, s;
    s = Math.floor(ms / 1000);
    m = Math.floor(s / 60);
    s = s % 60;
    h = Math.floor(m / 60);
    m = m % 60;
    d = Math.floor(h / 24);
    h = h % 24;
    h += d * 24;
    return h + ':' + m + ':' + s;
}

enter image description here

Thanks to https://gist.github.com/remino/1563878

How does data binding work in AngularJS?

  1. The one-way data binding is an approach where a value is taken from the data model and inserted into an HTML element. There is no way to update model from view. It is used in classical template systems. These systems bind data in only one direction.

  2. Data-binding in Angular apps is the automatic synchronisation of data between the model and view components.

Data binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. If the model is changed, the view reflects the change and vice versa.

How to use ng-if to test if a variable is defined

Try this:

item.shipping!==undefined

How to join components of a path when you are constructing a URL in Python

To improve slightly over Alex Martelli's response, the following will not only cleanup extra slashes but also preserve trailing (ending) slashes, which can sometimes be useful :

>>> items = ["http://www.website.com", "/api", "v2/"]
>>> url = "/".join([(u.strip("/") if index + 1 < len(items) else u.lstrip("/")) for index, u in enumerate(items)])
>>> print(url)
http://www.website.com/api/v2/

It's not as easy to read though, and won't cleanup multiple extra trailing slashes.

Class method decorator with self arguments?

You can't. There's no self in the class body, because no instance exists. You'd need to pass it, say, a str containing the attribute name to lookup on the instance, which the returned function can then do, or use a different method entirely.

Changing upload_max_filesize on PHP

By default, PHP permits uploading maximum 2 MB file on the server. But you can modify the maximum size of file upload as per your condition. By using the PHP configuration file php.ini, you can increase or decrease the file upload size in PHP.

First open the php.ini file in your text editor. Search the upload_max_filesize variable and stipulate the size which you want to increase.

Search for post_max_size variable and stipulate the size which you want to increase.

post_max_size = 128M

you can check this from here

How to select only 1 row from oracle sql?

The answer is:

You should use nested query as:

SELECT *
FROM ANY_TABLE_X 
WHERE ANY_COLUMN_X = (SELECT MAX(ANY_COLUMN_X) FROM ANY_TABLE_X) 

=> In PL/SQL "ROWNUM = 1" is NOT equal to "TOP 1" of TSQL.

So you can't use a query like this: "select * from any_table_x where rownum=1 order by any_column_x;" Because oracle gets first row then applies order by clause.

MySQL Workbench not displaying query results

I had the same problem after upgrading to Ubuntu 14.10. I found this link which describes the steps to be followed in order to apply the patch. It takes a while since you have to start all over again: downloading, building, installing... but it worked for me! Sorry I'm not an expert and I can't provide further details.

Here are the steps described in the link above:

If you want to patch and build mysql-workbench yourself, get the source from for 6.2.3. From the directory you downloaded it to, do:

wget 'http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-workbench-community-6.2.3-src.tar.gz'

tar xvf mysql-workbench-community-6.2.3-src.tar.gz && cd mysql-workbench-community-6.2.3-src

wget -O patch-glib.diff 'http://bugs.mysql.com/file.php?id=21874&bug_id=74147'

patch -p0 < patch-glib.diff

sudo apt-get build-dep mysql-workbench

sudo apt-get install libgdal-dev

cd build

cmake .. -DBUILD_CONFIG=mysql_release

make

sudo make install

Hope this can be helpful.

How to get jQuery to wait until an effect is finished?

With jQuery 1.6 version you can use the .promise() method.

$(selector).fadeOut('slow');
$(selector).promise().done(function(){
    // will be called when all the animations on the queue finish
});

How to install and run Typescript locally in npm?

As of npm 5.2.0, once you've installed locally via

npm i typescript --save-dev

...you no longer need an entry in the scripts section of package.json -- you can now run the compiler with npx:

npx tsc

Now you don't have to update your package.json file every time you want to compile with different arguments.

How to manually send HTTP POST requests from Firefox or Chrome browser?

Forget browser and try CLI. HTTPie is great tool!

HTTPie screenshot

CLI http clients:

If you insist on browser extension then:

Chrome:

Firefox:

How to use lodash to find and return an object from Array?

lodash and ES5

var song = _.find(songs, {id:id});

lodash and ES6

let song = _.find(songs, {id});

docs at https://lodash.com/docs#find

SQL Server : export query as a .txt file

Another way is from command line, using the osql:

OSQL -S SERVERNAME -E -i thequeryfile.sql -o youroutputfile.txt

This can be used from a BAT file and shceduled by a windows user to authenticated.

Expected corresponding JSX closing tag for input Reactjs

You have to close all tags like , etc for this to not show.

Filtering a spark dataframe based on date

The following solutions are applicable since spark 1.5 :

For lower than :

// filter data where the date is lesser than 2015-03-14
data.filter(data("date").lt(lit("2015-03-14")))      

For greater than :

// filter data where the date is greater than 2015-03-14
data.filter(data("date").gt(lit("2015-03-14"))) 

For equality, you can use either equalTo or === :

data.filter(data("date") === lit("2015-03-14"))

If your DataFrame date column is of type StringType, you can convert it using the to_date function :

// filter data where the date is greater than 2015-03-14
data.filter(to_date(data("date")).gt(lit("2015-03-14"))) 

You can also filter according to a year using the year function :

// filter data where year is greater or equal to 2016
data.filter(year($"date").geq(lit(2016))) 

Best way to specify whitespace in a String.Split operation

If you just call:

string[] ssize = myStr.Split(null); //Or myStr.Split()

or:

string[] ssize = myStr.Split(new char[0]);

then white-space is assumed to be the splitting character. From the string.Split(char[]) method's documentation page.

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

Always, always, always read the documentation!

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

I strongly recommend to use a Maven Repository Manager such as Nexus. It will help you to get stable and reproducible builds with Maven. As the Repository Manager is usually in your LAN, you don't have to configure the proxy settings, but you need to define some other configurations:

http://www.sonatype.com/books/nexus-book/reference/maven-sect-single-group.html

http://maven.apache.org/repository-management.html

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

Pause Console in C++ program

The best way depends a lot on the platform(s) being targeted, debug vs. release usage etc.

I don't think there is one best way, but to "force" a wait on enter type scenario in a fairly generic way, especially when debugging (typically this is either compiled in or out based on NDEBUG or _DEBUG), you could try std::getline as follows

inline void wait_on_enter()
{
    std::string dummy;
    std::cout << "Enter to continue..." << std::endl;
    std::getline(std::cin, dummy);
}

With our without the "enter to continue", as needed.

Upload file to SFTP using PowerShell

I am able to sftp using PowerShell as below:

PS C:\Users\user\Desktop> sftp [email protected]                                                     
[email protected]'s password:
Connected to [email protected].
sftp> ls
testFolder
sftp> cd testFolder
sftp> ls
taj_mahal.jpeg
sftp> put taj_mahal_1.jpeg
Uploading taj_mahal_1.jpeg to /home/user/testFolder/taj_mahal_1.jpeg
taj_mahal_1.jpeg                                                                      100%   11KB  35.6KB/s   00:00
sftp> ls
taj_mahal.jpeg      taj_mahal_1.jpeg
sftp>

I do not have installed Posh-SSH or anything like that. I am using Windows 10 Pro PowerShell. No additional modules installed.

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :

 android:theme="@style/Theme.AppCompat"

or each kind of AppCompat theme!

Make the first character Uppercase in CSS

There's a property for that:

a.m_title {
    text-transform: capitalize;
}

If your links can contain multiple words and you only want the first letter of the first word to be uppercase, use :first-letter with a different transform instead (although it doesn't really matter). Note that in order for :first-letter to work your a elements need to be block containers (which can be display: block, display: inline-block, or any of a variety of other combinations of one or more properties):

a.m_title {
    display: block;
}

a.m_title:first-letter {
    text-transform: uppercase;
}

How to delete session cookie in Postman?

I think the response of aaron can be enhanced for URL that contains variables:

var sdk = require('postman-collection');      

const testURL=pm.environment.values.substitute(pm.request.url, null, false);

const objURL=new sdk.Url(testURL);

console.log("clearing cookies for: "+testURL);

const jar = pm.cookies.jar();

jar.clear(objURL, function (error) {
  // error - <Error>
  if(error)
  console.log("Error clearing cookies: "+error);
});

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

Change the current directory from a Bash script

Putting the above together, you can make an alias

alias your_cmd=". your_cmd"

if you don't want to write the leading "." each time you want to source your script to the shell environment, or if you simply don't want to remember that must be done for the script to work correctly.

What exactly does big ? notation represent?

First let's understand what big O, big Theta and big Omega are. They are all sets of functions.

Big O is giving upper asymptotic bound, while big Omega is giving a lower bound. Big Theta gives both.

Everything that is ?(f(n)) is also O(f(n)), but not the other way around.
T(n) is said to be in ?(f(n)) if it is both in O(f(n)) and in Omega(f(n)).
In sets terminology, ?(f(n)) is the intersection of O(f(n)) and Omega(f(n))

For example, merge sort worst case is both O(n*log(n)) and Omega(n*log(n)) - and thus is also ?(n*log(n)), but it is also O(n^2), since n^2 is asymptotically "bigger" than it. However, it is not ?(n^2), Since the algorithm is not Omega(n^2).

A bit deeper mathematic explanation

O(n) is asymptotic upper bound. If T(n) is O(f(n)), it means that from a certain n0, there is a constant C such that T(n) <= C * f(n). On the other hand, big-Omega says there is a constant C2 such that T(n) >= C2 * f(n))).

Do not confuse!

Not to be confused with worst, best and average cases analysis: all three (Omega, O, Theta) notation are not related to the best, worst and average cases analysis of algorithms. Each one of these can be applied to each analysis.

We usually use it to analyze complexity of algorithms (like the merge sort example above). When we say "Algorithm A is O(f(n))", what we really mean is "The algorithms complexity under the worst1 case analysis is O(f(n))" - meaning - it scales "similar" (or formally, not worse than) the function f(n).

Why we care for the asymptotic bound of an algorithm?

Well, there are many reasons for it, but I believe the most important of them are:

  1. It is much harder to determine the exact complexity function, thus we "compromise" on the big-O/big-Theta notations, which are informative enough theoretically.
  2. The exact number of ops is also platform dependent. For example, if we have a vector (list) of 16 numbers. How much ops will it take? The answer is: it depends. Some CPUs allow vector additions, while other don't, so the answer varies between different implementations and different machines, which is an undesired property. The big-O notation however is much more constant between machines and implementations.

To demonstrate this issue, have a look at the following graphs: enter image description here

It is clear that f(n) = 2*n is "worse" than f(n) = n. But the difference is not quite as drastic as it is from the other function. We can see that f(n)=logn quickly getting much lower than the other functions, and f(n) = n^2 is quickly getting much higher than the others.
So - because of the reasons above, we "ignore" the constant factors (2* in the graphs example), and take only the big-O notation.

In the above example, f(n)=n, f(n)=2*n will both be in O(n) and in Omega(n) - and thus will also be in Theta(n).
On the other hand - f(n)=logn will be in O(n) (it is "better" than f(n)=n), but will NOT be in Omega(n) - and thus will also NOT be in Theta(n).
Symetrically, f(n)=n^2 will be in Omega(n), but NOT in O(n), and thus - is also NOT Theta(n).


1Usually, though not always. when the analysis class (worst, average and best) is missing, we really mean the worst case.

Converting String To Float in C#

Your thread's locale is set to one in which the decimal mark is "," instead of ".".

Try using this:

float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);

Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.

How to cast an Object to an int

int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
    ArrayList list = null;
    Statement statement = conn.createStatement();
    ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
    while (result.next()) {
        list.add(result.getInt(1));
    }
    statement.close();
    int id[] = new int[list.size()];
    for (int i = 0; i < id.length; i++) {
        try {
            id[i] = ((Integer) list.get(i)).intValue();
        } catch(NullPointerException ne) {
        } catch(ClassCastException ch) {}
    }
    return id;
}
// enter code here

This code shows why ArrayList is important and why we use it. Simply casting int from Object. May be its helpful.

Create a custom callback in JavaScript

My 2 cent. Same but different...

<script>
    dosomething("blaha", function(){
        alert("Yay just like jQuery callbacks!");
    });


    function dosomething(damsg, callback){
        alert(damsg);
        if(typeof callback == "function") 
        callback();
    }
</script>

Java - Including variables within strings?

Since Java 15, you can use a non-static string method called String::formatted(Object... args)

Example:

String foo = "foo";
String bar = "bar";

String str = "First %s, then %s".formatted(foo, bar);     

Output:

"First foo, then bar"

how to configure hibernate config file for sql server

We also need to mention default schema for SQSERVER: dbo

<property name="hibernate.default_schema">dbo</property>

Tested with hibernate 4

HTTPS connection Python

I had some code that was failing with an HTTPConnection (MOVED_PERMANENTLY error), but as soon as I switched to HTTPS it worked perfectly again with no other changes needed. That's a very simple fix!

Space between Column's children in Flutter

The sized box will not help in the case, the phone is in landscape mode.

body: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
      ],
     )

Android Studio AVD - Emulator: Process finished with exit code 1

My issue resolved

  • May be you do not have enough space to create this virtual device (like in my case). if this happens, try to create space enough for this Virtual device.

OR

  • Uninstall and re-install can solve this issue.

OR

  • Restarting Android Studio can solve.

case-insensitive matching in xpath?

One possible PHP solution:

// load XML to SimpleXML
$x = simplexml_load_string($xmlstr);

// index it by title once
$index = array();
foreach ($x->CD as &$cd) {
  $title = strtolower((string)$cd['title']); 
  if (!array_key_exists($title, $index)) $index[$title] = array();
  $index[$title][] = &$cd;
}

// query the index 
$result = $index[strtolower("EMPIRE BURLESQUE")];

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

Java ArrayList clear() function

ArrayList.clear(From Java Doc):

Removes all of the elements from this list. The list will be empty after this call returns

How to set a cell to NaN in a pandas dataframe

Most replies here need to import numpy as np

There is a built-in solution into pandas itself: pd.NA, to use like this:

df.replace('N/A', pd.NA)

How to pass macro definition from "make" command line arguments (-D) to C source code?

Find the C file and Makefile implementation in below to meet your requirements

foo.c

 main ()
    {
        int a = MAKE_DEFINE;
        printf ("MAKE_DEFINE value:%d\n", a);
    }

Makefile

all:
    gcc -DMAKE_DEFINE=11 foo.c

Resize image with javascript canvas (smoothly)

You can use down-stepping to achieve better results. Most browsers seem to use linear interpolation rather than bi-cubic when resizing images.

(Update There has been added a quality property to the specs, imageSmoothingQuality which is currently available in Chrome only.)

Unless one chooses no smoothing or nearest neighbor the browser will always interpolate the image after down-scaling it as this function as a low-pass filter to avoid aliasing.

Bi-linear uses 2x2 pixels to do the interpolation while bi-cubic uses 4x4 so by doing it in steps you can get close to bi-cubic result while using bi-linear interpolation as seen in the resulting images.

_x000D_
_x000D_
var canvas = document.getElementById("canvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image();_x000D_
_x000D_
img.onload = function () {_x000D_
_x000D_
    // set size proportional to image_x000D_
    canvas.height = canvas.width * (img.height / img.width);_x000D_
_x000D_
    // step 1 - resize to 50%_x000D_
    var oc = document.createElement('canvas'),_x000D_
        octx = oc.getContext('2d');_x000D_
_x000D_
    oc.width = img.width * 0.5;_x000D_
    oc.height = img.height * 0.5;_x000D_
    octx.drawImage(img, 0, 0, oc.width, oc.height);_x000D_
_x000D_
    // step 2_x000D_
    octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);_x000D_
_x000D_
    // step 3, resize to final size_x000D_
    ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,_x000D_
    0, 0, canvas.width, canvas.height);_x000D_
}_x000D_
img.src = "//i.imgur.com/SHo6Fub.jpg";
_x000D_
<img src="//i.imgur.com/SHo6Fub.jpg" width="300" height="234">_x000D_
<canvas id="canvas" width=300></canvas>
_x000D_
_x000D_
_x000D_

Depending on how drastic your resize is you can might skip step 2 if the difference is less.

In the demo you can see the new result is now much similar to the image element.

How to ignore the first line of data when processing CSV data?

Python 3.X

Handles UTF8 BOM + HEADER

It was quite frustrating that the csv module could not easily get the header, there is also a bug with the UTF-8 BOM (first char in file). This works for me using only the csv module:

import csv

def read_csv(self, csv_path, delimiter):
    with open(csv_path, newline='', encoding='utf-8') as f:
        # https://bugs.python.org/issue7185
        # Remove UTF8 BOM.
        txt = f.read()[1:]

    # Remove header line.
    header = txt.splitlines()[:1]
    lines = txt.splitlines()[1:]

    # Convert to list.
    csv_rows = list(csv.reader(lines, delimiter=delimiter))

    for row in csv_rows:
        value = row[INDEX_HERE]

What static analysis tools are available for C#?

Code violation detection Tools:

  • Fxcop, excellent tool by Microsoft. Check compliance with .net framework guidelines.

    Edit October 2010: No longer available as a standalone download. It is now included in the Windows SDK and after installation can be found in Program Files\Microsoft SDKs\Windows\ [v7.1] \Bin\FXCop\FxCopSetup.exe

    Edit February 2018: This functionality has now been integrated into Visual Studio 2012 and later as Code Analysis

  • Clocksharp, based on code source analysis (to C# 2.0)

  • Mono.Gendarme, similar to Fxcop but with an opensource licence (based on Mono.Cecil)

  • Smokey, similar to Fxcop and Gendarme, based on Mono.Cecil. No longer on development, the main developer works with Gendarme team now.

  • Coverity Preventâ„¢ for C#, commercial product

  • PRQA QA·C#, commercial product

  • PVS-Studio, commercial product

  • CAT.NET, visual studio addin that helps identification of security flaws Edit November 2019: Link is dead.

  • CodeIt.Right

  • Spec#

  • Pex

  • SonarQube, FOSS & Commercial options to support writing cleaner and safer code.

Quality Metric Tools:

  • NDepend, great visual tool. Useful for code metrics, rules, diff, coupling and dependency studies.
  • Nitriq, free, can easily write your own metrics/constraints, nice visualizations. Edit February 2018: download links now dead. Edit June 17, 2019: Links not dead.
  • RSM Squared, based on code source analysis
  • C# Metrics, using a full parse of C#
  • SourceMonitor, an old tool that occasionally gets updates
  • Code Metrics, a Reflector add-in
  • Vil, old tool that doesn't support .NET 2.0. Edit January 2018: Link now dead

Checking Style Tools:

  • StyleCop, Microsoft tool ( run from inside of Visual Studio or integrated into an MSBuild project). Also available as an extension for Visual Studio 2015 and C#6.0
  • Agent Smith, code style validation plugin for ReSharper

Duplication Detection:

  • Simian, based on source code. Works with plenty languages.
  • CloneDR, detects parameterized clones only on language boundaries (also handles many languages other than C#)
  • Clone Detective a Visual Studio plugin. (It uses ConQAT internally)
  • Atomiq, based on source code, plenty of languages, cool "wheel" visualization

General Refactoring tools

  • ReSharper - Majorly cool C# code analysis and refactoring features

Put a Delay in Javascript

Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.

function delay(t){

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);

//This will call the page named delay.php and the response will be sent to a division with ID as "response"

xmlhttp.send();

document.getElementById("response").innerHTML=xmlhttp.responseText;

}

http://www.hklabs.org/articles/put-delay-in-javascript

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:

TimeStamp ts = TimeStamp.FromTicks(value.ToUniversalTime().Ticks);

Since you named a variable epoch, do you want the Unix time equivalent of your date?

DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
long epoch = (long)Math.Floor((value.ToUniversalTime() - unixStart).TotalSeconds);

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Fast way to get the min/max values among properties of object

// Sorted
let Sorted = Object.entries({ "a":4, "b":0.5 , "c":0.35, "d":5 }).sort((prev, next) => prev[1] - next[1])
>> [ [ 'c', 0.35 ], [ 'b', 0.5 ], [ 'a', 4 ], [ 'd', 5 ] ]


//Min:
Sorted.shift()
>> [ 'c', 0.35 ]

// Max:
Sorted.pop()
>> [ 'd', 5 ]

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)

    In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:

    • It provides a backup of your files.
    • It gives you a visual interface for navigating your repos.
    • It gives other people a way to navigate your repos.
    • It makes repo collaboration easy (e.g., multiple people contributing to the same project).
    • It provides a lightweight issue tracking system.
  4. How does Git compare to a backup system such as Time Machine?

    Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, this is a manual process.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • Git employs a powerful branching system that allows you to work on multiple, independent lines of development simultaneously and then merge those branches together as needed.
    • Git allows you to view the line-by-line differences between different versions of your files, which makes troubleshooting easier.
    • Git forces you to describe each of your commits, which makes it significantly easier to track down a specific previous version of a given file (and potentially revert to that previous version).
    • If you ever need help with your code, having it tracked by Git and hosted on GitHub makes it much easier for someone else to look at your code.

For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.

MySQL table is marked as crashed and last (automatic?) repair failed

If it gives you permission denial while moving to /var/lib/mysql then use the following solution

$ cd /var/lib/
$ sudo -u mysql myisamchk -r -v -f mysql/<DB_NAME>/<TABLE_NAME>

Installation error: INSTALL_FAILED_OLDER_SDK

Make sure to check your build.gradle and that it doesn't use a newer SDK version than what is installed on your AVD. That's only if you use Android Studio though.

Best way to concatenate List of String objects?

Use one of the the StringUtils.join methods in Apache Commons Lang.

import org.apache.commons.lang3.StringUtils;

String result = StringUtils.join(list, ", ");

If you are fortunate enough to be using Java 8, then it's even easier...just use String.join

String result = String.join(", ", list);

Change color of Button when Mouse is over

As others already said, there seems to be no good solution to do that easily.
But to keep your code clean I suggest creating a seperate class that hides the ugly XAML.

How to use after we created the ButtonEx-class:

<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfEx="clr-namespace:WpfExtensions"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <wpfEx:ButtonEx HoverBackground="Red"></wpfEx:ButtonEx>
    </Grid>
</Window>

ButtonEx.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WpfExtensions
{
    /// <summary>
    /// Standard button with extensions
    /// </summary>
    public partial class ButtonEx : Button
    {
        readonly static Brush DefaultHoverBackgroundValue = new BrushConverter().ConvertFromString("#FFBEE6FD") as Brush;

        public ButtonEx()
        {
            InitializeComponent();
        }

        public Brush HoverBackground
        {
            get { return (Brush)GetValue(HoverBackgroundProperty); }
            set { SetValue(HoverBackgroundProperty, value); }
        }
        public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.Register(
          "HoverBackground", typeof(Brush), typeof(ButtonEx), new PropertyMetadata(DefaultHoverBackgroundValue));
    }
}

ButtonEx.xaml
Note: This contains all the original XAML from System.Windows.Controls.Button

<Button x:Class="WpfExtensions.ButtonEx"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
            x:Name="buttonExtension">
    <Button.Resources>
        <Style x:Key="FocusVisual">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="10" StrokeDashArray="1 2"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
        <SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
        <SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
        <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
        <SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
        <SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
        <SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
        <SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
        <SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
    </Button.Resources>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
            <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Padding" Value="1"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                            <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsDefaulted" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{Binding Path=HoverBackground, ElementName=buttonExtension}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                            </Trigger>
                            <Trigger Property="IsPressed" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                                <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

Tip: You can add an UserControl with name "ButtonEx" to your project in VS Studio and then copy paste the stuff above in.

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

I hope (not exactly verified) that newer java brought nio package and Path. Hopefully it have it fixed: String s="C:\\some\\ile.txt"; System.out.println(new File(s).toPath().toUri());

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

add the maven dependencies:

<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>1.1.2</version>
  <scope>compile</scope>
</dependency>

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'))

Why is "npm install" really slow?

I am using Linux and have nvm and working with more than 7 version of node As of my experience I experienced the same situation with my latest project (actually not hours but minutes as I can't wait hours because of hourly project :))

Disclaimer: don't try below option until you know how cache clean works

npm cache clean --force

and then all working fine for me so it's looks like sometimes npm's cache gets confused with different versions of Node.

Official documentation of Npm cache can be found here

Purpose of returning by const value?

In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that + returned a non-const value, and you could write:

(a + b).expensive();

In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.

In summary, there is a rationale for this practice, but it is essentially obsolete.

Send mail via Gmail with PowerShell V2's Send-MailMessage

I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From [email protected]
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

Get Enum from Description attribute

public static class EnumEx
{
    public static T GetValueFromDescription<T>(string description) where T : Enum
    {
        foreach(var field in typeof(T).GetFields())
        {
            if (Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException("Not found.", nameof(description));
        // Or return default(T);
    }
}

Usage:

var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

removing new line character from incoming stream using sed

To remove newlines, use tr:

tr -d '\n'

If you want to replace each newline with a single space:

tr '\n' ' '

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$\!ba;s/\n/ /g'  # Suitable for csh only!!

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

Android Studio - How to Change Android SDK Path

From the quick start window, choose Configure, then choose Project Defaults, and then choose Project Structure. Then on the left under Platform Settings choose SDKs. Then to the right of that choose the current android platform, mine was Android 4.2.2 Platform, and delete it using the red minus button at the top, then add a new android platform using the green plus button at the top and point it to your current SDK folder and that is it.

Get json value from response

Normally you could access it by its property name:

var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);

or perhaps you've got a JSON string that needs to be turned into an object:

var foo = jQuery.parseJSON(data);
alert(foo.id);

http://api.jquery.com/jQuery.parseJSON/

How to Initialize char array from a string

Another option is to use sprintf.

For example,

char buffer[50];
sprintf( buffer, "My String" );

Good luck.

What does "exec sp_reset_connection" mean in Sql Server Profiler?

It's an indication that connection pooling is being used (which is a good thing).

In Java, what does NaN mean?

Minimal runnable example

The first thing that you have to know, is that the concept of NaN is implemented directly on the CPU hardware.

All major modern CPUs seem to follow IEEE 754 which specifies floating point formats, and NaNs, which are just special float values, are part of that standard.

Therefore, the concept will be the very similar across any language, including Java which just emits floating point code directly to the CPU.

Before proceeding, you might want to first read up the following answers I've written:

Now for some Java action. Most of the functions of interest that are not in the core language live inside java.lang.Float.

Nan.java

import java.lang.Float;
import java.lang.Math;

public class Nan {
    public static void main(String[] args) {
        // Generate some NaNs.
        float nan            = Float.NaN;
        float zero_div_zero  = 0.0f / 0.0f;
        float sqrt_negative  = (float)Math.sqrt(-1.0);
        float log_negative   = (float)Math.log(-1.0);
        float inf_minus_inf  = Float.POSITIVE_INFINITY - Float.POSITIVE_INFINITY;
        float inf_times_zero = Float.POSITIVE_INFINITY * 0.0f;
        float quiet_nan1     = Float.intBitsToFloat(0x7fc00001);
        float quiet_nan2     = Float.intBitsToFloat(0x7fc00002);
        float signaling_nan1 = Float.intBitsToFloat(0x7fa00001);
        float signaling_nan2 = Float.intBitsToFloat(0x7fa00002);
        float nan_minus      = -nan;

        // Generate some infinities.
        float positive_inf   = Float.POSITIVE_INFINITY;
        float negative_inf   = Float.NEGATIVE_INFINITY;
        float one_div_zero   = 1.0f / 0.0f;
        float log_zero       = (float)Math.log(0.0);

        // Double check that they are actually NaNs.
        assert  Float.isNaN(nan);
        assert  Float.isNaN(zero_div_zero);
        assert  Float.isNaN(sqrt_negative);
        assert  Float.isNaN(inf_minus_inf);
        assert  Float.isNaN(inf_times_zero);
        assert  Float.isNaN(quiet_nan1);
        assert  Float.isNaN(quiet_nan2);
        assert  Float.isNaN(signaling_nan1);
        assert  Float.isNaN(signaling_nan2);
        assert  Float.isNaN(nan_minus);
        assert  Float.isNaN(log_negative);

        // Double check that they are infinities.
        assert  Float.isInfinite(positive_inf);
        assert  Float.isInfinite(negative_inf);
        assert !Float.isNaN(positive_inf);
        assert !Float.isNaN(negative_inf);
        assert one_div_zero == positive_inf;
        assert log_zero == negative_inf;
            // Double check infinities.

        // See what they look like.
        System.out.printf("nan            0x%08x %f\n", Float.floatToRawIntBits(nan           ), nan           );
        System.out.printf("zero_div_zero  0x%08x %f\n", Float.floatToRawIntBits(zero_div_zero ), zero_div_zero );
        System.out.printf("sqrt_negative  0x%08x %f\n", Float.floatToRawIntBits(sqrt_negative ), sqrt_negative );
        System.out.printf("log_negative   0x%08x %f\n", Float.floatToRawIntBits(log_negative  ), log_negative  );
        System.out.printf("inf_minus_inf  0x%08x %f\n", Float.floatToRawIntBits(inf_minus_inf ), inf_minus_inf );
        System.out.printf("inf_times_zero 0x%08x %f\n", Float.floatToRawIntBits(inf_times_zero), inf_times_zero);
        System.out.printf("quiet_nan1     0x%08x %f\n", Float.floatToRawIntBits(quiet_nan1    ), quiet_nan1    );
        System.out.printf("quiet_nan2     0x%08x %f\n", Float.floatToRawIntBits(quiet_nan2    ), quiet_nan2    );
        System.out.printf("signaling_nan1 0x%08x %f\n", Float.floatToRawIntBits(signaling_nan1), signaling_nan1);
        System.out.printf("signaling_nan2 0x%08x %f\n", Float.floatToRawIntBits(signaling_nan2), signaling_nan2);
        System.out.printf("nan_minus      0x%08x %f\n", Float.floatToRawIntBits(nan_minus     ), nan_minus     );
        System.out.printf("positive_inf   0x%08x %f\n", Float.floatToRawIntBits(positive_inf  ), positive_inf  );
        System.out.printf("negative_inf   0x%08x %f\n", Float.floatToRawIntBits(negative_inf  ), negative_inf  );
        System.out.printf("one_div_zero   0x%08x %f\n", Float.floatToRawIntBits(one_div_zero  ), one_div_zero  );
        System.out.printf("log_zero       0x%08x %f\n", Float.floatToRawIntBits(log_zero      ), log_zero      );

        // NaN comparisons always fail.
        // Therefore, all tests that we will do afterwards will be just isNaN.
        assert !(1.0f < nan);
        assert !(1.0f == nan);
        assert !(1.0f > nan);
        assert !(nan == nan);

        // NaN propagate through most operations.
        assert Float.isNaN(nan + 1.0f);
        assert Float.isNaN(1.0f + nan);
        assert Float.isNaN(nan + nan);
        assert Float.isNaN(nan / 1.0f);
        assert Float.isNaN(1.0f / nan);
        assert Float.isNaN((float)Math.sqrt((double)nan));
    }
}

GitHub upstream.

Run with:

javac Nan.java && java -ea Nan

Output:

nan            0x7fc00000 NaN
zero_div_zero  0x7fc00000 NaN
sqrt_negative  0xffc00000 NaN
log_negative   0xffc00000 NaN
inf_minus_inf  0x7fc00000 NaN
inf_times_zero 0x7fc00000 NaN
quiet_nan1     0x7fc00001 NaN
quiet_nan2     0x7fc00002 NaN
signaling_nan1 0x7fa00001 NaN
signaling_nan2 0x7fa00002 NaN
nan_minus      0xffc00000 NaN
positive_inf   0x7f800000 Infinity
negative_inf   0xff800000 -Infinity
one_div_zero   0x7f800000 Infinity
log_zero       0xff800000 -Infinity

So from this we learn a few things:

  • weird floating operations that don't have any sensible result give NaN:

    • 0.0f / 0.0f
    • sqrt(-1.0f)
    • log(-1.0f)

    generate a NaN.

    In C, it is actually possible to request signals to be raised on such operations with feenableexcept to detect them, but I don't think it is exposed in Java: Why does integer division by zero 1/0 give error but floating point 1/0.0 returns "Inf"?

  • weird operations that are on the limit of either plus or minus infinity however do give +- infinity instead of NaN

    • 1.0f / 0.0f
    • log(0.0f)

    0.0 almost falls in this category, but likely the problem is that it could either go to plus or minus infinity, so it was left as NaN.

  • if NaN is the input of a floating operation, the output also tends to be NaN

  • there are several possible values for NaN 0x7fc00000, 0x7fc00001, 0x7fc00002, although x86_64 seems to generate only 0x7fc00000.

  • NaN and infinity have similar binary representation.

    Let's break down a few of them:

    nan          = 0x7fc00000 = 0 11111111 10000000000000000000000
    positive_inf = 0x7f800000 = 0 11111111 00000000000000000000000
    negative_inf = 0xff800000 = 1 11111111 00000000000000000000000
                                | |        |
                                | |        mantissa
                                | exponent
                                |
                                sign
    

    From this we confirm what IEEE754 specifies:

    • both NaN and infinities have exponent == 255 (all ones)
    • infinities have mantissa == 0. There are therefore only two possible infinities: + and -, differentiated by the sign bit
    • NaN has mantissa != 0. There are therefore several possibilities, except for mantissa == 0 which is infinity
  • NaNs can be either positive or negative (top bit), although it this has no effect on normal operations

Tested in Ubuntu 18.10 amd64, OpenJDK 1.8.0_191.

Clear back stack using fragments

To make an answer for @Warpzit's comment and make it easier for others to find.

Use:

fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Python: Assign print output to a variable

To answer the question more generaly how to redirect standard output to a variable ?

do the following :

from io import StringIO
import sys

result = StringIO()
sys.stdout = result
result_string = result.getvalue()

If you need to do that only in some function do the following :

old_stdout = sys.stdout  

# your function containing the previous lines
my_function()

sys.stdout = old_stdout

Show row number in row header of a DataGridView

row.HeaderCell.Value = row.Index + 1;

when applied on datagridview with a very large number of rows creates a memory leak and eventually will result in an out of memory issue. Any ideas how to reclaim the memory?

Here is sample code to apply to an empty grid with some columns. it simply adds rows and numbers the index. Repeat button click a few times.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        dataGridView1.SuspendLayout();
        for (int i = 1; i < 10000; i++)
        {
            dataGridView1.Rows.Add(i);                
        }
        dataGridView1.ResumeLayout();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
            row.HeaderCell.Value = (row.Index + 1).ToString();
    }
}

delete_all vs destroy_all?

delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.

If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.

Android: ProgressDialog.show() crashes with getApplicationContext

I am using Android version 2.1 with API Level 7. I faced with this (or similar) problem and solved by using this:

Dialog dialog = new Dialog(this);

instead of this:

Dialog dialog = new Dialog(getApplicationContext());

Hope this helps :)

Using subprocess to run Python script on Windows

It looks like windows tries to run the script using its own EXE framework rather than call it like

python /the/script.py

Try,

subprocess.Popen(["python", "/the/script.py"])

Edit: "python" would need to be on your path.

Asynchronous file upload (AJAX file upload) using jsp and javascript

The two common approaches are to submit the form to an invisible iframe, or to use a Flash control such as YUI Uploader. You could also use Java instead of Flash, but this has a narrower install base.

(Shame about the layout table in the first example)

Drop all data in a pandas dataframe

This code make clean dataframe:

df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
#clean
df = pd.DataFrame()

NSOperation vs Grand Central Dispatch

In line with my answer to a related question, I'm going to disagree with BJ and suggest you first look at GCD over NSOperation / NSOperationQueue, unless the latter provides something you need that GCD doesn't.

Before GCD, I used a lot of NSOperations / NSOperationQueues within my applications for managing concurrency. However, since I started using GCD on a regular basis, I've almost entirely replaced NSOperations and NSOperationQueues with blocks and dispatch queues. This has come from how I've used both technologies in practice, and from the profiling I've performed on them.

First, there is a nontrivial amount of overhead when using NSOperations and NSOperationQueues. These are Cocoa objects, and they need to be allocated and deallocated. In an iOS application that I wrote which renders a 3-D scene at 60 FPS, I was using NSOperations to encapsulate each rendered frame. When I profiled this, the creation and teardown of these NSOperations was accounting for a significant portion of the CPU cycles in the running application, and was slowing things down. I replaced these with simple blocks and a GCD serial queue, and that overhead disappeared, leading to noticeably better rendering performance. This wasn't the only place where I noticed overhead from using NSOperations, and I've seen this on both Mac and iOS.

Second, there's an elegance to block-based dispatch code that is hard to match when using NSOperations. It's so incredibly convenient to wrap a few lines of code in a block and dispatch it to be performed on a serial or concurrent queue, where creating a custom NSOperation or NSInvocationOperation to do this requires a lot more supporting code. I know that you can use an NSBlockOperation, but you might as well be dispatching something to GCD then. Wrapping this code in blocks inline with related processing in your application leads in my opinion to better code organization than having separate methods or custom NSOperations which encapsulate these tasks.

NSOperations and NSOperationQueues still have very good uses. GCD has no real concept of dependencies, where NSOperationQueues can set up pretty complex dependency graphs. I use NSOperationQueues for this in a handful of cases.

Overall, while I usually advocate for using the highest level of abstraction that accomplishes the task, this is one case where I argue for the lower-level API of GCD. Among the iOS and Mac developers I've talked with about this, the vast majority choose to use GCD over NSOperations unless they are targeting OS versions without support for it (those before iOS 4.0 and Snow Leopard).

Best way to store a key=>value array in JavaScript?

You can use Map.

  • A new data structure introduced in JavaScript ES6.
  • Alternative to JavaScript Object for storing key/value pairs.
  • Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);

// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }

Get value of the Map using key

console.log(map.get('name')); // John 
console.log(map.get('id')); // 11

Get size of the Map

console.log(map.size); // 2

Check key exists in Map

console.log(map.has('name')); // true
console.log(map.has('age')); // false

Get keys

console.log(map.keys()); // MapIterator { 'name', 'id' }

Get values

console.log(map.values()); // MapIterator { 'John', 11 }

Get elements of the Map

for (let element of map) {
  console.log(element);
}

// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]

Print key value pairs

for (let [key, value] of map) {
  console.log(key + " - " + value);
}

// Output: 
// name - John
// id - 11

Print only keys of the Map

for (let key of map.keys()) {
  console.log(key);
}

// Output:
// name
// id

Print only values of the Map

for (let value of map.values()) {
  console.log(value);
}

// Output:
// John
// 11

How to convert a number to string and vice versa in C++

How to convert a number to a string in C++03

  1. Do not use the itoa or itof functions because they are non-standard and therefore not portable.
  2. Use string streams

     #include <sstream>  //include this to use string streams
     #include <string> 
    
    int main()
    {    
        int number = 1234;
    
        std::ostringstream ostr; //output string stream
        ostr << number; //use the string stream just like cout,
        //except the stream prints not to stdout but to a string.
    
        std::string theNumberString = ostr.str(); //the str() function of the stream 
        //returns the string.
    
        //now  theNumberString is "1234"  
    }
    

    Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with cout

    std::ostringstream ostr;
    float f = 1.2;
    int i = 3;
    ostr << f << " + " i << " = " << f + i;   
    std::string s = ostr.str();
    //now s is "1.2 + 3 = 4.2" 
    

    You can use stream manipulators, such as std::endl, std::hex and functions std::setw(), std::setprecision() etc. with string streams in exactly the same manner as with cout

    Do not confuse std::ostringstream with std::ostrstream. The latter is deprecated

  3. Use boost lexical cast. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. To download and install boost and its documentation go here. Although boost isn't in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.

    Lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.

    #include <boost/lexical_cast.hpp>
    #include <string>
    
    int main()
    {
       float f = 1.2;
       int i = 42;
       std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
       std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
    }
    

How to convert a string to a number in C++03

  1. The most lightweight option, inherited from C, is the functions atoi (for integers (alphabetical to integer)) and atof (for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.

    #include <cstdlib> //the standard C library header
    #include <string>
    int main()
    {
        std::string si = "12";
        std::string sf = "1.2";
        int i = atoi(si.c_str()); //the c_str() function "converts" 
        double f = atof(sf.c_str()); //std::string to const char*
    }
    
  2. Use string streams (this time input string stream, istringstream). Again, istringstream is used just like cin. Again, do not confuse istringstream with istrstream. The latter is deprecated.

    #include <sstream>
    #include <string>
    int main()
    {
       std::string inputString = "1234 12.3 44";
       std::istringstream istr(inputString);
       int i1, i2;
       float f;
       istr >> i1 >> f >> i2;
       //i1 is 1234, f is 12.3, i2 is 44  
    }
    
  3. Use boost lexical cast.

    #include <boost/lexical_cast.hpp>
    #include <string>
    
    int main()
    {
       std::string sf = "42.2"; 
       std::string si = "42";
       float f = boost::lexical_cast<float>(sf); //f is 42.2
       int i = boost::lexical_cast<int>(si);  //i is 42
    }       
    

    In case of a bad input, lexical_cast throws an exception of type boost::bad_lexical_cast

Hidden property of a button in HTML

It also works without jQuery if you do the following changes:

  1. Add type="button" to the edit button in order not to trigger submission of the form.

  2. Change the name of your function from change() to anything else.

  3. Don't use hidden="hidden", use CSS instead: style="display: none;".

The following code works for me:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">

<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
    <img src="dba_images/textfield_key.png" alt=""/>
    Edit
</button>

<button type="submit" class="positive" name="save" id="save" style="display:none;">
    <img src="dba_images/apply2.png" alt=""/>
    Save
</button>

<button class="regular" name="change" id="change" style="display:none;">
    <img src="dba_images/textfield_key.png" alt=""/>
    change
</button>

    <button class="negative" name="cancel" id="cancel" style="display:none;">
        <img src="dba_images/cross.png" alt=""/>
        Cancel
    </button>
</div>
</form>
</body>
</html>

Bootstrap 3 with remote Modal

As much as I dislike modifying Bootstrap code (makes upgrading more difficult), you can simply add ".find('.modal-body') to the load statement in modal.js as follows:

// original code
// if (this.options.remote) this.$element.load(this.options.remote)

// modified code
if (this.options.remote) this.$element.find('.modal-body').load(this.options.remote)

HTML: Select multiple as dropdown

A similar question was asked here

If you're able to add an external library to your project, you can try Chosen

Here's a sample:

_x000D_
_x000D_
$(".chosen-select").chosen({_x000D_
  no_results_text: "Oops, nothing found!"_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.jquery.min.js"></script>_x000D_
<link href="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.min.css" rel="stylesheet"/>_x000D_
_x000D_
<form action="http://httpbin.org/post" method="post">_x000D_
  <select data-placeholder="Begin typing a name to filter..." multiple class="chosen-select" name="test">_x000D_
    <option value=""></option>_x000D_
    <option>American Black Bear</option>_x000D_
    <option>Asiatic Black Bear</option>_x000D_
    <option>Brown Bear</option>_x000D_
    <option>Giant Panda</option>_x000D_
    <option>Sloth Bear</option>_x000D_
    <option>Sun Bear</option>_x000D_
    <option>Polar Bear</option>_x000D_
    <option>Spectacled Bear</option>_x000D_
  </select>_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

One thing I've run into, you have to include JQuery BEFORE you include Chosen or you'll get errors.

How to find the Windows version from the PowerShell command line

$OSVersion = [Version](Get-ItemProperty -Path "$($Env:Windir)\System32\hal.dll" -ErrorAction SilentlyContinue).VersionInfo.FileVersion.Split()[0]

On Windows 10 returns: 10.0.10586.420

You can then use the variable to access properties for granular comparison

$OSVersion.Major equals 10
$OSVersion.Minor equals 0
$OSVersion.Build equals 10586
$OSVersion.Revision equals 420

Additionally, you can compare operating system versions using the following

If ([Version]$OSVersion -ge [Version]"6.1")
   {
       #Do Something
   }

What is the equivalent to getLastInsertId() in Cakephp?

each time you perform an insert operation on any model, cake internally fetchesthe last insert Id and Sets to Model->id attribute.

so one can access it directly by $Model->id;, no need to query again for lastInsertId.

Java creating .jar file

Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.

How to do a batch insert in MySQL

Most of the time, you are not working in a MySQL client and you should batch inserts together using the appropriate API.

E.g. in JDBC:

connection con.setAutoCommit(false); 
PreparedStatement prepStmt = con.prepareStatement("UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?");
prepStmt.setString(1,mgrnum1);                 
prepStmt.setString(2,deptnum1);
prepStmt.addBatch();

prepStmt.setString(1,mgrnum2);                        
prepStmt.setString(2,deptnum2);
prepStmt.addBatch();

int [] numUpdates=prepStmt.executeBatch();

http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/tjvbtupd.htm

spark submit add multiple jars in classpath

if you are using properties file you can add following line there:

spark.jars=jars/your_jar1.jar,...

assuming that

<your root from where you run spark-submit>
  |
  |-jars
      |-your_jar1.jar

Using NULL in C++?

I never use NULL in my C or C++ code. 0 works just fine, as does if (ptrname). Any competent C or C++ programmer should know what those do.

Parsing huge logfiles in Node.js - read in line-by-line

node-byline uses streams, so i would prefer that one for your huge files.

for your date-conversions i would use moment.js.

for maximising your throughput you could think about using a software-cluster. there are some nice-modules which wrap the node-native cluster-module quite well. i like cluster-master from isaacs. e.g. you could create a cluster of x workers which all compute a file.

for benchmarking splits vs regexes use benchmark.js. i havent tested it until now. benchmark.js is available as a node-module

Xampp MySQL not starting - "Attempting to start MySQL service..."

  1. In the cmd type: services.msc Find MySql and change properties to the disabled.
  2. In the control panel of Xampp uninstall MySql by the checkbox on the left side, and install again by the click in the same checkbox.

How to create a TextArea in Android

<EditText
    android:id="@+id/comments_textbox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="comments"
    android:inputType="textMultiLine"
    android:longClickable="false" />

use it to create multi line text box like textArea in Html

Count specific character occurrences in a string

Thanks, @guffa. The ability to do it in one line, or even within a longer statement in .NET is very handy. This VB.NET example counts the number of LineFeed characters:

Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)

j returns the number of LineFeeds in MyString.

How do I remove the first characters of a specific column in a table?

The Complete thing

DECLARE @v varchar(10)

SET @v='#temp'

select STUFF(@v, 1, 1, '')
WHERE LEFT(@v,1)='#'

Regular expression to match balanced parentheses

I didn't use regex since it is difficult to deal with nested code. So this snippet should be able to allow you to grab sections of code with balanced brackets:

def extract_code(data):
    """ returns an array of code snippets from a string (data)"""
    start_pos = None
    end_pos = None
    count_open = 0
    count_close = 0
    code_snippets = []
    for i,v in enumerate(data):
        if v =='{':
            count_open+=1
            if not start_pos:
                start_pos= i
        if v=='}':
            count_close +=1
            if count_open == count_close and not end_pos:
                end_pos = i+1
        if start_pos and end_pos:
            code_snippets.append((start_pos,end_pos))
            start_pos = None
            end_pos = None

    return code_snippets

I used this to extract code snippets from a text file.

How do I 'foreach' through a two-dimensional array?

string[][] languages = new string[2][];
            languages[0] = new string[2];
            languages[1] = new string[3];
// inserting data into double dimensional arrays.
            for (int i = 0; i < 2; i++)
            {
                languages[0][i] = "Jagged"+i.ToString();
            }
            for (int j = 0; j < 3; j++)
            {
                languages[1][j] = "Jag"+j.ToString();
            }

// doing foreach through 2 dimensional arrays.
foreach (string[] s in languages)
            {
                foreach (string a in s)
                {
                    Console.WriteLine(a);
                }
            }

Easiest way to ignore blank lines when reading a file in Python

If you want you can just put what you had in a list comprehension:

names_list = [line for line in open("names.txt", "r").read().splitlines() if line]

or

all_lines = open("names.txt", "r").read().splitlines()
names_list = [name for name in all_lines if name]

splitlines() has already removed the line endings.

I don't think those are as clear as just looping explicitly though:

names_list = []
with open('names.txt', 'r') as _:
    for line in _:
        line = line.strip()
        if line:
            names_list.append(line)

Edit:

Although, filter looks quite readable and concise:

names_list = filter(None, open("names.txt", "r").read().splitlines())

How to fix curl: (60) SSL certificate: Invalid certificate chain

After updating to OS X 10.9.2, I started having invalid SSL certificate issues with Homebrew, Textmate, RVM, and Github.

When I initiate a brew update, I was getting the following error:

fatal: unable to access 'https://github.com/Homebrew/homebrew/': SSL certificate problem: Invalid certificate chain
Error: Failure while executing: git pull -q origin refs/heads/master:refs/remotes/origin/master

I was able to alleviate some of the issue by just disabling the SSL verification in Git. From the console (a.k.a. shell or terminal):

git config --global http.sslVerify false

I am leary to recommend this because it defeats the purpose of SSL, but it is the only advice I've found that works in a pinch.

I tried rvm osx-ssl-certs update all which stated Already are up to date.

In Safari, I visited https://github.com and attempted to set the certificate manually, but Safari did not present the options to trust the certificate.

Ultimately, I had to Reset Safari (Safari->Reset Safari... menu). Then afterward visit github.com and select the certificate, and "Always trust" This feels wrong and deletes the history and stored passwords, but it resolved my SSL verification issues. A bittersweet victory.

How can you integrate a custom file browser/uploader with CKEditor?

I just went through the learning process myself. I figured it out, but I agree the documentation is written in a way that was sorta intimidating to me. The big "aha" moment for me was understanding that for browsing, all CKeditor does is open a new window and provide a few parameters in the url. It allows you to add additional parameters but be advised you will need to use encodeURIComponent() on your values.

I call the browser and the uploader with

CKEDITOR.replace( 'body',  
{  
    filebrowserBrowseUrl: 'browse.php?type=Images&dir=' +  
        encodeURIComponent('content/images'),  
    filebrowserUploadUrl: 'upload.php?type=Files&dir=' +  
        encodeURIComponent('content/images')  
}

For the browser, in the open window (browse.php) you use php & js to supply a list of choices and then upon your supplied onclick handler, you call a CKeditor function with two arguments, the url/path to the selected image and CKEditorFuncNum supplied by CKeditor in the url:

function myOnclickHandler(){  
//..    
    window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, pathToImage);  
    window.close();
}       

Simarly, the uploader simply calls the url you supply, e.g., upload.php, and again supplies $_GET['CKEditorFuncNum']. The target is an iframe so, after you save the file from $_FILES you pass your feedback to CKeditor as thus:

$funcNum = $_GET['CKEditorFuncNum'];  
exit("<script>window.parent.CKEDITOR.tools.callFunction($funcNum, '$filePath', '$errorMessage');</script>");  

Below is a simple to understand custom browser script. While it does not allow users to navigate around in the server, it does allow you to indicate which directory to pull image files from when calling the browser.

It's all rather basic coding so it should work in all relatively modern browsers.

CKeditor merely opens a new window with the url provided

/*          
    in CKeditor **use encodeURIComponent()** to add dir param to the filebrowserBrowseUrl property

    Replace content/images with directory where your images are housed.
*/          
        CKEDITOR.replace( 'editor1', {  
            filebrowserBrowseUrl: '**browse.php**?type=Images&dir=' + encodeURIComponent('content/images'),  
            filebrowserUploadUrl: 'upload.php?type=Files&dir=' + encodeURIComponent('content/images') 
        });   

// ========= complete code below for browse.php

<?php  
header("Content-Type: text/html; charset=utf-8\n");  
header("Cache-Control: no-cache, must-revalidate\n");  
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");  

// e-z params  
$dim = 150;         /* image displays proportionally within this square dimension ) */  
$cols = 4;          /* thumbnails per row */
$thumIndicator = '_th'; /* e.g., *image123_th.jpg*) -> if not using thumbNails then use empty string */  
?>  
<!DOCTYPE html>  
<html>  
<head>  
    <title>browse file</title>  
    <meta charset="utf-8">  

    <style>  
        html,  
        body {padding:0; margin:0; background:black; }  
        table {width:100%; border-spacing:15px; }  
        td {text-align:center; padding:5px; background:#181818; }  
        img {border:5px solid #303030; padding:0; verticle-align: middle;}  
        img:hover { border-color:blue; cursor:pointer; }  
    </style>  

</head>  


<body>  

<table>  

<?php  

$dir = $_GET['dir'];    

$dir = rtrim($dir, '/'); // the script will add the ending slash when appropriate  

$files = scandir($dir);  

$images = array();  

foreach($files as $file){  
    // filter for thumbNail image files (use an empty string for $thumIndicator if not using thumbnails )
    if( !preg_match('/'. $thumIndicator .'\.(jpg|jpeg|png|gif)$/i', $file) )  
        continue;  

    $thumbSrc = $dir . '/' . $file;  
    $fileBaseName = str_replace('_th.','.',$file);  

    $image_info = getimagesize($thumbSrc);  
    $_w = $image_info[0];  
    $_h = $image_info[1]; 

    if( $_w > $_h ) {       // $a is the longer side and $b is the shorter side
        $a = $_w;  
        $b = $_h;  
    } else {  
        $a = $_h;  
        $b = $_w;  
    }     

    $pct = $b / $a;     // the shorter sides relationship to the longer side

    if( $a > $dim )   
        $a = $dim;      // limit the longer side to the dimension specified

    $b = (int)($a * $pct);  // calculate the shorter side

    $width =    $_w > $_h ? $a : $b;  
    $height =   $_w > $_h ? $b : $a;  

    // produce an image tag
    $str = sprintf('<img src="%s" width="%d" height="%d" title="%s" alt="">',   
        $thumbSrc,  
        $width,  
        $height,  
        $fileBaseName  
    );  

    // save image tags in an array
    $images[] = str_replace("'", "\\'", $str); // an unescaped apostrophe would break js  

}

$numRows = floor( count($images) / $cols );  

// if there are any images left over then add another row
if( count($images) % $cols != 0 )  
    $numRows++;  


// produce the correct number of table rows with empty cells
for($i=0; $i<$numRows; $i++)   
    echo "\t<tr>" . implode('', array_fill(0, $cols, '<td></td>')) . "</tr>\n\n";  

?>  
</table>  


<script>  

// make a js array from the php array
images = [  
<?php   

foreach( $images as $v)  
    echo sprintf("\t'%s',\n", $v);  

?>];  

tbl = document.getElementsByTagName('table')[0];  

td = tbl.getElementsByTagName('td');  

// fill the empty table cells with data
for(var i=0; i < images.length; i++)  
    td[i].innerHTML = images[i];  


// event handler to place clicked image into CKeditor
tbl.onclick =   

    function(e) {  

        var tgt = e.target || event.srcElement,  
            url;  

        if( tgt.nodeName != 'IMG' )  
            return;  

        url = '<?php echo $dir;?>' + '/' + tgt.title;  

        this.onclick = null;  

        window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, url);  

        window.close();  
    }  
</script>  
</body>  
</html>            

What GRANT USAGE ON SCHEMA exactly do?

GRANTs on different objects are separate. GRANTing on a database doesn't GRANT rights to the schema within. Similiarly, GRANTing on a schema doesn't grant rights on the tables within.

If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table.

The rights tests are done in order:

Do you have `USAGE` on the schema? 
    No:  Reject access. 
    Yes: Do you also have the appropriate rights on the table? 
        No:  Reject access. 
        Yes: Check column privileges.

Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public, which every user/group is a member of. So everyone already has usage on that schema.

The phrase:

(assuming that the objects' own privilege requirements are also met)

Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.

It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists.

If you were to grant world-read rights on the file (mode rw-r--r--) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.

If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.

You need to set both permissions for people to actually be able to view the file.

Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table.

(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECTing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

For those it might help, I use this list as a reference to define my content-type when I have to deal with images on my app.

It says that jpg extension can be declared with Content-type : image/jpeg

There isn't any image/jpg attribute for content-type.

Node.js: get path from the request

simply call req.url. that should do the work. you'll get something like /something?bla=foo

What is ADT? (Abstract Data Type)

ADT is a data type in which collection of data and operation works on that data . It focuses on more the concept than implementation.. It's up to you which language you use to make it visible on the earth Example: Stack is an ADT while the Array is not Stack is ADT because we can implement it by many languages, Python c c++ java and many more , while Array is built in data type

How do you fix a bad merge, and replay your good commits onto a fixed merge?

You should probably clone your repository first.

Remove your file from all branches history:
git filter-branch --tree-filter 'rm -f filename.orig' -- --all

Remove your file just from the current branch:
git filter-branch --tree-filter 'rm -f filename.orig' -- --HEAD    

Lastly you should run to remove empty commits:
git filter-branch -f --prune-empty -- --all

In Git, how do I figure out what my current revision is?

What do you mean by "version number"? It is quite common to tag a commit with a version number and then use

$ git describe --tags

to identify the current HEAD w.r.t. any tags. If you mean you want to know the hash of the current HEAD, you probably want:

$ git rev-parse HEAD

or for the short revision hash:

$ git rev-parse --short HEAD

It is often sufficient to do:

$ cat .git/refs/heads/${branch-master}

but this is not reliable as the ref may be packed.

fastest MD5 Implementation in JavaScript

I've heard Joseph's Myers implementation is quite fast. Additionally, he has a lengthy article on Javascript optimization describing what he learned while writing his implementation. It's a good read for anyone interested in performant javascript.

http://www.webreference.com/programming/javascript/jkm3/

His MD5 implementation can be found here

What is default color for text in textview?

There are defaults in the theme that Android uses if you don't specifiy a text color. It may be different colors in various Android UIs (e.g. HTC Sense, Samsung TouchWiz, etc). Android has a _dark and _light theme, so the defaults are different for these (but nearly black in both of them in vanilla android). It is however good practice to define your primary text color yourself for to provide a consistent style throughout the devices.

In code:

getResources().getColor(android.R.color.primary_text_dark);
getResources().getColor(android.R.color.primary_text_light);

In xml:

android:color="@android:color/primary_text_dark"
android:color="@android:color/primary_text_light"

As reference in vanilla Android the dark theme text color is #060001 and the in the light theme it's #060003 since API v1. See the android style class here

Android: Go back to previous activity

Besides all the mentioned answers, their is still an alternative way of doing this, lets say you have two classes , class A and class B.

Class A you have made some activities like checkbox select, printed out some data and intent to class B. Class B, you would like to pass multiple values to class A and maintain the previous state of class A, you can use, try this alternative method or download source code to demonstrate this

http://whats-online.info/science-and-tutorials/125/Android-maintain-the-previous-state-of-activity-on-intent/

or

http://developer.android.com/reference/android/content/Intent.html

What is the best way to implement a "timer"?

By using System.Windows.Forms.Timer class you can achieve what you need.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();


t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
      //Call method
}

By using stop() method you can stop timer.

t.Stop();

Using CSS for a fade-in effect on page load

Looking forward to Web Animations in 2020.

_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        transform: `translateY(${el.getBoundingClientRect().top}px)`
      },
    ], {
      duration: durationInMs,
      easing: 'ease-in',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeIn(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        opacity: '0.5',
        offset: 0.5
      },
      {
        opacity: '1',
        offset: 1
      }
    ], {
      duration: durationInMs,
      easing: 'linear',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeInSections() {
  for (const section of document.getElementsByTagName('section')) {
    await fadeIn(section, 200);
  }
}

window.addEventListener('load', async() => {
  await moveToPosition(document.getElementById('headerContent'), 500);
  await fadeInSections();
  await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
  height: 100vh;
}

header {
  height: 20%;
}

.text-center {
  text-align: center;
}

.leading-none {
  line-height: 1;
}

.leading-3 {
  line-height: .75rem;
}

.leading-2 {
  line-height: .25rem;
}

.bg-black {
  background-color: rgba(0, 0, 0, 1);
}

.bg-gray-50 {
  background-color: rgba(249, 250, 251, 1);
}

.pt-12 {
  padding-top: 3rem;
}

.pt-2 {
  padding-top: 0.5rem;
}

.text-lightGray {
  color: lightGray;
}

.container {
  display: flex;
  /* or inline-flex */
  justify-content: space-between;
}

.container section {
  padding: 0.5rem;
}

.opacity-0 {
  opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="Web site created using create-snowpack-app" />
  <link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>

<body>
  <header class="bg-gray-50">
    <div id="headerContent">
      <h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
      <p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
    </div>
  </header>
  <div class="container">
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 1</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 2</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>

    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 3</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
  </div>
  <footer class="opacity-0">
    <h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
    <p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
  </footer>
</body>

</html>
_x000D_
_x000D_
_x000D_

SQL Insert Query Using C#

I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...
here is the code from my current project:

public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
    SqlConnection connection = new SqlConnection(ConnectionString);
    try
    {
        using (SqlCommand cmd = new SqlCommand(query, connection))
        {   // for cases where no parameters needed
            if (parameters != null)
            {
                cmd.Parameters.AddRange(parameters.ToArray());
            }

            connection.Open();
            int result = cmd.ExecuteNonQuery();
            return result;
        }
    }
    catch (Exception ex)
    {
        AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
        return 0;
        throw;
    }

    finally
    {
        CloseConnection(ref connection);
    }
}

private static void CloseConnection(ref SqlConnection conn)
{
    if (conn.State != ConnectionState.Closed)
    {
        conn.Close();
        conn.Dispose();
    }
}

Set cURL to use local virtual hosts

EDIT: While this is currently accepted answer, readers might find this other answer by user John Hart more adapted to their needs. It uses an option which, according to user Ken, was introduced in version 7.21.3 (which was released in December 2010, i.e. after this initial answer).


In your edited question, you're using the URL as the host name, whereas it needs to be the host name only.

Try:

curl -H 'Host: project1.loc' http://127.0.0.1/something

where project1.loc is just the host name and 127.0.0.1 is the target IP address.

(If you're using curl from a library and not on the command line, make sure you don't put http:// in the Host header.)

What is the difference between pull and clone in git?

Hmm, what's missing to see the remote branch "4.2" when I pull, as I do when I clone? Something's clearly not identical.

tmp$  mkdir some_repo

tmp$  cd some_repo

some_repo$  git init
Initialized empty Git repository in /tmp/some_repo/.git/

some_repo$  git pull https://github.ourplace.net/babelfish/some_repo.git
  :
From https://github.ourplace.net/babelfish/some_repo
 * branch            HEAD       -> FETCH_HEAD

some_repo$  git branch
* master

vs

tmp$  rm -rf some_repo

tmp$  git clone https://github.ourplace.net/babelfish/some_repo.git
Cloning into 'some_repo'...
  :
Checking connectivity... done.

tmp$  cd some_repo

some_repo$  git branch
* 4.2

Why is __dirname not defined in node REPL?

Seems like you could also do this:

__dirname=fs.realpathSync('.');

of course, dont forget fs=require('fs')

(it's not really global in node scripts exactly, its just defined on the module level)

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

It is very easy and simple setting problem that can be fixed in 5 seconds by following these steps

To allow you to save changes after you alter table, Please follow these steps for your sql setting:

  1. Open Microsoft SQL Server Management Studio 2008
  2. Click Tools menu options, then click Options
  3. Select Designers
  4. Uncheck "prevent saving changes that require table re-creation" option
  5. Click OK
  6. Try to alter your table
  7. Your changes will performed as desired

What's onCreate(Bundle savedInstanceState)

As Dhruv Gairola answered, you can save the state of the application by using Bundle savedInstanceState. I am trying to give a very simple example that new learners like me can understand easily.

Suppose, you have a simple fragment with a TextView and a Button. Each time you clicked the button the text changes. Now, change the orientation of you device/emulator and notice that you lost the data (means the changed data after clicking you got) and fragment starts as the first time again. By using Bundle savedInstanceState we can get rid of this. If you take a look into the life cyle of the fragment.Fragment Lifecylce you will get that a method "onSaveInstanceState" is called when the fragment is about to destroyed.

So, we can save the state means the changed text value into that bundle like this

 int counter  = 0;
 @Override
 public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("value",counter);
 }

After you make the orientation the "onCreate" method will be called right? so we can just do this

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState == null){
        //it is the first time the fragment is being called
        counter = 0;
    }else{
        //not the first time so we will check SavedInstanceState bundle
        counter = savedInstanceState.getInt("value",0); //here zero is the default value
    }
}

Now, you won't lose your value after the orientation. The modified value always will be displayed.

Differences between C++ string == and compare()?

One thing that is not covered here is that it depends if we compare string to c string, c string to string or string to string.

A major difference is that for comparing two strings size equality is checked before doing the compare and that makes the == operator faster than a compare.

here is the compare as i see it on g++ Debian 7

// operator ==
  /**
   *  @brief  Test equivalence of two strings.
   *  @param __lhs  First string.
   *  @param __rhs  Second string.
   *  @return  True if @a __lhs.compare(@a __rhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
           const basic_string<_CharT, _Traits, _Alloc>& __rhs)
    { return __lhs.compare(__rhs) == 0; }

  template<typename _CharT>
    inline
    typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, bool>::__type
    operator==(const basic_string<_CharT>& __lhs,
           const basic_string<_CharT>& __rhs)
    { return (__lhs.size() == __rhs.size()
          && !std::char_traits<_CharT>::compare(__lhs.data(), __rhs.data(),
                            __lhs.size())); }

  /**
   *  @brief  Test equivalence of C string and string.
   *  @param __lhs  C string.
   *  @param __rhs  String.
   *  @return  True if @a __rhs.compare(@a __lhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const _CharT* __lhs,
           const basic_string<_CharT, _Traits, _Alloc>& __rhs)
    { return __rhs.compare(__lhs) == 0; }

  /**
   *  @brief  Test equivalence of string and C string.
   *  @param __lhs  String.
   *  @param __rhs  C string.
   *  @return  True if @a __lhs.compare(@a __rhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
           const _CharT* __rhs)
    { return __lhs.compare(__rhs) == 0; }

sys.argv[1], IndexError: list index out of range

sys.argv represents the command line options you execute a script with.

sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

You are attempting to open a file that uses sys.argv[1] (the first argument) as what looks to be the directory.

Try running something like this:

python ConcatenateFiles.py /tmp

iOS for VirtualBox

VirtualBox is a virtualizer, not an emulator. (The name kinda gives it away.) I.e. it can only virtualize a CPU that is actually there, not emulate one that isn't. In particular, VirtualBox can only virtualize x86 and AMD64 CPUs. iOS only runs on ARM CPUs.

window.location.href doesn't redirect

In case anyone was a tired and silly as I was the other night whereupon I came across many threads espousing the different methods to get a javascript redirect, all of which were failing...

You can't use window.location.replace or document.location.href or any of your favourite vanilla javascript methods to redirect a page to itself.

So if you're dynamically adding in the redirect path from the back end, or pulling it from a data tag, make sure you do check at some stage for redirects to the current page. It could be as simple as:

if(window.location.href == linkout)
{
    location.reload();
}
else
{
    window.location.href = linkout;
}

Combining C++ and C - how does #ifdef __cplusplus work?

It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.

Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.

While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.

People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.

Need a good hex editor for Linux

I am a VIMer. I can do some rare Hex edits with:

  • :%!xxd to switch into hex mode

  • :%!xxd -r to exit from hex mode

But I strongly recommend ht

apt-cache show ht

Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>

Homepage: http://hte.sourceforge.net/

Note: The package is called ht, whereas the executable is named hte after the package was installed.

  1. Supported file formats
    • common object file format (COFF/XCOFF32)
    • executable and linkable format (ELF)
    • linear executables (LE)
    • standard DO$ executables (MZ)
    • new executables (NE)
    • portable executables (PE32/PE64)
    • java class files (CLASS)
    • Mach exe/link format (MachO)
    • X-Box executable (XBE)
    • Flat (FLT)
    • PowerPC executable format (PEF)
  2. Code & Data Analyser
    • finds branch sources and destinations recursively
    • finds procedure entries
    • creates labels based on this information
    • creates xref information
    • allows to interactively analyse unexplored code
    • allows to create/rename/delete labels
    • allows to create/edit comments
    • supports x86, ia64, alpha, ppc and java code
  3. Target systems
    • DJGPP
    • GNU/Linux
    • FreeBSD
    • OpenBSD
    • Win32

Refresh image with a new one at the same url

I used the below concept of first binding the image with a false(buffer) url and next binding it with the valid url.

imgcover.ImageUrl = ConfigurationManager.AppSettings["profileLargeImgPath"] + "Myapp_CoverPic_" + userid + "Buffer.jpg";

imgcover.ImageUrl = ConfigurationManager.AppSettings["profileLargeImgPath"] + "Myapp_CoverPic_" + userid + ".jpg";

This way, I am forcing the browser to refresh with valid url.

How to remove carriage return and newline from a variable in shell script

Pipe to sed -e 's/[\r\n]//g' to remove both Carriage Returns (\r) and Line Feeds (\n) from each text line.

How can I calculate the number of years between two dates?

You can get the exact age using timesstamp:

const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
    const dob = new Date(dateOfBirth).getTime();
    const dateToCompare = new Date(dateToCalculate).getTime();
    const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
    return Math.floor(age);
};

Check whether a table contains rows or not sql server 2005

Can't you just count the rows using select count(*) from table (or an indexed column instead of * if speed is important)?

If not then maybe this article can point you in the right direction.

How do I install Eclipse Marketplace in Eclipse Classic?

The easy way to do it

  1. Help--> Install New Software
  2. In the box type in http://download.eclipse.org/mpc/juno

  3. General Purpose Tools--> Select Eclipse Marketplace checkbox and Finish.

Along with these steps I tried To install the whole bunch of software, but it gives an error later. So please make sure you select only one or two at a time.

How does "304 Not Modified" work exactly?

Last-Modified : The last modified date for the requested object

If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.

ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.

If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.

the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:

enter image description here

the server will return 304 when the if statement is False, and browser will use cache.

Prevent screen rotation on Android

The following attribute on the ACTIVITY in AndroidManifest.xml is all you need:

android:configChanges="orientation"

So, the full activity node would be:

<activity android:name="Activity1"
          android:icon="@drawable/icon"
          android:label="App Name"
          android:excludeFromRecents="true"
          android:configChanges="orientation">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>

How to outline text in HTML / CSS

from: Outline effect to text

.strokeme
{
    color: white;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;  
}

lodash: mapping array to object

You can use one liner javascript with array reduce method and ES6 destructuring to convert array of key value pairs to object.

arr.reduce((map, { name, input }) => ({ ...map, [name]: input }), {});

Is there a way to crack the password on an Excel VBA Project?

You can try this direct VBA approach which doesn't require HEX editing. It will work for any files (*.xls, *.xlsm, *.xlam ...).

Tested and works on:

Excel 2007
Excel 2010
Excel 2013 - 32 bit version
Excel 2016 - 32 bit version

Looking for 64 bit version? See this answer

How it works

I will try my best to explain how it works - please excuse my English.

  1. The VBE will call a system function to create the password dialog box.
  2. If user enters the right password and click OK, this function returns 1. If user enters the wrong password or click Cancel, this function returns 0.
  3. After the dialog box is closed, the VBE checks the returned value of the system function
  4. if this value is 1, the VBE will "think" that the password is right, hence the locked VBA project will be opened.
  5. The code below swaps the memory of the original function used to display the password dialog with a user defined function that will always return 1 when being called.

Using the code

Please backup your files first!

  1. Open the file(s) that contain your locked VBA Projects
  2. Create a new xlsm file and store this code in Module1

    code credited to Siwtom (nick name), a Vietnamese developer

    Option Explicit
    
    Private Const PAGE_EXECUTE_READWRITE = &H40
    
    Private Declare Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" _
            (Destination As Long, Source As Long, ByVal Length As Long)
    
    Private Declare Function VirtualProtect Lib "kernel32" (lpAddress As Long, _
            ByVal dwSize As Long, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long
    
    Private Declare Function GetModuleHandleA Lib "kernel32" (ByVal lpModuleName As String) As Long
    
    Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, _
            ByVal lpProcName As String) As Long
    
    Private Declare Function DialogBoxParam Lib "user32" Alias "DialogBoxParamA" (ByVal hInstance As Long, _
            ByVal pTemplateName As Long, ByVal hWndParent As Long, _
            ByVal lpDialogFunc As Long, ByVal dwInitParam As Long) As Integer
    
    Dim HookBytes(0 To 5) As Byte
    Dim OriginBytes(0 To 5) As Byte
    Dim pFunc As Long
    Dim Flag As Boolean
    
    Private Function GetPtr(ByVal Value As Long) As Long
        GetPtr = Value
    End Function
    
    Public Sub RecoverBytes()
        If Flag Then MoveMemory ByVal pFunc, ByVal VarPtr(OriginBytes(0)), 6
    End Sub
    
    Public Function Hook() As Boolean
        Dim TmpBytes(0 To 5) As Byte
        Dim p As Long
        Dim OriginProtect As Long
    
        Hook = False
    
        pFunc = GetProcAddress(GetModuleHandleA("user32.dll"), "DialogBoxParamA")
    
    
        If VirtualProtect(ByVal pFunc, 6, PAGE_EXECUTE_READWRITE, OriginProtect) <> 0 Then
    
            MoveMemory ByVal VarPtr(TmpBytes(0)), ByVal pFunc, 6
            If TmpBytes(0) <> &H68 Then
    
                MoveMemory ByVal VarPtr(OriginBytes(0)), ByVal pFunc, 6
    
                p = GetPtr(AddressOf MyDialogBoxParam)
    
                HookBytes(0) = &H68
                MoveMemory ByVal VarPtr(HookBytes(1)), ByVal VarPtr(p), 4
                HookBytes(5) = &HC3
    
                MoveMemory ByVal pFunc, ByVal VarPtr(HookBytes(0)), 6
                Flag = True
                Hook = True
            End If
        End If
    End Function
    
    Private Function MyDialogBoxParam(ByVal hInstance As Long, _
            ByVal pTemplateName As Long, ByVal hWndParent As Long, _
            ByVal lpDialogFunc As Long, ByVal dwInitParam As Long) As Integer
        If pTemplateName = 4070 Then
            MyDialogBoxParam = 1
        Else
            RecoverBytes
            MyDialogBoxParam = DialogBoxParam(hInstance, pTemplateName, _
                               hWndParent, lpDialogFunc, dwInitParam)
            Hook
        End If
    End Function
    
  3. Paste this code under the above code in Module1 and run it

    Sub unprotected()
        If Hook Then
            MsgBox "VBA Project is unprotected!", vbInformation, "*****"
        End If
    End Sub
    
  4. Come back to your VBA Projects and enjoy.

Is it possible to simulate key press events programmatically?

For those interested, you can, in-fact recreate keyboard input events reliably. In order to change text in input area (move cursors, or the page via an input character) you have to follow the DOM event model closely: http://www.w3.org/TR/DOM-Level-3-Events/#h4_events-inputevents

The model should do:

  • focus (dispatched on the DOM with the target set)

Then for each character:

  • keydown (dispatched on the DOM)
  • beforeinput (dispatched at the target if its a textarea or input)
  • keypress (dispatched on the DOM)
  • input (dispatched at the target if its a textarea or input)
  • change (dispatched at the target if its a select)
  • keyup (dispatched on the DOM)

Then, optionally for most:

  • blur (dispatched on the DOM with the target set)

This actually changes the text in the page via javascript (without modifying value statements) and sets off any javascript listeners/handlers appropriately. If you mess up the sequence javascript will not fire in the appropriate order, the text in the input box will not change, the selections will not change or the cursor will not move to the next space in the text area.

Unfortunately the code was written for an employer under an NDA so I cannot share it, but it is definitely possible but you must recreate the entire key input "stack" for each element in the correct order.

How to sum up an array of integers in C#

An alternative also it to use the Aggregate() extension method.

var sum = arr.Aggregate((temp, x) => temp+x);

image processing to improve tesseract OCR accuracy

I am by no means an OCR expert. But I this week had need to convert text out of a jpg.

I started with a colorized, RGB 445x747 pixel jpg. I immediately tried tesseract on this, and the program converted almost nothing. I then went into GIMP and did the following. image>mode>grayscale image>scale image>1191x2000 pixels filters>enhance>unsharp mask with values of radius = 6.8, amount = 2.69, threshold = 0 I then saved as a new jpg at 100% quality.

Tesseract then was able to extract all the text into a .txt file

Gimp is your friend.

Java 8: How do I work with exception throwing methods in streams?

You might want to do one of the following:

  • propagate checked exception,
  • wrap it and propagate unchecked exception, or
  • catch the exception and stop propagation.

Several libraries let you do that easily. Example below is written using my NoException library.

// Propagate checked exception
as.forEach(Exceptions.sneak().consumer(A::foo));

// Wrap and propagate unchecked exception
as.forEach(Exceptions.wrap().consumer(A::foo));
as.forEach(Exceptions.wrap(MyUncheckedException::new).consumer(A::foo));

// Catch the exception and stop propagation (using logging handler for example)
as.forEach(Exceptions.log().consumer(Exceptions.sneak().consumer(A::foo)));

How to pass objects to functions in C++?

Since no one mentioned I am adding on it, When you pass a object to a function in c++ the default copy constructor of the object is called if you dont have one which creates a clone of the object and then pass it to the method, so when you change the object values that will reflect on the copy of the object instead of the original object, that is the problem in c++, So if you make all the class attributes to be pointers, then the copy constructors will copy the addresses of the pointer attributes , so when the method invocations on the object which manipulates the values stored in pointer attributes addresses, the changes also reflect in the original object which is passed as a parameter, so this can behave same a Java but dont forget that all your class attributes must be pointers, also you should change the values of pointers, will be much clear with code explanation.

Class CPlusPlusJavaFunctionality {
    public:
       CPlusPlusJavaFunctionality(){
         attribute = new int;
         *attribute = value;
       }

       void setValue(int value){
           *attribute = value;
       }

       void getValue(){
          return *attribute;
       }

       ~ CPlusPlusJavaFuncitonality(){
          delete(attribute);
       }

    private:
       int *attribute;
}

void changeObjectAttribute(CPlusPlusJavaFunctionality obj, int value){
   int* prt = obj.attribute;
   *ptr = value;
}

int main(){

   CPlusPlusJavaFunctionality obj;

   obj.setValue(10);

   cout<< obj.getValue();  //output: 10

   changeObjectAttribute(obj, 15);

   cout<< obj.getValue();  //output: 15
}

But this is not good idea as you will be ending up writing lot of code involving with pointers, which are prone for memory leaks and do not forget to call destructors. And to avoid this c++ have copy constructors where you will create new memory when the objects containing pointers are passed to function arguments which will stop manipulating other objects data, Java does pass by value and value is reference, so it do not require copy constructors.

How to initialise memory with new operator in C++?

There is number of methods to allocate an array of intrinsic type and all of these method are correct, though which one to choose, depends...

Manual initialisation of all elements in loop

int* p = new int[10];
for (int i = 0; i < 10; i++)
    p[i] = 0;

Using std::memset function from <cstring>

int* p = new int[10];
std::memset(p, 0, sizeof *p * 10);

Using std::fill_n algorithm from <algorithm>

int* p = new int[10];
std::fill_n(p, 10, 0);

Using std::vector container

std::vector<int> v(10); // elements zero'ed

If C++11 is available, using initializer list features

int a[] = { 1, 2, 3 }; // 3-element static size array
vector<int> v = { 1, 2, 3 }; // 3-element array but vector is resizeable in runtime

How to run a single test with Mocha?

Consolidate all your tests in one test.js file & your package json add scripts as:

  "scripts": {
  "api:test": "node_modules/.bin/mocha --timeout 10000 --recursive api_test/"
},

Type command on your test directory:

npm run api:test

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).