Programs & Examples On #Strength reduction

How can you search Google Programmatically Java API

To search google using API you should use Google Custom Search, scraping web page is not allowed

In java you can use CustomSearch API Client Library for Java

The maven dependency is:

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-customsearch</artifactId>
    <version>v1-rev57-1.23.0</version>
</dependency> 

Example code searching using Google CustomSearch API Client Library

public static void main(String[] args) throws GeneralSecurityException, IOException {

    String searchQuery = "test"; //The query to search
    String cx = "002845322276752338984:vxqzfa86nqc"; //Your search engine

    //Instance Customsearch
    Customsearch cs = new Customsearch.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null) 
                   .setApplicationName("MyApplication") 
                   .setGoogleClientRequestInitializer(new CustomsearchRequestInitializer("your api key")) 
                   .build();

    //Set search parameter
    Customsearch.Cse.List list = cs.cse().list(searchQuery).setCx(cx); 

    //Execute search
    Search result = list.execute();
    if (result.getItems()!=null){
        for (Result ri : result.getItems()) {
            //Get title, link, body etc. from search
            System.out.println(ri.getTitle() + ", " + ri.getLink());
        }
    }

}

As you can see you will need to request an api key and setup an own search engine id, cx.

Note that you can search the whole web by selecting "Search entire web" on basic tab settings during setup of cx, but results will not be exactly the same as a normal browser google search.

Currently (date of answer) you get 100 api calls per day for free, then google like to share your profit.

No converter found capable of converting from type to type

You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.

Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation

import org.springframework.beans.factory.annotation.Value;

public interface DeadlineTypeProjection {
    String getId();

    // can get code and or change name of getter below
    String getCode();

    // Points to the code attribute of entity class
    @Value(value = "#{target.code}")
    String getText();
}

DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class DeadlineType {
    String id;

    // Use this annotation if you need to change the name of the property that is passed back from controller
    // Needs to be called code to be used in Repository
    @JsonProperty(value = "text")
    String code;

}

Entity class

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {

    @Id
    private String id;
    private String code;
}

Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>

import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {

    List<ABDeadlineType> findAll();

    List<DeadlineType> findAllDtoBy();

    List<DeadlineTypeProjection> findAllProjectionBy();

}

Example Controller - accesses the repository directly to simplify code

@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {

    private final ABDeadlineTypeRepository abDeadlineTypeRepository;

    @Autowired
    public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
        this.abDeadlineTypeRepository = abDeadlineTypeRepository;
    }

    @GetMapping(value = "/list")
    public ResponseEntity<List<ABDeadlineType>> list() {

        List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listdto")
    public ResponseEntity<List<DeadlineType>> listDto() {

        List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listprojection")
    public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {

        List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
        return ResponseEntity.ok(types);
    }
}

Hope that helps

Les

What is the difference between URI, URL and URN?

URL -- Uniform Resource Locator

Contains information about how to fetch a resource from its location. For example:

  • http://example.com/mypage.html
  • ftp://example.com/download.zip
  • mailto:[email protected]
  • file:///home/user/file.txt
  • http://example.com/resource?foo=bar#fragment
  • /other/link.html (A relative URL, only useful in the context of another URL)

URLs always start with a protocol (http) and usually contain information such as the network host name (example.com) and often a document path (/foo/mypage.html). URLs may have query parameters and fragment identifiers.

URN -- Uniform Resource Name

Identifies a resource by name. It always starts with the prefix urn: For example:

  • urn:isbn:0451450523 to identify a book by its ISBN number.
  • urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66 a globally unique identifier
  • urn:publishing:book - An XML namespace that identifies the document as a type of book.

URNs can identify ideas and concepts. They are not restricted to identifying documents. When a URN does represent a document, it can be translated into a URL by a "resolver". The document can then be downloaded from the URL.

URI -- Uniform Resource Identifier

URIs encompasses both URLs, URNs, and other ways to indicate a resource.

An example of a URI that is neither a URL nor a URN would be a data URI such as data:,Hello%20World. It is not a URL or URN because the URI contains the data. It neither names it, nor tells you how to locate it over the network.

There are also uniform resource citations (URCs) that point to meta data about a document rather than to the document itself. An example of a URC would be an indicator for viewing the source code of a web page: view-source:http://example.com/. A URC is another type of URI that is neither URL nor URN.

Frequently Asked Questions

I've heard that I shouldn't say URL anymore, why?

The w3 spec for HTML says that the href of an anchor tag can contain a URI, not just a URL. You should be able to put in a URN such as <a href="urn:isbn:0451450523">. Your browser would then resolve that URN to a URL and download the book for you.

Do any browsers actually know how to fetch documents by URN?

Not that I know of, but modern web browser do implement the data URI scheme.

Can a URI be both a URL and a URN?

Good question. I've seen lots of places on the web that state this is true. I haven't been able to find any examples of something that is both a URL and a URN. I don't see how it is possible because a URN starts with urn: which is not a valid network protocol.

Does the difference between URL and URI have anything to do with whether it is relative or absolute?

No. Both relative and absolute URLs are URLs (and URIs.)

Does the difference between URL and URI have anything to do with whether it has query parameters?

No. Both URLs with and without query parameters are URLs (and URIs.)

Does the difference between URL and URI have anything to do with whether it has a fragment identifier?

No. Both URLs with and without fragment identifiers are URLs (and URIs.)

Is a tel: URI a URL or a URN?

For example tel:1-800-555-5555. It doesn't start with urn: and it has a protocol for reaching a resource over a network. It must be a URL.

But doesn't the w3C now say that URLs and URIs are the same thing?

Yes. The W3C realized that there is a ton of confusion about this. They issued a URI clarification document that says that it is now OK to use URL and URI interchangeably. It is no longer useful to strictly segment URIs into different types such as URL, URN, and URC.

Hide vertical scrollbar in <select> element

Chrome (and maybe other webkit browsers) only:

_x000D_
_x000D_
/* you probably want to specify the size if you're going to disable the scrollbar */_x000D_
select[size]::-webkit-scrollbar {_x000D_
 display: none;_x000D_
}
_x000D_
<select size=4>_x000D_
  <option>Mango</option>_x000D_
  <option>Peach</option>_x000D_
  <option>Orange</option>_x000D_
  <option>Banana</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How can I hide an HTML table row <tr> so that it takes up no space?

position: absolute will remove it from the layout flow and should solve your problem - the element will remain in the DOM but won't affect others.

How do you clear the console screen in C?

In Windows I have made the mistake of using

system("clear")

but that is actually for Linux

The Windows type is

system("cls")

without #include conio.h

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

I faced a similar issue. Try to follow the below steps: Manually delete the .m2 folder. Refer to the settings.xml file and check if the repository details are proper, like id and url tags. Also make sure you are connected to same network and check if the URL is accessible from browser. And lastly keep maven projects in /home/User/.

How do I drop a foreign key constraint only if it exists in sql server?

The more simple solution is provided in Eric Isaacs's answer. However, it will find constraints on any table. If you want to target a foreign key constraint on a specific table, use this:

IF EXISTS (SELECT * 
  FROM sys.foreign_keys 
   WHERE object_id = OBJECT_ID(N'dbo.FK_TableName_TableName2')
   AND parent_object_id = OBJECT_ID(N'dbo.TableName')
)
  ALTER TABLE [dbo.TableName] DROP CONSTRAINT [FK_TableName_TableName2]

Simplest way to serve static data from outside the application server in a Java web application

If you decide to dispatch to FileServlet then you will also need allowLinking="true" in context.xml in order to allow FileServlet to traverse the symlinks.

See http://tomcat.apache.org/tomcat-6.0-doc/config/context.html

Make the current commit the only (initial) commit in a Git repository?

To remove the last commit from git, you can simply run

git reset --hard HEAD^ 

If you are removing multiple commits from the top, you can run

git reset --hard HEAD~2 

to remove the last two commits. You can increase the number to remove even more commits.

More info here.

Git tutoturial here provides help on how to purge repository:

you want to remove the file from history and add it to the .gitignore to ensure it is not accidentally re-committed. For our examples, we're going to remove Rakefile from the GitHub gem repository.

git clone https://github.com/defunkt/github-gem.git

cd github-gem

git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch Rakefile' \
  --prune-empty --tag-name-filter cat -- --all

Now that we've erased the file from history, let's ensure that we don't accidentally commit it again.

echo "Rakefile" >> .gitignore

git add .gitignore

git commit -m "Add Rakefile to .gitignore"

If you're happy with the state of the repository, you need to force-push the changes to overwrite the remote repository.

git push origin master --force

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

It is not always about the compilation flags, I have the same error on gentoo when using distcc.

The reason is that on distcc server is using a not-hardened profile and on client the profile is hardened. Check this discussion: https://forums.gentoo.org/viewtopic-p-7463994.html

C#: Limit the length of a string?

foo = foo.Substring(0,5);

Read a file line by line assigning the value to a variable

If you need to process both the input file and user input (or anything else from stdin), then use the following solution:

#!/bin/bash
exec 3<"$1"
while IFS='' read -r -u 3 line || [[ -n "$line" ]]; do
    read -p "> $line (Press Enter to continue)"
done

Based on the accepted answer and on the bash-hackers redirection tutorial.

Here, we open the file descriptor 3 for the file passed as the script argument and tell read to use this descriptor as input (-u 3). Thus, we leave the default input descriptor (0) attached to a terminal or another input source, able to read user input.

Integer value comparison

One more thing to watch out for is if the second value was another Integer object instead of a literal '0', the '==' operator compares the object pointers and will not auto-unbox.

ie:

Integer a = new Integer(0);   
Integer b = new Integer(0);   
int c = 0;

boolean isSame_EqOperator = (a==b); //false!
boolean isSame_EqMethod = (a.equals(b)); //true
boolean isSame_EqAutoUnbox = ((a==c) && (a.equals(c)); //also true, because of auto-unbox

//Note: for initializing a and b, the Integer constructor 
// is called explicitly to avoid integer object caching 
// for the purpose of the example.
// Calling it explicitly ensures each integer is created 
// as a separate object as intended.
// Edited in response to comment by @nolith

Responsive Google Map?

Adding a 100% to the width and height attributes of its iframe has always worked for me. For example

<iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.in/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=+&amp;q=surat&amp;ie=UTF8&amp;hq=&amp;hnear=Surat,+Gujarat&amp;ll=21.195,72.819444&amp;spn=0.36299,0.676346&amp;t=m&amp;z=11&amp;output=embed"></iframe><br />

How can I render Partial views in asp.net mvc 3?

Create your partial view something like:

@model YourModelType
<div>
  <!-- HTML to render your object -->
</div>

Then in your view use:

@Html.Partial("YourPartialViewName", Model)

If you do not want a strongly typed partial view remove the @model YourModelType from the top of the partial view and it will default to a dynamic type.

Update

The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/ in the path below.

@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)

Setting dynamic scope variables in AngularJs - scope.<some_string>

If you are using Lodash library below is the way to set a dynamic variable in the angular scope.

To set the value in the angular scope.

_.set($scope, the_string, 'life.meaning')

To get the value from the angular scope.

_.get($scope, 'life.meaning')

Using wget to recursively fetch a directory with arbitrary files in it

wget -r http://mysite.com/configs/.vim/

works for me.

Perhaps you have a .wgetrc which is interfering with it?

Oracle insert if not exists statement

The correct way to insert something (in Oracle) based on another record already existing is by using the MERGE statement.

Please note that this question has already been answered here on SO:

What's the simplest way to print a Java array?

If using Commons.Lang library, we could do:

ArrayUtils.toString(array)

int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob"};
ArrayUtils.toString(intArray);
ArrayUtils.toString(strArray);

Output:

{1,2,3,4,5}
{John,Mary,Bob}

How to set the JSTL variable value in javascript?

Just don't. Don't write code with code. Write a JSON object or a var somewhere but for the love of a sensible HTTP divide, don't write JavaScript functions or methods hardcoded with vars/properties provided by JSTL. Generating JSON is cool. It ends there or your UI dev hates you.

Imagine if you had to dig into JavaScript to find something that was setting parameters in the middle of a class that originated on the client-side. It's awful. Pass data back and forth. Handle the data. But don't try to generate actual code.

Turning a Comma Separated string into individual rows

Finally, the wait is over with SQL Server 2016. They have introduced the Split string function, STRING_SPLIT:

select OtherID, cs.Value --SplitData
from yourtable
cross apply STRING_SPLIT (Data, ',') cs

All the other methods to split string like XML, Tally table, while loop, etc.. have been blown away by this STRING_SPLIT function.

Here is an excellent article with performance comparison: Performance Surprises and Assumptions: STRING_SPLIT.

For older versions, using tally table here is one split string function(best possible approach)

CREATE FUNCTION [dbo].[DelimitedSplit8K]
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
     -- enough to cover NVARCHAR(4000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;

Referred from Tally OH! An Improved SQL 8K “CSV Splitter” Function

What is the exact location of MySQL database tables in XAMPP folder?

Well, here's what worked for me:
Copy and paste the entire data folder, not just the content.
I use xampp, and the path to the data is xampp/mysql/data.

Goodluck!

How to find the date of a day of the week from a date using PHP?

Just:

2012-10-11 as $date and 5 as $day

<?php
$day=5;
$w      = date("w", strtotime("2011-01-11")) + 1; // you must add 1 to for Sunday

echo $w;

$sunday = date("Y-m-d", strtotime("2011-01-11")-strtotime("+$w day"));

$result = date("Y-m-d", strtotime($sunday)+strtotime("+$day day"));

echo $result;

?>

The $result = '2012-10-12' is what you want.

relative path in BAT script

I have found that %CD% gives the path the script was called from and not the path of the script, however, %~dp0 will give the path of the script itself.

android start activity from service

From inside the Service class:

Intent dialogIntent = new Intent(this, MyActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);

"Unable to find remote helper for 'https'" during git clone

found this in 2020 and solution solved the issue with OMZ https://stackoverflow.com/a/13018777/13222154

...
?  ~ cd $ZSH
?  .oh-my-zsh (master) ? git remote -v
origin  https://github.com/ohmyzsh/ohmyzsh.git (fetch)
origin  https://github.com/ohmyzsh/ohmyzsh.git (push)
?  .oh-my-zsh (master) ? date ; omz update
Wed Sep 30 16:16:31 CDT 2020
Updating Oh My Zsh
fatal: Unable to find remote helper for 'https'
There was an error updating. Try again later?
omz::update: restarting the zsh session...

...

    ln "$execdir/git-remote-http" "$execdir/$p" 2>/dev/null || \
    ln -s "git-remote-http" "$execdir/$p" 2>/dev/null || \
    cp "$execdir/git-remote-http" "$execdir/$p" || exit; \
done && \
./check_bindir "z$bindir" "z$execdir" "$bindir/git-add"
?  git-2.9.5 
?  git-2.9.5 
?  git-2.9.5 
?  git-2.9.5 omz update       
Updating Oh My Zsh
remote: Enumerating objects: 296, done.
remote: Counting objects: 100% (296/296), done.
remote: Compressing objects: 100% (115/115), done.
remote: Total 221 (delta 146), reused 179 (delta 105), pack-reused 0
Receiving objects: 100% (221/221), 42.89 KiB | 0 bytes/s, done.
Resolving deltas: 100% (146/146), completed with 52 local objects.
From https://github.com/ohmyzsh/ohmyzsh
 * branch            master     -> FETCH_HEAD
   7deda85..f776af2  master     -> origin/master
Created autostash: 273f6e9

Allow anything through CORS Policy

I had issues, especially with Chrome as well. What you did looks essentially like what I did in my application. The only difference is that I am responding with a correct hostnames in my Origin CORS headers and not a wildcard. It seems to me that Chrome is picky with this.

Switching between development and production is a pain, so I wrote this little function which helps me in development mode and also in production mode. All of the following things happen in my application_controller.rb unless otherwise noted, it might not be the best solution, but rack-cors didn't work for me either, I can't remember why.

def add_cors_headers
  origin = request.headers["Origin"]
  unless (not origin.nil?) and (origin == "http://localhost" or origin.starts_with? "http://localhost:")
    origin = "https://your.production-site.org"
  end
  headers['Access-Control-Allow-Origin'] = origin
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'
  allow_headers = request.headers["Access-Control-Request-Headers"]
  if allow_headers.nil?
    #shouldn't happen, but better be safe
    allow_headers = 'Origin, Authorization, Accept, Content-Type'
  end
  headers['Access-Control-Allow-Headers'] = allow_headers
  headers['Access-Control-Allow-Credentials'] = 'true'
  headers['Access-Control-Max-Age'] = '1728000'
end

And then I have this little thing in my application_controller.rb because my site requires a login:

before_filter :add_cors_headers
before_filter {authenticate_user! unless request.method == "OPTIONS"}

In my routes.rb I also have this thing:

match '*path', :controller => 'application', :action => 'empty', :constraints => {:method => "OPTIONS"}

and this method looks like this:

def empty
  render :nothing => true
end

Generate SQL Create Scripts for existing tables with Query

See my answer in this Question : How to generate create script of table using SQL query in SQL Server

Use this query :

DROP FUNCTION [dbo].[Get_Table_Script]
Go

Create Function Get_Table_Script
(
    @vsTableName varchar(50)
)

Returns
    VarChar(Max)
With ENCRYPTION

Begin

Declare @ScriptCommand varchar(Max)

Select @ScriptCommand =
    ' Create Table [' + SO.name + '] (' + o.list + ')' 
    +
    (
        Case
        When TC.Constraint_Name IS NULL 
            Then ''
        Else 'ALTER TABLE ' + SO.Name + ' ADD CONSTRAINT ' +
            TC.Constraint_Name  + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')'
        End
    )
From sysobjects As SO
    Cross Apply

    (
        Select 
            '  [' + column_name + '] ' + 
             data_type + 
             (
                Case data_type
                    When 'sql_variant' 
                        Then ''
                    When 'text' 
                        Then ''
                    When 'decimal' 
                        Then '(' + Cast( numeric_precision_radix As varchar ) + ', ' + Cast( numeric_scale As varchar ) + ') '
                    Else Coalesce( '(' + 
                                        Case 
                                            When character_maximum_length = -1 
                                                Then 'MAX'
                                            Else Cast( character_maximum_length As VarChar ) 
                                        End + ')' , ''
                                 ) 
                End 
            ) 
            + ' ' +
            (
                Case 
                    When Exists ( 
                                    Select id 
                                    From syscolumns
                                    Where 
                                        ( object_name(id) = SO.name )
                                        And 
                                        ( name = column_name )
                                        And 
                                        ( columnproperty(id,name,'IsIdentity') = 1 )
                                ) 
                        Then 'IDENTITY(' + 
                                Cast( ident_seed(SO.name) As varchar ) + ',' + 
                                Cast( ident_incr(SO.name) As varchar ) + ')'

                    Else ''

                End
            ) + ' ' +

            (
                Case 
                    When IS_NULLABLE = 'No' 
                        Then 'NOT ' 
                    Else '' 
                End 
            ) + 'NULL ' + 
            (
                Case 
                    When information_schema.columns.COLUMN_DEFAULT IS NOT NULL 
                        Then 'DEFAULT ' + information_schema.columns.COLUMN_DEFAULT 
                    ELse '' 
                End 
            ) + ', ' 
        From information_schema.columns 
        Where 
            ( table_name = SO.name )
        Order by ordinal_position
        FOR XML PATH('')) o (list)

        Inner Join information_schema.table_constraints As TC On (
                                                                    ( TC.Table_name = SO.Name )
                                                                    AND 
                                                                    ( TC.Constraint_Type  = 'PRIMARY KEY' )
                                                                    And 
                                                                    ( TC.TABLE_NAME = @vsTableName )
                                                                 )
        Cross Apply
            (
                Select '[' + Column_Name + '], '
                From  information_schema.key_column_usage As kcu
                Where 
                    ( kcu.Constraint_Name = TC.Constraint_Name )
                Order By ORDINAL_POSITION
                FOR XML PATH('')
            ) As j (list)
Where
    ( xtype = 'U' )
    AND 
    ( Name NOT IN ('dtproperties') )

Return @ScriptCommand

End

And you can fire this Function like this :

Select [dbo].Get_Table_Script '<Your_Table_Name>'

Using CSS td width absolute, position

My crazy solution.)

$(document).ready(function() {
    $("td").each(function(index) { 
    var htmlText = "<div style='width:300px;'>" + $(this).text() +"</div>";
    $(this).html(htmlText);
  });
});

How to copy and paste worksheets between Excel workbooks?

You can also do this without any code at all. If you right-click on the little sheet tab at the bottom of the sheet, and select "Move or Copy", you will get a dialog box that lets you choose which open workbook to transfer the sheet to.

See this link for more detailed instructions and screenshots.

CSS background opacity with rgba not working in IE 8

This a transparency solution for most browsers including IE x

.transparent {
    /* Required for IE 5, 6, 7 */
    /* ...or something to trigger hasLayout, like zoom: 1; */
    width: 100%; 

    /* Theoretically for IE 8 & 9 (more valid) */   
    /* ...but not required as filter works too */
    /* should come BEFORE filter */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

    /* This works in IE 8 & 9 too */
    /* ... but also 5, 6, 7 */
    filter: alpha(opacity=50);

    /* Older than Firefox 0.9 */
    -moz-opacity:0.5;

    /* Safari 1.x (pre WebKit!) */
    -khtml-opacity: 0.5;

    /* Modern!
    /* Firefox 0.9+, Safari 2?, Chrome any?
    /* Opera 9+, IE 9+ */
    opacity: 0.5;
}

The request was aborted: Could not create SSL/TLS secure channel

I finally found the answer (I haven't noted my source but it was from a search);

While the code works in Windows XP, in Windows 7, you must add this at the beginning:

// using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons

And now, it works perfectly.


ADDENDUM

As mentioned by Robin French; if you are getting this problem while configuring PayPal, please note that they won't support SSL3 starting by December, 3rd 2018. You'll need to use TLS. Here's Paypal page about it.

How to retrieve a user environment variable in CMake (Windows)

You need to have your variables exported. So for example in Linux:

export EnvironmentVariableName=foo

Unexported variables are empty in CMAKE.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

This solved it for me:
https://gist.github.com/beccasaurus/929007/a8f820b153a1cfdee3d06a9c0a1d7ebfced8bb77

TL;DR:
Problem:
localhost returns expected content, remote IP alters 400 content to "Bad Request"
Solution:
Adding <httpErrors existingResponse="PassThrough"></httpErrors> to web.config/configuration/system.webServer solved this for me; now all servers (local & remote) return the exact same content (generated by me) regardless of the IP address and/or HTTP code I return.

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had a such problem too because i was using IMG tag and UL tag.

Try to apply the 'corners' plugin to elements such as $('#mydiv').corner(), $('#myspan').corner(), $('#myp').corner() but NOT for $('#img').corner()! This rule is related with adding child DIVs into specified element for emulation round-corner effect. As we know IMG element couldn't have any child elements.

I've solved this by wrapping a needed element within the div and changing IMG to DIV with background: CSS property.

Good luck!

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

Alternative to itoa() for converting integer to string C++?

Note that all of the stringstream methods may involve locking around the use of the locale object for formatting. This may be something to be wary of if you're using this conversion from multiple threads...

See here for more. Convert a number to a string with specified length in C++

Implementing a simple file download servlet

Try with Resource

File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
   ps.println("Bar");
}
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
         String.format("attachment; filename=\"%s\"", file.getName()));

OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
    byte[] buffer = new byte[4096];
    int length;
    while ((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
    }
}
out.flush();

Python Pandas : pivot table with aggfunc = count unique distinct

You can construct a pivot table for each distinct value of X. In this case,

for xval, xgroup in g:
    ptable = pd.pivot_table(xgroup, rows='Y', cols='Z', 
        margins=False, aggfunc=numpy.size)

will construct a pivot table for each value of X. You may want to index ptable using the xvalue. With this code, I get (for X1)

     X        
Z   Z1  Z2  Z3
Y             
Y1   2   1 NaN
Y2 NaN NaN   1

How can I convert a string to upper- or lower-case with XSLT?

For ANSI character encoding:

 translate(//variable, 'ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞŸŽŠŒ', 'abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿžšœ')

JQuery - Call the jquery button click event based on name property

You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;

$(function() {
    $("input[name = 'xyz']").css("border","2px solid red");
})

DEMO

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Update for MySQL 8.0

Your sql-mode will not have NO_AUTO_CREATE_USER as it has been removed as mentioned here - how-to-set-sql-mode-in-my-cnf-in-mysql-8

[mysqld]
sql-mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

Also if someone doesn't have a my.cnf file then they create a new one in /etc/my.cnf and then add the above lines.

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

Reporting Services export to Excel with Multiple Worksheets

I found a simple way around this in 2005. Here are my steps:

  1. Create a string parameter with values ‘Y’ and ‘N’ called ‘PageBreaks’.
  2. Add a group level above the group (value) which was used to split the data to the multiple sheets in Excel.
  3. Inserted into the first textbox field for this group, the expression for the ‘PageBreaks’ as such… =IIF(Parameters!PageBreaks.Value="Y",Fields!DISP_PROJECT.Value,"") Note: If the parameter =’Y’ then you will get the multiple sheets for each different value. Otherwise the field is NULL for every group record (which causes only one page break at the end).
  4. Change the visibility hidden value of the new grouping row to ‘True’.
  5. NOTE: When you do this it will also determine whether or not you have a page break in the view, but my users love it since they have the control.

What is the difference between `let` and `var` in swift?

It's maybe better to state this difference by the Mutability / Immutability notion that is the correct paradigm of values and instances changeability in Objects space which is larger than the only "constant / variable" usual notions. And furthermore this is closer to Objective C approach.

2 data types: value type and reference type.

In the context of Value Types:

'let' defines a constant value (immutable). 'var' defines a changeable value (mutable).

let aInt = 1   //< aInt is not changeable

var aInt = 1   //< aInt can be changed

In the context of Reference Types:

The label of a data is not the value but the reference to a value.

if aPerson = Person(name:Foo, first:Bar)

aPerson doesn't contain the Data of this person but the reference to the data of this Person.

let aPerson = Person(name:Foo, first:Bar)
               //< data of aPerson are changeable, not the reference

var aPerson = Person(name:Foo, first:Bar)
               //< both reference and data are changeable.

eg:

var aPersonA = Person(name:A, first: a)
var aPersonB = Person(name:B, first: b)

aPersonA = aPersonB

aPersonA now refers to Person(name:B, first: b)

and

let aPersonA = Person(name:A, first: a)
let aPersonB = Person(name:B, first: b)

let aPersonA = aPersonB // won't compile

but

let aPersonA = Person(name:A, first: a)

aPersonA.name = "B" // will compile

Update Jenkins from a war file

We run jenkins from the .war file with the following command.

java -Xmx2500M -jar jenkins.war --httpPort=3333 --prefix=/jenkins

You can even run the command from the ~/Downloads directory

Insert, on duplicate update in PostgreSQL?

UPDATE will return the number of modified rows. If you use JDBC (Java), you can then check this value against 0 and, if no rows have been affected, fire INSERT instead. If you use some other programming language, maybe the number of the modified rows still can be obtained, check documentation.

This may not be as elegant but you have much simpler SQL that is more trivial to use from the calling code. Differently, if you write the ten line script in PL/PSQL, you probably should have a unit test of one or another kind just for it alone.

What is the best IDE to develop Android apps in?

One good system is Basic4Android - great for anyone familiar with Basic,

  • Includes a visual designer for screen layouts
  • Can connect to the emulators available as part of the Android SDK
  • Makes it relatively easy to develop programs.

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

TypeError: 'module' object is not callable

socket is a module, containing the class socket.

You need to do socket.socket(...) or from socket import socket:

>>> import socket
>>> socket
<module 'socket' from 'C:\Python27\lib\socket.pyc'>
>>> socket.socket
<class 'socket._socketobject'>
>>>
>>> from socket import socket
>>> socket
<class 'socket._socketobject'>

This is what the error message means:
It says module object is not callable, because your code is calling a module object. A module object is the type of thing you get when you import a module. What you were trying to do is to call a class object within the module object that happens to have the same name as the module that contains it.

Here is a way to logically break down this sort of error:

  • "module object is not callable. Python is telling me my code trying to call something that cannot be called. What is my code trying to call?"
  • "The code is trying to call on socket. That should be callable! Is the variable socket is what I think it is?`
  • I should print out what socket is and check print socket

Error CS2001: Source file '.cs' could not be found

I open the project,.csproj, using a notepad and delete that missing file reference.

How can I find the number of days between two Date objects in Ruby?

How about this?

(beginDate...endDate).count

The Range is a set of unique serials. And ... is an exclusive Range literal.

So beginDate..(endDate - 1) is same. Except is not.

In case when beginDate equals endDate, first element will be excluded because of uniqueness and ... will exclude last one. So if we want to .count dates between today and today it will return 0.

How to cancel a Task in await?

I just want to add to the already accepted answer. I was stuck on this, but I was going a different route on handling the complete event. Rather than running await, I add a completed handler to the task.

Comments.AsAsyncAction().Completed += new AsyncActionCompletedHandler(CommentLoadComplete);

Where the event handler looks like this

private void CommentLoadComplete(IAsyncAction sender, AsyncStatus status )
{
    if (status == AsyncStatus.Canceled)
    {
        return;
    }
    CommentsItemsControl.ItemsSource = Comments.Result;
    CommentScrollViewer.ScrollToVerticalOffset(0);
    CommentScrollViewer.Visibility = Visibility.Visible;
    CommentProgressRing.Visibility = Visibility.Collapsed;
}

With this route, all the handling is already done for you, when the task is cancelled it just triggers the event handler and you can see if it was cancelled there.

Converting Hexadecimal String to Decimal Integer

This is a little library that should help you with hexadecimals in Java: https://github.com/PatrykSitko/HEX4J

It can convert from and to hexadecimals. It supports:

  • byte
  • boolean
  • char
  • char[]
  • String
  • short
  • int
  • long
  • float
  • double (signed and unsigned)

With it, you can convert your String to hexadecimal and the hexadecimal to a float/double.

Example:

String hexValue = HEX4J.Hexadecimal.from.String("Hello World");
double doubleValue = HEX4J.Hexadecimal.to.Double(hexValue);

how to write procedure to insert data in to the table in phpmyadmin?

# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12

(IN numRating_Chapter INT(11) UNSIGNED, 

 IN txtRating_Chapter VARCHAR(250),

 IN chapterName VARCHAR(250),

 IN addedBy VARCHAR(250)

)

BEGIN
DECLARE numRating_Chapter INT;

DECLARE txtRating_Chapter VARCHAR(250);

DECLARE chapterName1 VARCHAR(250);

DECLARE addedBy1 VARCHAR(250);

DECLARE chapterId INT;

DECLARE studentId INT;

SET chapterName1 = chapterName;
SET addedBy1 = addedBy;

SET chapterId = (SELECT chapterId 
                   FROM chapters 
                   WHERE chaptername = chapterName1);

SET studentId = (SELECT Id 
                   FROM students 
                   WHERE email = addedBy1);

SELECT chapterId;
SELECT studentId;

INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);

END //

//DELIMITER;

WPF global exception handler

A quick example of code for Application.Dispatcher.UnhandledException:

public App() {
    this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}

void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) {
    string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
    MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    // OR whatever you want like logging etc. MessageBox it's just example
    // for quick debugging etc.
    e.Handled = true;
}

I added this code in App.xaml.cs

Best way to track onchange as-you-type in input type="text"?

there is a quite near solution (do not fix all Paste ways) but most of them:

It works for inputs as well as for textareas:

<input type="text" ... >
<textarea ... >...</textarea>

Do like this:

<input type="text" ... onkeyup="JavaScript: ControlChanges()" onmouseup="JavaScript: ControlChanges()" >
<textarea ... onkeyup="JavaScript: ControlChanges()" onmouseup="JavaScript: ControlChanges()" >...</textarea>

As i said, not all ways to Paste fire an event on all browsers... worst some do not fire any event at all, but Timers are horrible to be used for such.

But most of Paste ways are done with keyboard and/or mouse, so normally an onkeyup or onmouseup are fired after a paste, also onkeyup is fired when typing on keyboard.

Ensure yor check code does not take much time... otherwise user get a poor impresion.

Yes, the trick is to fire on key and on mouse... but beware both can be fired, so take in mind such!!!

Automated testing for REST Api

API test automation, up to once per minute, is a service available through theRightAPI. You create your test scenarios, and execute them. Once those tests do what you expect them to, you can then schedule them. Tests can be 'chained' together for scenarios that require authentication. For example, you can have a test that make an OAuth request to Twitter, and creates a shared token that can then be used by any other test. Tests can also have validation criteria attached to ensure http status codes, or even detailed inspection of the responses using javascript or schema validation. Once tests are scheduled, you can then have alerts notify you as soon as a particular test fails validation, or is behaving out of established ranges for response time or response size.

How to compare two dates in php

you can try something like:

        $date1 = date_create('2014-1-23'); // format of yyyy-mm-dd
        $date2 = date_create('2014-2-3'); // format of yyyy-mm-dd
        $dateDiff = date_diff($date1, $date2);
        var_dump($dateDiff);

You can then access the difference in days like this $dateDiff->d;

How to load json into my angular.js ng-model?

Here's a simple example of how to load JSON data into an Angular model.

I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.

http://www.iNorthwind.com/Service1.svc/getAllCustomers

It returns some JSON data which looks like this:

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..and I want to populate a drop down list with this data, to look like this...

Angular screenshot

I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.

How would I do it ?

My Angular controller would look like this:

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

... which fills a "listOfCustomers" variable with this set of JSON data.

Then, in my HTML page, I'd use this:

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

And that's it. We can now see a list of our JSON data on a web page, ready to be used.

The key to this is in the "ng-options" tag:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

It's a strange syntax to get your head around !

When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.

The full script for this example can be found here:

JSON data with Angular

Mike

How can I print out C++ map values?

for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
    it != myMap.end(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator. You can use auto

for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

Note the use of cbegin() and cend() functions.

Easier still, you can use the range-based for loop:

for(auto elem : myMap)
{
   std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}

How to change navbar/container width? Bootstrap 3

Hello this working you try! in your case is .navbar-fixed-top{}

.navbar-fixed-bottom{
    width:1200px;
    left:20%;
}

Nullable DateTime conversion

Make sure those two types are nullable DateTime

var lastPostDate = reader[3] == DBNull.Value ?
                                        null : 
                                   (DateTime?) Convert.ToDateTime(reader[3]);
  • Usage of DateTime? instead of Nullable<DateTime> is a time saver...
  • Use better indent of the ? expression like I did.

I have found this excellent explanations in Eric Lippert blog:

The specification for the ?: operator states the following:

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

  • If X and Y are the same type, then this is the type of the conditional expression.

  • Otherwise, if an implicit conversion exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

  • Otherwise, if an implicit conversion exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

  • Otherwise, no expression type can be determined, and a compile-time error occurs.

The compiler doesn't check what is the type that can "hold" those two types.

In this case:

  • null and DateTime aren't the same type.
  • null doesn't have an implicit conversion to DateTime
  • DateTime doesn't have an implicit conversion to null

So we end up with a compile-time error.

In what cases will HTTP_REFERER be empty

BalusC's list is solid. One additional way this field frequently appears empty is when the user is behind a proxy server. This is similar to being behind a firewall but is slightly different so I wanted to mention it for the sake of completeness.

How do I correct the character encoding of a file?

I found a simple way to auto-detect file encodings - change the file to a text file (on a mac rename the file extension to .txt) and drag it to a Mozilla Firefox window (or File -> Open). Firefox will detect the encoding - you can see what it came up with under View -> Character Encoding.

I changed my file's encoding using TextMate once I knew the correct encoding. File -> Reopen using encoding and choose your encoding. Then File -> Save As and change the encoding to UTF-8 and line endings to LF (or whatever you want)

ipython notebook clear cell output in code

You can use IPython.display.clear_output to clear the output of a cell.

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Concepts

Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.

What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map, ...). This allows to handle asynchronous things in a very flexible way.

A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

(textValue is the control associated with the filter input).

Here is a wider description of such use case: How to watch for form changes in Angular 2?.

There are two great presentations at AngularConnect 2015 and EggHead:

Christoph Burgdorf also wrote some great blog posts on the subject:

In action

In fact regarding your code, you mixed two approaches ;-) Here are they:

  • Manage the observable by your own. In this case, you're responsible to call the subscribe method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of result">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit, OnDestroy {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.friendsObservable = http.get('friends.json')
                      .map(response => response.json())
                      .subscribe(result => this.result = result);
       }
    
       ngOnDestroy() {
         this.friendsObservable.dispose();
       }
    }
    

    Returns from both get and map methods are the observable not the result (in the same way than with promises).

  • Let manage the observable by the Angular template. You can also leverage the async pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe method.

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of (result | async)">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.result = http.get('friends.json')
                      .map(response => response.json());
       }
    }
    

You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe method.

You can also notice that the map method is used to extract the JSON content from the response and use it then in the observable processing.

Hope this helps you, Thierry

Handling a Menu Item Click Event - Android

This code is work for me

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

     if (id == R.id.action_settings) {
  // add your action here that you want
        return true;
    }

    else if (id==R.id.login)
     {
         // add your action here that you want
     }


    return super.onOptionsItemSelected(item);
}

tsc is not recognized as internal or external command

You need to run:

npx tsc

...rather than just calling tsc own its on like a Windows command as everyone else seems to be suggesting.

If you don't have npx installed then you should. It should be installed globally (unlike Typescript). So first run:

npm install -g npx

..then run npx tsc.

Understanding REST: Verbs, error codes, and authentication

I noticed this question a couple of days late, but I feel that I can add some insight. I hope this can be helpful towards your RESTful venture.


Point 1: Am I understanding it right?

You understood right. That is a correct representation of a RESTful architecture. You may find the following matrix from Wikipedia very helpful in defining your nouns and verbs:


When dealing with a Collection URI like: http://example.com/resources/

  • GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.

  • PUT: Meaning defined as "replace the entire collection with another collection".

  • POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.

  • DELETE: Meaning defined as "delete the entire collection".


When dealing with a Member URI like: http://example.com/resources/7HOU57Y

  • GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.

  • PUT: Update the addressed member of the collection or create it with the specified ID.

  • POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.

  • DELETE: Delete the addressed member of the collection.


Point 2: I need more verbs

In general, when you think you need more verbs, it may actually mean that your resources need to be re-identified. Remember that in REST you are always acting on a resource, or on a collection of resources. What you choose as the resource is quite important for your API definition.

Activate/Deactivate Login: If you are creating a new session, then you may want to consider "the session" as the resource. To create a new session, use POST to http://example.com/sessions/ with the credentials in the body. To expire it use PUT or a DELETE (maybe depending on whether you intend to keep a session history) to http://example.com/sessions/SESSION_ID.

Change Password: This time the resource is "the user". You would need a PUT to http://example.com/users/USER_ID with the old and new passwords in the body. You are acting on "the user" resource, and a change password is simply an update request. It's quite similar to the UPDATE statement in a relational database.

My instinct would be to do a GET call to a URL like /api/users/1/activate_login

This goes against a very core REST principle: The correct usage of HTTP verbs. Any GET request should never leave any side effect.

For example, a GET request should never create a session on the database, return a cookie with a new Session ID, or leave any residue on the server. The GET verb is like the SELECT statement in a database engine. Remember that the response to any request with the GET verb should be cache-able when requested with the same parameters, just like when you request a static web page.


Point 3: How to return error messages and codes

Consider the 4xx or 5xx HTTP status codes as error categories. You can elaborate the error in the body.

Failed to Connect to Database: / Incorrect Database Login: In general you should use a 500 error for these types of errors. This is a server-side error. The client did nothing wrong. 500 errors are normally considered "retryable". i.e. the client can retry the same exact request, and expect it to succeed once the server's troubles are resolved. Specify the details in the body, so that the client will be able to provide some context to us humans.

The other category of errors would be the 4xx family, which in general indicate that the client did something wrong. In particular, this category of errors normally indicate to the client that there is no need to retry the request as it is, because it will continue to fail permanently. i.e. the client needs to change something before retrying this request. For example, "Resource not found" (HTTP 404) or "Malformed Request" (HTTP 400) errors would fall in this category.


Point 4: How to do authentication

As pointed out in point 1, instead of authenticating a user, you may want to think about creating a session. You will be returned a new "Session ID", along with the appropriate HTTP status code (200: Access Granted or 403: Access Denied).

You will then be asking your RESTful server: "Can you GET me the resource for this Session ID?".

There is no authenticated mode - REST is stateless: You create a session, you ask the server to give you resources using this Session ID as a parameter, and on logout you drop or expire the session.

Get first key in a (possibly) associative array?

array_keys returns an array of keys. Take the first entry. Alternatively, you could call reset on the array, and subsequently key. The latter approach is probably slightly faster (Thoug I didn't test it), but it has the side effect of resetting the internal pointer.

Default username password for Tomcat Application Manager

First navigate to below location and open it in a text editor

<TOMCAT_HOME>/conf/tomcat-users.xml

For tomcat 7, Add the following xml code somewhere between <tomcat-users> I find the following solution.

  <role rolename="manager-gui"/>
  <user username="username" password="password" roles="manager-gui"/>

Now restart the tomcat server.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

How can I get terminal output in python?

The recommended way in Python 3.5 and above is to use subprocess.run():

from subprocess import run
output = run("pwd", capture_output=True).stdout

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

How to compare two tags with git?

$ git diff tag1 tag2

or show log between them:

$ git log tag1..tag2

sometimes it may be convenient to see only the list of files that were changed:

$ git diff tag1 tag2 --stat

and then look at the differences for some particular file:

$ git diff tag1 tag2 -- some/file/name

A tag is only a reference to the latest commit 'on that tag', so that you are doing a diff on the commits between them.

(Make sure to do git pull --tags first)

Also, a good reference: http://learn.github.com/p/diff.html

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

JSON Invalid UTF-8 middle byte

I got this after saving the JSON file using Notepad2, so I had to open it with Notepad++ and then say "Convert to UTF-8". Then it worked.

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

File being used by another process after using File.Create()

When creating a text file you can use the following code:

System.IO.File.WriteAllText("c:\test.txt", "all of your content here");

Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:

string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
    System.IO.FileStream f = System.IO.File.Create(filePath);
    f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{ 
    //write my text 
}

Python "extend" for a dictionary

In case you need it as a Class, you can extend it with dict and use update method:

Class a(dict):
  # some stuff
  self.update(b)

Python Loop: List Index Out of Range

Try reducing the range of the for loop to range(len(a)-1):

a = [0,1,2,3]
b = []

for i in range(len(a)-1):
    b.append(a[i]+a[i+1])

print(b)

This can also be written as a list comprehension:

b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)

Javascript - sort array based on another array

I had to do this for a JSON payload I receive from an API, but it wasn't in the order I wanted it.

Array to be the reference array, the one you want the second array sorted by:

var columns = [
    {last_name: "last_name"},
    {first_name: "first_name"},
    {book_description: "book_description"},
    {book_id: "book_id"},
    {book_number: "book_number"},
    {due_date: "due_date"},
    {loaned_out: "loaned_out"}
];

I did these as objects because these will have other properties eventually.

Created array:

 var referenceArray= [];
 for (var key in columns) {
     for (var j in columns[key]){
         referenceArray.push(j);
     }
  }

Used this with result set from database. I don't know how efficient it is but with the few number of columns I used, it worked fine.

result.forEach((element, index, array) => {                            
    var tr = document.createElement('tr');
    for (var i = 0; i < referenceArray.length - 1; i++) {
        var td = document.createElement('td');
        td.innerHTML = element[referenceArray[i]];
        tr.appendChild(td);

    }
    tableBody.appendChild(tr);
}); 

How can I print the contents of an array horizontally?

I would suggest:

foreach(var item in array)
  Console.Write("{0}", item);

As written above, except it does not raise an exception if one item is null.

Console.Write(string.Join(" ", array));

would be perfect if the array is a string[].

git: fatal: Could not read from remote repository

I solved this problem by switching to root with sudo su.

Unable to install pyodbc on Linux

Execute the following commands (tested on centos 6.5):

yum install install unixodbc-dev
yum install gcc-c++
yum install python-devel
pip install --allow-external pyodbc --allow-unverified pyodbc pyodbc

How to remove symbols from a string with Python?

Sometimes it takes longer to figure out the regex than to just write it out in python:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')

If you need other characters you can change it to use a white-list or extend your black-list.

Sample white-list:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

Sample white-list using a generator-expression:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

Disable developer mode extensions pop up in Chrome

For anyone using WebdriverIO, you can disable extensions by creating your client like this:

var driver = require('webdriverio');
var client = driver.remote({
    desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions: {
            args: [
                'disable-extensions'
            ]
        }
    }
});

C++, What does the colon after a constructor mean?

It's called an initialization list. It initializes members before the body of the constructor executes.

How to filter multiple values (OR operation) in angularJS

The quickest solution that I've found is to use the filterBy filter from angular-filter, for example:

<input type="text" placeholder="Search by name or genre" ng-model="ctrl.search"/>   
<ul>
  <li ng-repeat="movie in ctrl.movies | filterBy: ['name', 'genre']: ctrl.search">
    {{movie.name}} ({{movie.genre}}) - {{movie.rating}}
  </li>
</ul>

The upside is that angular-filter is a fairly popular library (~2.6k stars on GitHub) which is still actively developed and maintained, so it should be fine to add it to your project as a dependency.

jQuery AJAX submit form

JavaScript

(function ($) {
    var form= $('#add-form'),
      input = $('#exampleFormControlTextarea1');


   form.submit(function(event) {

       event.preventDefault(); 

       var req = $.ajax({
           url: form.attr('action'),
           type: 'POST',
           data: form.serialize()
       });
    req.done(function(data) {
       if (data === 'success') {
           var li = $('<li class="list-group-item">'+ input.val() +'</li>');
            li.hide()
                .appendTo('.list-group')
                .fadeIn();
            $('input[type="text"],textarea').val('');
        }
   });
});


}(jQuery));

HTML

    <ul class="list-group col-sm-6 float-left">
            <?php
            foreach ($data as $item) {
                echo '<li class="list-group-item">'.$item.'</li>';
            }
            ?>
        </ul>

        <form id="add-form" class="col-sm-6 float-right" action="_inc/add-new.php" method="post">
            <p class="form-group">
                <textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="Is there something new?"></textarea>
            </p>
            <button type="submit" class="btn btn-danger">Add new item</button>
        </form>

How to add text to JFrame?

when I create my JLabel and enter the text to it, there is no wordwrap or anything

HTML formatting can be used to cause word wrap in any Swing component that offers styled text. E.G. as demonstrated in this answer.

Get random sample from list while maintaining ordering of items?

Maybe you can just generate the sample of indices and then collect the items from your list.

randIndex = random.sample(range(len(mylist)), sample_size)
randIndex.sort()
rand = [mylist[i] for i in randIndex]

Are members of a C++ struct initialized to 0 by default?

In C++, use no-argument constructors. In C you can't have constructors, so use either memset or - the interesting solution - designated initializers:

struct Snapshot s = { .x = 0.0, .y = 0.0 };

Python-Requests close http connection

I think a more reliable way of closing a connection is to tell the sever explicitly to close it in a way compliant with HTTP specification:

HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example,

   Connection: close

in either the request or the response header fields indicates that the connection SHOULD NOT be considered `persistent' (section 8.1) after the current request/response is complete.

The Connection: close header is added to the actual request:

r = requests.post(url=url, data=body, headers={'Connection':'close'})

Changing the selected option of an HTML Select element

Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():

NodeList.prototype.forEach = Array.prototype.forEach

Just:

var requiredValue = 'i-50332a31',   
  selectBox = document.querySelector('select')

selectBox.childNodes.forEach(function(element, index){
  if ( element.value === requiredValue ) {
    selectBox.selectedIndex = index
  }
})

creating a table in ionic

The flexbox grid should do what you want. You're not clear as to what limitation you ran into, so it's hard to address your specifics.

Here's a codepen with a working sample that generates your table with the first couple rows and a header: http://codepen.io/anon/pen/pjzKMZ

HTML

<html ng-app="ionicApp">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <title>Ionic Template</title>

    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
    <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
 </head>

  <body ng-controller="MyCtrl as ctrl">
    <ion-header-bar class="bar-stable">
        <h1 class="title">Service Provider Details</h1>
    </ion-header-bar>
    <ion-content>
        <div class="row header">
          <div class="col">Utility Company Name</div>
          <div class="col">Service Code</div>
          <div class="col">Pay Limit</div>
          <div class="col">Account Number to Use</div>
          <div class="col"></div>
        </div>
        <div class="row" ng-repeat="data in ctrl.data">
          <div class="col">{{data.name}}</div>
          <div class="col">{{data.code}}</div>
          <div class="col">LK {{data.limit}}</div>
          <div class="col">{{data.account}}</div>
          <div class="col"><button class="button" ng-click="ctrl.add($index)">Add</button></div>
        </div>
    </ion-content>
  </body>

</html>

CSS

body {
    cursor: url('http://ionicframework.com/img/finger.png'), auto;
}

.header .col {
    background-color:lightgrey;
}

.col {
    border: solid 1px grey;
    border-bottom-style: none;
    border-right-style: none;
}

.col:last-child {
    border-right: solid 1px grey;
}

.row:last-child .col {
    border-bottom: solid 1px grey;
}

Javascript

angular.module('ionicApp', ['ionic'])

.controller('MyCtrl', function($scope) {

    var ctrl = this;

    ctrl.add = add;
    ctrl.data = [
        {
            name: "AiA",
            code: "AI101",
            limit: 25000,
            account: "Life Insurance"
        },
        {
            name: "Cargills",
            code: "CF001",
            limit: 30000,
            account: "Food City"
        }
    ]

    ////////
    function add(index) {
        window.alert("Added: " + index);
    }
});

How can I send an Ajax Request on button click from a form with 2 buttons?

Given that the only logical difference between the handlers is the value of the button clicked, you can use the this keyword to refer to the element which raised the event and get the val() from that. Try this:

$("button").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/pages/test/",
        data: { 
            id: $(this).val(), // < note use of 'this' here
            access_token: $("#access_token").val() 
        },
        success: function(result) {
            alert('ok');
        },
        error: function(result) {
            alert('error');
        }
    });
});

Format JavaScript date as yyyy-mm-dd

_x000D_
_x000D_
const today = new Date(); // or whatever _x000D_
_x000D_
const yearFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[0]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}`;_x000D_
}_x000D_
_x000D_
const monthFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
const dayFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
console.log(yearFirstFormater(today));_x000D_
console.log(monthFirstFormater(today));_x000D_
console.log(dayFirstFormater(today));
_x000D_
_x000D_
_x000D_

How to create a circle icon button in Flutter?

I used this one because I like the customisation of the border-radius and size.

  Material( // pause button (round)
    borderRadius: BorderRadius.circular(50), // change radius size
    color: Colors.blue, //button colour
    child: InkWell(
      splashColor: Colors.blue[900], // inkwell onPress colour
      child: SizedBox(
        width: 35,height: 35, //customisable size of 'button'
        child: Icon(Icons.pause,color: Colors.white,size: 16,),
      ),
      onTap: () {}, // or use onPressed: () {}
    ),
  ),

  Material( // eye button (customised radius)
    borderRadius: BorderRadius.only(
        topRight: Radius.circular(10.0),
        bottomLeft: Radius.circular(50.0),),
    color: Colors.blue,
    child: InkWell(
      splashColor: Colors.blue[900], // inkwell onPress colour
      child: SizedBox(
        width: 40, height: 40, //customisable size of 'button'
        child: Icon(Icons.remove_red_eye,color: Colors.white,size: 16,),),
      onTap: () {}, // or use onPressed: () {}
    ),
  ),

enter image description here

How to find NSDocumentDirectory in Swift?

Usually i prefer like below in swift 3, because i can add file name and create a file easily

let fileManager = FileManager.default
if let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
    let databasePath = documentsURL.appendingPathComponent("db.sqlite3").path
    print("directory path:", documentsURL.path)
    print("database path:", databasePath)
    if !fileManager.fileExists(atPath: databasePath) {
        fileManager.createFile(atPath: databasePath, contents: nil, attributes: nil)
    }
}

Binary Data in JSON String. Something better than Base64

While it is true that base64 has ~33% expansion rate, it is not necessarily true that processing overhead is significantly more than this: it really depends on JSON library/toolkit you are using. Encoding and decoding are simple straight-forward operations, and they can even be optimized wrt character encoding (as JSON only supports UTF-8/16/32) -- base64 characters are always single-byte for JSON String entries. For example on Java platform there are libraries that can do the job rather efficiently, so that overhead is mostly due to expanded size.

I agree with two earlier answers:

  • base64 is simple, commonly used standard, so it is unlikely to find something better specifically to use with JSON (base-85 is used by postscript etc; but benefits are at best marginal when you think about it)
  • compression before encoding (and after decoding) may make lots of sense, depending on data you use

How to clean project cache in Intellij idea like Eclipse's clean?

Maybe not THE answer, but it's definitely AN answer.

If nothing else is working for you, go the nuclear option: Close IDEA and delete the ".../.IntelliJIdea/system" directory using your local file system tools.

The .IntelliJIdea directory is usually found in your home directory. Your IDE configuration is in the ".../.IntelliJIdea/config" directory, so it should be fine.

Obviously, this is not the "IDEA" way to do it and would be completely unsupported by JetBrains. Also - I don't use Android Studio so I dunno if this will cause problems, but there you go.

It's worked for me before when I've had problems getting IDEA to start and nothing else works to get me going. Maybe back up your entire .IntelliJIdea directory if you have a morbid fear of losing all your work >.<

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

On windows, Try using git bash and use your Linux commands there. Easy approach

chmod 400 *****.pem

ssh -i "******.pem" [email protected]

Apply function to pandas groupby

As of Pandas version 0.22, there exists also an alternative to apply: pipe, which can be considerably faster than using apply (you can also check this question for more differences between the two functionalities).

For your example:

df = pd.DataFrame({"my_label": ['A','B','A','C','D','D','E']})

  my_label
0        A
1        B
2        A
3        C
4        D
5        D
6        E

The apply version

df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])

gives

          my_label
my_label          
A         0.285714
B         0.142857
C         0.142857
D         0.285714
E         0.142857

and the pipe version

df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())

yields

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

So the values are identical, however, the timings differ quite a lot (at least for this small dataframe):

%timeit df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
100 loops, best of 3: 5.52 ms per loop

and

%timeit df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
1000 loops, best of 3: 843 µs per loop

Wrapping it into a function is then also straightforward:

def get_perc(grp_obj):
    gr_size = grp_obj.size()
    return gr_size / gr_size.sum()

Now you can call

df.groupby('my_label').pipe(get_perc)

yielding

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

However, for this particular case, you do not even need a groupby, but you can just use value_counts like this:

df['my_label'].value_counts(sort=False) / df.shape[0]

yielding

A    0.285714
C    0.142857
B    0.142857
E    0.142857
D    0.285714
Name: my_label, dtype: float64

For this small dataframe it is quite fast

%timeit df['my_label'].value_counts(sort=False) / df.shape[0]
1000 loops, best of 3: 770 µs per loop

As pointed out by @anmol, the last statement can also be simplified to

df['my_label'].value_counts(sort=False, normalize=True)

How to get current available GPUs in tensorflow?

The accepted answer gives you the number of GPUs but it also allocates all the memory on those GPUs. You can avoid this by creating a session with fixed lower memory before calling device_lib.list_local_devices() which may be unwanted for some applications.

I ended up using nvidia-smi to get the number of GPUs without allocating any memory on them.

import subprocess

n = str(subprocess.check_output(["nvidia-smi", "-L"])).count('UUID')

Using the passwd command from within a shell script

Read the wise words from:

I quote:

Nothing you can do in bash can possibly work. passwd(1) does not read from standard input. This is intentional. It is for your protection. Passwords were never intended to be put into programs, or generated by programs. They were intended to be entered only by the fingers of an actual human being, with a functional brain, and never, ever written down anywhere.

Nonetheless, we get hordes of users asking how they can circumvent 35 years of Unix security.

It goes on to explain how you can set your shadow(5) password properly, and shows you the GNU-I-only-care-about-security-if-it-doesn't-make-me-think-too-much-way of abusing passwd(1).

Lastly, if you ARE going to use the silly GNU passwd(1) extension --stdin, do not pass the password putting it on the command line.

echo $mypassword | passwd --stdin # Eternal Sin.
echo "$mypassword" | passwd --stdin # Eternal Sin, but at least you remembered to quote your PE.
passwd --stdin <<< "$mypassword" # A little less insecure, still pretty insecure, though.
passwd --stdin < "passwordfile" # With a password file that was created with a secure `umask(1)`, a little bit secure.

The last is the best you can do with GNU passwd. Though I still wouldn't recommend it.

Putting the password on the command line means anyone with even the remotest hint of access to the box can be monitoring ps or such and steal the password. Even if you think your box is safe; it's something you should really get in the habit of avoiding at all cost (yes, even the cost of doing a bit more trouble getting the job done).

GridView sorting: SortDirection always Ascending

In vb.net but very simple!

Protected Sub grTicketHistory_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grTicketHistory.Sorting

    Dim dt As DataTable = Session("historytable")
    If Session("SortDirection" & e.SortExpression) = "ASC" Then
        Session("SortDirection" & e.SortExpression) = "DESC"
    Else
        Session("SortDirection" & e.SortExpression) = "ASC"
    End If
    dt.DefaultView.Sort = e.SortExpression & " " & Session("SortDirection" & e.SortExpression)
    grTicketHistory.DataSource = dt
    grTicketHistory.DataBind()

End Sub

What is the difference between String and string in C#?

As pointed out, they are the same thing and string is just an alias to String.

For what it's worth, I use string to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - int, bool, var etc (although Int32 and Boolean are also correct).

I use String when using the static methods on the String class, like String.Split() or String.IsNullOrEmpty(). I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.

Are vectors passed to functions by value or by reference in C++

A vector is functionally same as an array. But, to the language vector is a type, and int is also a type. To a function argument, an array of any type (including vector[]) is treated as pointer. A vector<int> is not same as int[] (to the compiler). vector<int> is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.

So, you must use vector<int>& (preferably with const, if function isn't modifying it) to pass it as a reference.

After installing SQL Server 2014 Express can't find local db

Most probably, you didn't install any SQL Server Engine service. If no SQL Server engine is installed, no service will appear in the SQL Server Configuration Manager tool. Consider that the packages SQLManagementStudio_Architecture_Language.exe and SQLEXPR_Architecture_Language.exe, available in the Microsoft site contain, respectively only the Management Studio GUI Tools and the SQL Server engine.

If you want to have a full featured SQL Server installation, with the database engine and Management Studio, download the installer file of SQL Server with Advanced Services. Moreover, to have a sample database in order to perform some local tests, use the Adventure Works database.

Considering the package of SQL Server with Advanced Services, at the beginning at the installation you should see something like this (the screenshot below is about SQL Server 2008 Express, but the feature selection is very similar). The checkbox next to "Database Engine Services" must be checked. In the next steps, you will be able to configure the instance settings and other options.

Execute again the installation process and select the database engine services in the feature selection step. At the end of the installation, you should be able to see the SQL Server services in the SQL Server Configuration Manager.

enter image description here

Directly assigning values to C Pointers

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

In the second example, the address is set when you say ptr = &q, so you're OK.

Android Studio does not show layout preview

I also go through same problem and do this simple work just go to res->values->style.xml and change

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 

to

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

How to enable assembly bind failure logging (Fusion) in .NET

Just a tiny bit of info that might help others; if you do something along the lines of searching all assemblies in some directory for classes that inherit/implement classes/interfaces, then make sure you clean out stale assemblies if you get this error pertaining to one of your own assemblies.

The scenario would be something like:

  1. Assembly A loads all assemblies in some folder
  2. Assembly B in this folder is stale, but references assembly C
  3. Assembly C exists, but namespaces, class names or some other detail might have changed in the time that has passed since assembly B became stale (in my case a namespace was changed through a refactoring process)

In short: A ---loads--> B (stale) ---references---> C

If this happens, the only telltale sign is the namespace and classname in the error message. Examine it closely. If you can't find it anywhere in your solution, you are likely trying to load a stale assembly.

Convert date to UTC using moment.js

I use this method and it works. ValueOf does not work for me.

moment.utc(yourDate).format()

How to pass parameters to a partial view in ASP.NET MVC?

You need to create a view model. Something like this should do...

public class FullNameViewModel
{
     public string FirstName { get; set; }
     public string LastName { get; set; }

     public FullNameViewModel() { } 

     public FullNameViewModel(string firstName, string lastName)
     {
          this.FirstName = firstName;
          this.LastName = lastName;
     }

}

then from your action result pass the model

return View("FullName", new FullNameViewModel("John", "Doe"));

and you will be able to access @Model.FirstName and @Model.LastName accordingly.

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

Because it's not actually a dictionary; it's another mapping type that looks like a dictionary. Use type() to verify. Pass it to dict() to get a real dictionary from it.

How to set css style to asp.net button?

The answer you mentioned will be applied to all buttons. You should try this:

input[type="submit"].someclass {
    //somestyle}

And make sure you add this to your button:

CssClass="someclass"

How to change package name in android studio?

First click once on your package and then click setting icon on Android Studio.

Close/Unselect Compact Empty Middle Packages

Then, right click your package and rename it.

Thats all.

enter image description here

Reading DataSet

DataSet resembles database. DataTable resembles database table, and DataRow resembles a record in a table. If you want to add filtering or sorting options, you then do so with a DataView object, and convert it back to a separate DataTable object.

If you're using database to store your data, then you first load a database table to a DataSet object in memory. You can load multiple database tables to one DataSet, and select specific table to read from the DataSet through DataTable object. Subsequently, you read a specific row of data from your DataTable through DataRow. Following codes demonstrate the steps:

SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();

da.SelectCommand = new SqlCommand(@"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];

foreach (DataRow dr in dt.Rows)
{
    MessageBox.Show(dr["Column1"].ToString());
}

To read a specific cell in a row:

int rowNum // row number
string columnName = "DepartureTime";  // database table column name
dt.Rows[rowNum][columnName].ToString();

Matplotlib: ValueError: x and y must have same first dimension

Changing your lists to numpy arrays will do the job!!

import matplotlib.pyplot as plt
from scipy import stats
import numpy as np 

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15

plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()

enter image description here

BehaviorSubject vs Observable?

BehaviorSubject vs Observable : RxJS has observers and observables, Rxjs offers a multiple classes to use with data streams, and one of them is a BehaviorSubject.

Observables : Observables are lazy collections of multiple values over time.

BehaviorSubject:A Subject that requires an initial value and emits its current value to new subscribers.

 // RxJS v6+
import { BehaviorSubject } from 'rxjs';

const subject = new BehaviorSubject(123);

//two new subscribers will get initial value => output: 123, 123
subject.subscribe(console.log);
subject.subscribe(console.log);

//two subscribers will get new value => output: 456, 456
subject.next(456);

//new subscriber will get latest value (456) => output: 456
subject.subscribe(console.log);

//all three subscribers will get new value => output: 789, 789, 789
subject.next(789);

// output: 123, 123, 456, 456, 456, 789, 789, 789

How to change font-size of a tag using inline css?

You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style attribute. Apparently, it has to be one using the !important specifier, which generally indicates poor logic and structure in styling.

Primarily, modify the style.css file so that it does not use !important. Failing this, add !important to the rule in style attribute. But you should aim at reducing the use of !important, not increasing it.

delete image from folder PHP

<?php

    require 'database.php';

    $id = $_GET['id'];

    $image = "SELECT * FROM slider WHERE id = '$id'";
    $query = mysqli_query($connect, $image);
    $after = mysqli_fetch_assoc($query);

    if ($after['image'] != 'default.png') {
        unlink('../slider/'.$after['image']);
    }

    $delete = "DELETE FROM slider WHERE id = $id";
    $query = mysqli_query($connect, $delete);

    if ($query) {
        header('location: slider.php');
    }

?>

getting the index of a row in a pandas apply function

Either:

1. with row.name inside the apply(..., axis=1) call:

df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'], index=['x','y'])

   a  b  c
x  1  2  3
y  4  5  6

df.apply(lambda row: row.name, axis=1)

x    x
y    y

2. with iterrows() (slower)

DataFrame.iterrows() allows you to iterate over rows, and access their index:

for idx, row in df.iterrows():
    ...

Can I catch multiple Java exceptions in the same catch clause?

A cleaner (but less verbose, and perhaps not as preferred) alternative to user454322's answer on Java 6 (i.e., Android) would be to catch all Exceptions and re-throw RuntimeExceptions. This wouldn't work if you're planning on catching other types of exceptions further up the stack (unless you also re-throw them), but will effectively catch all checked exceptions.

For instance:

try {
    // CODE THAT THROWS EXCEPTION
} catch (Exception e) {
    if (e instanceof RuntimeException) {
        // this exception was not expected, so re-throw it
        throw e;
    } else {
        // YOUR CODE FOR ALL CHECKED EXCEPTIONS
    } 
}

That being said, for verbosity, it might be best to set a boolean or some other variable and based on that execute some code after the try-catch block.

Find methods calls in Eclipse project

Right click on method and click on Open call Hierarchy

eclipse right click call hierarchy

How to export SQL Server 2005 query to CSV

In Sql Server 2012 - Management Studio:

Solution 1:

Execute the query

Right click the Results Window

Select Save Results As from the menu

Select CSV

Solution 2:

Right click on database

Select Tasks, Export Data

Select Source DB

Select Destination: Flat File Destination

Pick a file name

Select Format - Delimited

Choose a table or write a query

Pick a Column delimiter

Note: You can pick a Text qualifier that will delimit your text fields, such as quotes.

If you have a field with commas, don't use you use comma as a delimiter, because it does not escape commas. You can pick a column delimiter such as Vertical Bar: | instead of comma, or a tab character. Otherwise, write a query that escapes your commas or delimits your varchar field.

The escape character or text qualifier you need to use depends on your requirements.

Installation of VB6 on Windows 7 / 8 / 10

I've installed and use VB6 for legacy projects many times on Windows 7.

What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.

Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721

Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

Besides all above solutions, check if you have the "id" or any custom defined parameter in the DELETE method is matching the route config.

public void Delete(int id)
{
    //some code here
}

If you hit with repeated 405 errors better reset the method signature to default as above and try.

The route config by default will look for id in the URL. So the parameter name id is important here unless you change the route config under the App_Start folder.

You may change the data type of the id though.

For example the method below should work just fine:

public void Delete(string id)
{
    //some code here
}

Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.

DELETE http://{url}/{action}/{id}

Example:

DELETE http://localhost/item/1

Hope it helps.

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

How to call a method daily, at specific time, in C#?

I know this is old but how about this:

Build a timer to fire at startup that calculates time to next run time. At the first call of the runtime, cancel the first timer and start a new daily timer. change daily to hourly or whatever you want the periodicity to be.

Update statement with inner join on Oracle

It works fine oracle

merge into table1 t1
using (select * from table2) t2
on (t1.empid = t2.empid)
when matched then update set t1.salary = t2.salary

Is there a way I can retrieve sa password in sql server 2005

Wait!

There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password


How to use the tool to retrieve the password

To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer

"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user

name for which you want to retrieve password.Copy the password field (Hashed Code) and

paste here (in Hashed code Field) and click on start button to retrieve

I checked the tool on SQLServer 2000 and it's working fine.

How do I get a background location update every n minutes in my iOS application?

I did this in an application I'm developing. The timers don't work when the app is in the background but the app is constantly receiving the location updates. I read somewhere in the documentation (i can't seem to find it now, i'll post an update when i do) that a method can be called only on an active run loop when the app is in the background. The app delegate has an active run loop even in the bg so you dont need to create your own to make this work. [Im not sure if this is the correct explanation but thats how I understood from what i read]

First of all, add the location object for the key UIBackgroundModes in your app's info.plist. Now, what you need to do is start the location updates anywhere in your app:

    CLLocationManager locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;//or whatever class you have for managing location
    [locationManager startUpdatingLocation];

Next, write a method to handle the location updates, say -(void)didUpdateToLocation:(CLLocation*)location, in the app delegate. Then implement the method locationManager:didUpdateLocation:fromLocation of CLLocationManagerDelegate in the class in which you started the location manager (since we set the location manager delegate to 'self'). Inside this method you need to check if the time interval after which you have to handle the location updates has elapsed. You can do this by saving the current time every time. If that time has elapsed, call the method UpdateLocation from your app delegate:

NSDate *newLocationTimestamp = newLocation.timestamp;
NSDate *lastLocationUpdateTiemstamp;

int locationUpdateInterval = 300;//5 mins

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (userDefaults) {

        lastLocationUpdateTiemstamp = [userDefaults objectForKey:kLastLocationUpdateTimestamp];

        if (!([newLocationTimestamp timeIntervalSinceDate:lastLocationUpdateTiemstamp] < locationUpdateInterval)) {
            //NSLog(@"New Location: %@", newLocation);
            [(AppDelegate*)[UIApplication sharedApplication].delegate didUpdateToLocation:newLocation];
            [userDefaults setObject:newLocationTimestamp forKey:kLastLocationUpdateTimestamp];
        }
    }
}

This will call your method every 5 mins even when your app is in background. Imp: This implementation drains the battery, if your location data's accuracy is not critical you should use [locationManager startMonitoringSignificantLocationChanges]

Before adding this to your app, please read the Location Awareness Programming Guide

Why doesn't Java allow overriding of static methods?

Method overriding is made possible by dynamic dispatching, meaning that the declared type of an object doesn't determine its behavior, but rather its runtime type:

Animal lassie = new Dog();
lassie.speak(); // outputs "woof!"
Animal kermit = new Frog();
kermit.speak(); // outputs "ribbit!"

Even though both lassie and kermit are declared as objects of type Animal, their behavior (method .speak()) varies because dynamic dispatching will only bind the method call .speak() to an implementation at run time - not at compile time.

Now, here's where the static keyword starts to make sense: the word "static" is an antonym for "dynamic". So the reason why you can't override static methods is because there is no dynamic dispatching on static members - because static literally means "not dynamic". If they dispatched dynamically (and thus could be overriden) the static keyword just wouldn't make sense anymore.

How do I turn off autocommit for a MySQL client?

It looks like you can add it to your ~/.my.cnf, but it needs to be added as an argument to the init-command flag in your [client] section, like so:

[client]
init-command='set autocommit=0'

I keep getting "Uncaught SyntaxError: Unexpected token o"

Make sure your JSON file does not have any trailing characters before or after. Maybe an unprintable one? You may want to try this way:

[{"english":"bag","kana":"kaban","kanji":"K"},{"english":"glasses","kana":"megane","kanji":"M"}]

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

Latex - Change margins of only a few pages

Use the "geometry" package and write \newgeometry{left=3cm,bottom=0.1cm} where you want to change your margins. When you want to reset your margins, you write \restoregeometry.

Java - get the current class name?

I'm assuming this is happening for an anonymous class. When you create an anonymous class you actually create a class that extends the class whose name you got.

The "cleaner" way to get the name you want is:

If your class is an anonymous inner class, getSuperClass() should give you the class that it was created from. If you created it from an interface than you're sort of SOL because the best you can do is getInterfaces() which might give you more than one interface.

The "hacky" way is to just get the name with getClassName() and use a regex to drop the $1.

How to read attribute value from XmlNode in C#?

if all you need is the names, use xpath instead. No need to do the iteration yourself and check for null.

string xml = @"
<root>
    <Employee name=""an"" />
    <Employee name=""nobyd"" />
    <Employee/>
</root>
";

var doc = new XmlDocument();

//doc.Load(path);
doc.LoadXml(xml);

var names = doc.SelectNodes("//Employee/@name");

Builder Pattern in Effective Java

You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.

public class NutritionalFacts {
    private final int sodium;
    private final int fat;
    private final int carbo;

    public int getSodium(){
        return sodium;
    }

    public int getFat(){
        return fat;
    }

    public int getCarbo(){
        return carbo;
    }

    public static class Builder {
        private int sodium;
        private int fat;
        private int carbo;

        public Builder sodium(int s) {
            this.sodium = s;
            return this;
        }

        public Builder fat(int f) {
            this.fat = f;
            return this;
        }

        public Builder carbo(int c) {
            this.carbo = c;
            return this;
        }

        public NutritionalFacts build() {
            return new NutritionalFacts(this);
        }
    }

    private NutritionalFacts(Builder b) {
        this.sodium = b.sodium;
        this.fat = b.fat;
        this.carbo = b.carbo;
    }
}

And now you can set the properties as follows:

NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
fat(5).build();

How to show an empty view with a RecyclerView?

Here is my class for show empty view, retry view (when load api failed) and loading progress for RecyclerView

public class RecyclerViewEmptyRetryGroup extends RelativeLayout {
    private RecyclerView mRecyclerView;
    private LinearLayout mEmptyView;
    private LinearLayout mRetryView;
    private ProgressBar mProgressBar;
    private OnRetryClick mOnRetryClick;

    public RecyclerViewEmptyRetryGroup(Context context) {
        this(context, null);
    }

    public RecyclerViewEmptyRetryGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecyclerViewEmptyRetryGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onViewAdded(View child) {
        super.onViewAdded(child);
        if (child.getId() == R.id.recyclerView) {
            mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            return;
        }
        if (child.getId() == R.id.layout_empty) {
            mEmptyView = (LinearLayout) findViewById(R.id.layout_empty);
            return;
        }
        if (child.getId() == R.id.layout_retry) {
            mRetryView = (LinearLayout) findViewById(R.id.layout_retry);
            mRetryView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mRetryView.setVisibility(View.GONE);
                    mOnRetryClick.onRetry();
                }
            });
            return;
        }
        if (child.getId() == R.id.progress_bar) {
            mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        }
    }

    public void loading() {
        mRetryView.setVisibility(View.GONE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.VISIBLE);
    }

    public void empty() {
        mEmptyView.setVisibility(View.VISIBLE);
        mRetryView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public void retry() {
        mRetryView.setVisibility(View.VISIBLE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public void success() {
        mRetryView.setVisibility(View.GONE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    public void setOnRetryClick(OnRetryClick onRetryClick) {
        mOnRetryClick = onRetryClick;
    }

    public interface OnRetryClick {
        void onRetry();
    }
}

activity_xml

<...RecyclerViewEmptyRetryGroup
        android:id="@+id/recyclerViewEmptyRetryGroup">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"/>

        <LinearLayout
            android:id="@+id/layout_empty">
            ...
        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_retry">
            ...
        </LinearLayout>

        <ProgressBar
            android:id="@+id/progress_bar"/>

</...RecyclerViewEmptyRetryGroup>

enter image description here

The source is here https://github.com/PhanVanLinh/AndroidRecyclerViewWithLoadingEmptyAndRetry

How to determine whether a year is a leap year?

As a one-liner function:

def is_leap_year(year):
    """Determine whether a year is a leap year."""

    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

It's similar to the Mark's answer, but short circuits at the first test (note the parenthesis).

Alternatively, you can use the standard library's calendar.isleap, which has exactly the same implementation:

from calendar import isleap
print(isleap(1900))

No module named _sqlite3

This is what I did to get it to work.

I am using pythonbrew(which is using pip) with python 2.7.5 installed.

I first did what Zubair(above) said and ran this command:

sudo apt-get install libsqlite3-dev

Then I ran this command:

pip install pysqlite

This fixed the database problem and I got confirmation of this when I ran:

python manager.py syncdb

jquery, selector for class within id

You can use the class selector along with descendant selector

$("#my_id .my_class")

Environment Variable with Maven

You can just pass it on the command line, as

mvn -DmyVariable=someValue install

[Update] Note that the order of parameters is significant - you need to specify any options before the command(s).[/Update]

Within the POM file, you may refer to system variables (specified on the command line, or in the pom) as ${myVariable}, and environment variables as ${env.myVariable}. (Thanks to commenters for the correction.)

Update2

OK, so you want to pass your system variable to your tests. If - as I assume - you use the Surefire plugin for testing, the best is to specify the needed system variable(s) within the pom, in your plugins section, e.g.

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            ...
            <configuration>
                ...
                <systemPropertyVariables>
                    <WSNSHELL_HOME>conf</WSNSHELL_HOME>
                </systemPropertyVariables>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>

Datatable vs Dataset

One major difference is that DataSets can hold multiple tables and you can define relationships between those tables.

If you are only returning a single result set though I would think a DataTable would be more optimized. I would think there has to be some overhead (granted small) to offer the functionality a DataSet does and keep track of multiple DataTables.

Concat a string to SELECT * MySql

You cannot do this on multiple fields. You can also look for this.

tmux status bar configuration

Do C-b, :show which will show you all your current settings. /green, nnn will find you which properties have been set to green, the default. Do C-b, :set window-status-bg cyan and the bottom bar should change colour.

List available colours for tmux

You can tell more easily by the titles and the colours as they're actually set in your live session :show, than by searching through the man page, in my opinion. It is a very well-written man page when you have the time though.

If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf with a line like set window-status-bg -g cyan. Here's mine: https://gist.github.com/9083598

href image link download on click

Image download with using image clicking!

I did this simple code!:)

<html>
<head>
<title> Download-Button </title>
</head>
<body>
<p> Click the image ! You can download! </p>
<a download="logo.png" href="http://localhost/folder/img/logo.png" title="Logo title">
<img alt="logo" src="http://localhost/folder/img/logo.png">
</a>
</body>
</html>

Retrieve Button value with jQuery

As a button value is an attribute you need to use the .attr() method in jquery. This should do it

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {
            alert($(this).attr("value"));
        });
    });
</script>

You can also use attr to set attributes, more info in the docs.

This only works in JQuery 1.6+. See postpostmodern's answer for older versions.

Passing environment-dependent variables in webpack

I investigated a couple of options on how to set environment-specific variables and ended up with this:

I have 2 webpack configs currently:

webpack.production.config.js

new webpack.DefinePlugin({
  'process.env':{
    'NODE_ENV': JSON.stringify('production'),
    'API_URL': JSON.stringify('http://localhost:8080/bands')
  }
}),

webpack.config.js

new webpack.DefinePlugin({
  'process.env':{
    'NODE_ENV': JSON.stringify('development'),
    'API_URL': JSON.stringify('http://10.10.10.10:8080/bands')
  }
}),

In my code I get the value of API_URL in this (brief) way:

const apiUrl = process.env.API_URL;

EDIT 3rd of Nov, 2016

Webpack docs has an example: https://webpack.js.org/plugins/define-plugin/#usage

new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true),
    VERSION: JSON.stringify("5fa3b9"),
    BROWSER_SUPPORTS_HTML5: true,
    TWO: "1+1",
    "typeof window": JSON.stringify("object")
})

With ESLint you need to specifically allow undefined variables in code, if you have no-undef rule on. http://eslint.org/docs/rules/no-undef like this:

/*global TWO*/
console.log('Running App version ' + TWO);

EDIT 7th of Sep, 2017 (Create-React-App specific)

If you're not into configuring too much, check out Create-React-App: Create-React-App - Adding Custom Environment Variables. Under the hood CRA uses Webpack anyway.

Output (echo/print) everything from a PHP Array

 //@parram $data-array,$d-if true then die by default it is false
 //@author Your name

 function p($data,$d = false){

     echo "<pre>"; 
         print_r($data);
     echo "</pre>"; 

     if($d == TRUE){
        die();
     } 
} // END OF FUNCTION

Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function

In your case you can use in this way....

while($row = mysql_fetch_array($result)){
    p($row); // Use this function if you use above function in your page.
}

Submit form using AJAX and jQuery

There is a nice form plugin that allows you to send an HTML form asynchroniously.

$(document).ready(function() { 
    $('#myForm1').ajaxForm(); 
});

or

$("select").change(function(){
    $('#myForm1').ajaxSubmit();
});

to submit the form immediately

Find out if string ends with another string in C++

Check if str has suffix, using below:

/*
Check string is end with extension/suffix
*/
int strEndWith(char* str, const char* suffix)
{
  size_t strLen = strlen(str);
  size_t suffixLen = strlen(suffix);
  if (suffixLen <= strLen) {
    return strncmp(str + strLen - suffixLen, suffix, suffixLen) == 0;
  }
  return 0;
}

How to use a decimal range() step value?

This one liner will not clutter your code. The sign of the step parameter is important.

def frange(start, stop, step):
    return [x*step+start for x in range(0,round(abs((stop-start)/step)+0.5001),
        int((stop-start)/step<0)*-2+1)]

How to properly add 1 month from now to current date in moment.js

You could try

moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')

Build error: You must add a reference to System.Runtime

@PeterMajeed's comment in the accepted answer helped me out with a related problem. I am not using the portable library, but have the same build error on a fresh Windows Server 2012 install, where I'm running TeamCity.

Installing the Microsoft .NET Framework 4.5.1 Developer Pack took care of the issue (after having separately installed the MS Build Tools).

How do I convert an enum to a list in C#?

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public static List<NameValue> EnumToList<T>()
{
    var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>()); 
    var array2 = Enum.GetNames(typeof(T)).ToArray<string>(); 
    List<NameValue> lst = null;
    for (int i = 0; i < array.Length; i++)
    {
        if (lst == null)
            lst = new List<NameValue>();
        string name = array2[i];
        T value = array[i];
        lst.Add(new NameValue { Name = name, Value = value });
    }
    return lst;
}

Convert Enum To a list more information available here.

How to Query Database Name in Oracle SQL Developer?

I know this is an old thread but you can also get some useful info from the V$INSTANCE view as well. the V$DATABASE displays info from the control file, the V$INSTANCE view displays state of the current instance.

Vertical divider doesn't work in Bootstrap 3

I think this will bring it back using 3.0

.navbar .divider-vertical {
    height: 50px;
    margin: 0 9px;
    border-right: 1px solid #ffffff;
    border-left: 1px solid #f2f2f2;
}

.navbar-inverse .divider-vertical {
    border-right-color: #222222;
    border-left-color: #111111;
}

@media (max-width: 767px) {
    .navbar-collapse .nav > .divider-vertical {
        display: none;
     }
}

Vertical align in bootstrap table

As of Bootstrap 4 this is now much easier using the included utilities instead of custom CSS. You simply have to add the class align-middle to the td-element:

<table>
  <tbody>
    <tr>
      <td class="align-baseline">baseline</td>
      <td class="align-top">top</td>
      <td class="align-middle">middle</td>
      <td class="align-bottom">bottom</td>
      <td class="align-text-top">text-top</td>
      <td class="align-text-bottom">text-bottom</td>
    </tr>
  </tbody>
</table>

Is it possible to use JavaScript to change the meta-tags of the page?

It should be possible like this (or use jQuery like $('meta[name=author]').attr("content");):

<html>
<head>
<title>Meta Data</title>
<meta name="Author" content="Martin Webb">
<meta name="Author" content="A.N. Other">
<meta name="Description" content="A sample html file for extracting meta data">
<meta name="Keywords" content="JavaScript, DOM, W3C">

</head>

<body>
<script language="JavaScript"><!--
if (document.getElementsByName) {
  var metaArray = document.getElementsByName('Author');
  for (var i=0; i<metaArray.length; i++) {
    document.write(metaArray[i].content + '<br>');
  }

  var metaArray = document.getElementsByName('Description');
  for (var i=0; i<metaArray.length; i++) {
    document.write(metaArray[i].content + '<br>');
  }

  var metaArray = document.getElementsByName('Keywords');
  for (var i=0; i<metaArray.length; i++) {
    document.write(metaArray[i].content + '<br>');
  }
}
//--></script>
</body>

</html>

Difference between "process.stdout.write" and "console.log" in node.js?

I know this is a very old question but I didn't see anybody talking about the main difference between process.stdout.write and console.log and I just want to mention it.

As Mauvis Leford and TK-421 pointed out, the console.log adds a line-break character at the end of the line (\n) but that's not all what it does.

The code has not changed since at least 0.10.X version and now we have a a 5.X version.

Here is the code:

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

As you can see, there is a part that says .apply(this, arguments) and that makes a big difference on functionality. It is easier to explain that with examples:

process.stdout.write has a very basic functionality, you can just write something in there, like this:

process.stdout.write("Hello World\n"); 

If you don't put the break line at the end you will get a weird character after your string, something like this:

process.stdout.write("Hello World"); //Hello World% 

(I think that means something like "the end of the program", so you will see it only if you process.stdout.write was used at the end of your file and you didn't add the break line)

On the other hand, console.log can do more.

  1. You can use it in the same way

    console.log("Hello World"); //You don't need the break line here because it was already formated and also that weird character did disappear

  2. You can write more than one string

    console.log("Hello", "World");

  3. You can make associations

    console.log("Hello %s", "World") //Useful when "World" is inside a variable

An that's it, that added functionality is given thanks to the util.format.apply part (I could talk a lot about what exactly this does but you get my point, you can read more here).

I hope somebody find this information useful.

How does cookie based authentication work?

Cookie-Based Authentication

Cookies based Authentication works normally in these 4 steps-

  1. The user provides a username and password in the login form and clicks Log In.
  2. After the request is made, the server validate the user on the backend by querying in the database. If the request is valid, it will create a session by using the user information fetched from the database and store them, for each session a unique id called session Id is created ,by default session Id is will be given to client through the Browser.
  3. Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.

  4. Once a user logs out of the app, the session is destroyed both client-side and server-side.

Selecting multiple classes with jQuery

// Due to this Code ): Syntax problem.    
$('.myClass', '.myOtherClass').removeClass('theclass'); 

According to jQuery documentation: https://api.jquery.com/multiple-selector/

When can select multiple classes in this way:

jQuery(“selector1, selector2, selectorN”) // double Commas. // IS valid.
jQuery('selector1, selector2, selectorN') // single Commas. // Is valid.

by enclosing all the selectors in a single '...' ' or double commas, "..."

So in your case the correct way to call multiple classes is:

$('.myClass', '.myOtherClass').removeClass('theclass'); // your Code // Invalid.
$('.myClass , .myOtherClass').removeClass('theclass');  // Correct Code // Is valid.

Check if Key Exists in NameValueCollection

Yes, you can use Linq to check the AllKeys property:

using System.Linq;
...
collection.AllKeys.Contains(key);

However a Dictionary<string, string[]> would be far more suited to this purpose, perhaps created via an extension method:

public static void Dictionary<string, string[]> ToDictionary(this NameValueCollection collection) 
{
    return collection.Cast<string>().ToDictionary(key => key, key => collection.GetValues(key));
}

var dictionary = collection.ToDictionary();
if (dictionary.ContainsKey(key))
{
   ...
}

Current time formatting with Javascript

2017 update: use toLocaleDateString and toLocaleTimeString to format dates and times. The first parameter passed to these methods is a locale value, such as en-us. The second parameter, where present, specifies formatting options, such as the long form for the weekday.

_x000D_
_x000D_
let date = new Date();  _x000D_
let options = {  _x000D_
    weekday: "long", year: "numeric", month: "short",  _x000D_
    day: "numeric", hour: "2-digit", minute: "2-digit"  _x000D_
};  _x000D_
_x000D_
console.log(date.toLocaleTimeString("en-us", options)); 
_x000D_
_x000D_
_x000D_

Output : Wednesday, Oct 25, 2017, 8:19 PM

Please refer below link for more details.

Date and Time Strings (JavaScript)

How do I prevent site scraping?

Sorry, it's really quite hard to do this...

I would suggest that you politely ask them to not use your content (if your content is copyrighted).

If it is and they don't take it down, then you can take furthur action and send them a cease and desist letter.

Generally, whatever you do to prevent scraping will probably end up with a more negative effect, e.g. accessibility, bots/spiders, etc.

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

This function check for empty object {},empty array [], null, undefined and blank string ""

function isEmpty(val) {
  //check for empty object {}, array []
  if (val !== null && typeof val === 'object') {
    if (Object.keys(obj).length === 0) {
      return true;
    }
  }
  //check for undefined, null and "" 
  else if (val == null || val === "") {
    return true;
  }
  return false;
}

var val={};
isEmpty(val) -> true
val=[];
isEmpty(val) -> true
isEmpty(undefined) -> true
isEmpty(null) -> true
isEmpty("") -> true
isEmpty(false) -> false
isEmpty(0) -> false

Read only file system on Android

This worked for me

#Mount as ReadOnly

su -c "mount -o rw,remount /system"
# Change Permission for file
su -c "chmod 777 /system/build.prop" 
#Edit the file to add the property
su -c "busybox vi /system/build.prop"
# Add now
service.adb.tcp.port=5678

# Reset old permissions
su -c "chmod 644 /system/build.prop"

# Mount as readonly again once done
su -c "mount -o ro,remount /system"

Apache error: _default_ virtualhost overlap on port 443

On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:

{apache_dir}/conf.d/ssl.conf

This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.

To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf or update it to your own settings.

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

How can I truncate a string to the first 20 words in PHP?

With triple dots:

function limitWords($text, $limit) {
    $word_arr = explode(" ", $text);

    if (count($word_arr) > $limit) {
        $words = implode(" ", array_slice($word_arr , 0, $limit) ) . ' ...';
        return $words;
    }

    return $text;
}

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

My freely available memory profiler MemPro allows you to compare 2 snapshots and gives stack traces for all of the allocations.

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

Creating a copy of a database in PostgreSQL

If you want to copy whole schema you can make a pg_dump with following command:

pg_dump -h database.host.com -d database_name -n schema_name -U database_user --password

And when you want to import that dump, you can use:

psql "host=database.host.com user=database_user password=database_password dbname=database_name options=--search_path=schema_name" -f sql_dump_to_import.sql

More info about connection strings: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING

Or then just combining it in one liner:

pg_dump -h database.host.com -d postgres -n schema_name -U database_user --password | psql "host=database.host.com user=database_user password=database_password dbname=database_name options=--search_path=schema_name”

phpinfo() - is there an easy way for seeing it?

From your command line you can run..

php -i

I know it's not the browser window, but you can't see the phpinfo(); contents without making the function call. Obviously, the best approach would be to have a phpinfo script in the root of your web server directory, that way you have access to it at all times via http://localhost/info.php or something similar (NOTE: don't do this in a production environment or somewhere that is publicly accessible)

EDIT: As mentioned by binaryLV, its quite common to have two versions of a php.ini per installation. One for the command line interface (CLI) and the other for the web server interface. If you want to see phpinfo output for your web server make sure you specify the ini file path, for example...

php -c /etc/php/apache2/php.ini -i 

"CAUTION: provisional headers are shown" in Chrome debugger

For chrome v72+ what solved it for me was only this:

go to chrome://flags/ and disable this 3 flags

  • Disable site isolation
  • Enable network service
  • Runs network service in-process

enter image description here

or you can do it from command line :

chrome --disable-site-isolation-trials --disable-features=NetworkService,NetworkServiceInProcess

why this happen?

It seems that Google is refactoring their Chromium engine into modular structure, where different services will be separated into stand-alone modules and processes. They call this process servicification. Network service is the first step, Ui service, Identity service and Device service are coming up. Google provides the official information at the Chromium project site.

is it dangerous to change that?

An example is networking: once we have a network service we can choose to run it out of process for better stability/security, or in-process if we're resource constrained. source

After installation of Gulp: “no command 'gulp' found”

I'm on lubuntu 19.10

I've used combination of previous answers, and didn't tweak the $PATH.

  1. npm uninstall --global gulp gulp-cli This removes any package if they are already there.
  2. sudo npm install --global gulp-cli Reinstall it as root user.

If you want to do copy and paste

npm uninstall --global gulp gulp-cli && sudo npm install --global gulp-cli 

should work

I guess --global is unnecessary here as it's installed using sudo, but I've used it just in case.

Inserting HTML into a div

I using "+" (plus) to insert div to html :

document.getElementById('idParent').innerHTML += '<div id="idChild"> content html </div>';

Hope this help.

What is meant with "const" at end of function declaration?

Similar to this question.

In essence it means that the method Bar will not modify non mutable member variables of Foo.

What does "Error: object '<myvariable>' not found" mean?

While executing multiple lines of code in R, you need to first select all the lines of code and then click on "Run". This error usually comes up when we don't select our statements and click on "Run".

How to check if a character in a string is a digit or letter

You could use the existing methods from the Character class. Take a look at the docs:

http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)

So, you could do something like this...

String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) { 
    ... 
} else if (Character.isLetter(c)) {
    ...
}
...

If you ever want to know exactly how this is implemented, you could always look at the Java source code.

Split array into chunks of N length

It could be something like that:

_x000D_
_x000D_
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

var arrays = [], size = 3;
    
while (a.length > 0)
  arrays.push(a.splice(0, size));

console.log(arrays);
_x000D_
_x000D_
_x000D_

See splice Array's method.

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

How do I pass environment variables to Docker containers?

If you have the environment variables in an env.sh locally and want to set it up when the container starts, you could try

COPY env.sh /env.sh
COPY <filename>.jar /<filename>.jar
ENTRYPOINT ["/bin/bash" , "-c", "source /env.sh && printenv && java -jar /<filename>.jar"]

This command would start the container with a bash shell (I want a bash shell since source is a bash command), sources the env.sh file(which sets the environment variables) and executes the jar file.

The env.sh looks like this,

#!/bin/bash
export FOO="BAR"
export DB_NAME="DATABASE_NAME"

I added the printenv command only to test that actual source command works. You should probably remove it when you confirm the source command works fine or the environment variables would appear in your docker logs.

How can I catch a ctrl-c event?

signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void my_handler(int s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{

   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

   pause();

   return 0;    
}

Merging multiple PDFs using iTextSharp in c#.net

I don't see this solution anywhere and supposedly ... according to one person, the proper way to do it is with copyPagesTo(). This does work I tested it. Your mileage may vary between city and open road driving. Goo luck.

    public static bool MergePDFs(List<string> lststrInputFiles, string OutputFile, out int iPageCount, out string strError)
    {
        strError = string.Empty;

        PdfWriter pdfWriter = new PdfWriter(OutputFile);
        PdfDocument pdfDocumentOut = new PdfDocument(pdfWriter);

        PdfReader pdfReader0 = new PdfReader(lststrInputFiles[0]);
        PdfDocument pdfDocument0 = new PdfDocument(pdfReader0);
        int iFirstPdfPageCount0 = pdfDocument0.GetNumberOfPages();
        pdfDocument0.CopyPagesTo(1, iFirstPdfPageCount0, pdfDocumentOut);
        iPageCount = pdfDocumentOut.GetNumberOfPages();

        for (int ii = 1; ii < lststrInputFiles.Count; ii++)
        {
            PdfReader pdfReader1 = new PdfReader(lststrInputFiles[ii]);
            PdfDocument pdfDocument1 = new PdfDocument(pdfReader1);
            int iFirstPdfPageCount1 = pdfDocument1.GetNumberOfPages();
            iPageCount += iFirstPdfPageCount1;
            pdfDocument1.CopyPagesTo(1, iFirstPdfPageCount1, pdfDocumentOut);
            int iFirstPdfPageCount00 = pdfDocumentOut.GetNumberOfPages();
        }

        pdfDocumentOut.Close();

        return true;
    }

keytool error Keystore was tampered with, or password was incorrect

From your description I assume you are on windows machine and your home is abc

So Now : Cause

When you run this command

keytool -genkey -alias tomcat -keyalg RSA

because you are not specifying an explicit keystore it will try to generate (and in your case as you are getting exception so to update) keystore C:\users\abc>.keystore and of course you need to provide old password for .keystore while I believe you are providing your version (a new one).

Solution

  1. Either delete .keystore from C:\users\abc> location and try the command

  2. or try following command which will create a new xyzkeystore:

    keytool -genkey -keystore xyzkeystore -alias tomcat -keyalg RSA

Note: -genkey is old now rather use -genkeypair althought both work equally.

IOS - How to segue programmatically using swift

If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:

performSegue(withIdentifier: "mySegueID", sender: nil)

For older versions:

performSegueWithIdentifier("mySegueID", sender: nil)

You could also do:

presentViewController(nextViewController, animated: true, completion: nil)

Or if you are in a Navigation controller:

self.navigationController?.pushViewController(nextViewController, animated: true)

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

You can specify the connection timeout within the SQL connection string, when you connect to the database, like so:

"Data Source=localhost;Initial Catalog=database;Connect Timeout=15"

On the server level, use MSSQLMS to view the server properties, and on the Connections page you can specify the default query timeout.

I'm not quite sure that queries keep on running after the client connection has closed. Queries should not take that long either, MSSQL can handle large databases, I've worked with GB's of data on it before. Run a performance profile on the queries, prehaps some well-placed indexes could speed it up, or rewriting the query could too.

Update: According to this list, SQL timeouts happen when waiting for attention acknowledgement from server:

Suppose you execute a command, then the command times out. When this happens the SqlClient driver sends a special 8 byte packet to the server called an attention packet. This tells the server to stop executing the current command. When we send the attention packet, we have to wait for the attention acknowledgement from the server and this can in theory take a long time and time out. You can also send this packet by calling SqlCommand.Cancel on an asynchronous SqlCommand object. This one is a special case where we use a 5 second timeout. In most cases you will never hit this one, the server is usually very responsive to attention packets because these are handled very low in the network layer.

So it seems that after the client connection times out, a signal is sent to the server to cancel the running query too.

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

C# to convert a string to a byte array:

public static byte[] StrToByteArray(string str)
{
   System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
   return encoding.GetBytes(str);
}

Android Overriding onBackPressed()

At first you must consider that if your activity which I called A extends another activity (B) and in both of

them you want to use onbackpressed function then every code you have in B runs in A too. So if you want to separate these you should separate them. It means that A should not extend B , then you can have onbackpressed separately for each of them.

C# code to validate email address

If you really and I mean really want to know if an email address is valid...ask the mail exchanger to prove it, no regex needed. I can provide the code if requested.

General steps are as follows: 1. does email address have a domain name part? (index of @ > 0) 2. using a DNS query ask if domain has a mail exchanger 3. open tcp connection to mail exchanger 4. using the smtp protocol, open a message to the server using the email address as the reciever 5. parse the server's response. 6. quit the message if you made it this far, everything is good.

This is as you can imagine, very expensive time wise and relies on smtp, but it does work.