Programs & Examples On #Word count

The word count is the number of words in a document or passage of text.

How to extract the nth word and count word occurrences in a MySQL string?

I don't think such a thing is possible. You can use SUBSTRING function to extract the part you want.

How can we dynamically allocate and grow an array

You allocate a new Array (double the capacity, for instance), and move all elements to it.

Basically you need to check if the wordCount is about to hit the wordList.size(), when it does, create a new array with twice the length of the previous one, and copy all elements to it (create an auxiliary method to do this), and assign wordList to your new array.

To copy the contents over, you could use System.arraycopy, but I'm not sure that's allowed with your restrictions, so you can simply copy the elements one by one:

public String[] createNewArray(String[] oldArray){
    String[] newArray = new String[oldArray.length * 2];
    for(int i = 0; i < oldArray.length; i++) {
        newArray[i] = oldArray[i];
    }

    return newArray;
}

Proceed.

Count the number of all words in a string

You can use str_match_all, with a regular expression that would identify your words. The following works with initial, final and duplicated spaces.

library(stringr)
s <-  "
  Day after day, day after day,
  We stuck, nor breath nor motion;
"
m <- str_match_all( s, "\\S+" )  # Sequences of non-spaces
length(m[[1]])

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Unobtrusive validation is enabled by default in new version of ASP.NET. Unobtrusive validation aims to decrease the page size by replacing the inline JavaScript for performing validation with a small JavaScript library that uses jQuery.

You can either disable it by editing web.config to include the following:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Or better yet properly configure it by modifying the Application_Start method in global.asax:

void Application_Start(object sender, EventArgs e) 
{
    RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
        new ScriptResourceDefinition
        {
            Path = "/~Scripts/jquery-2.1.1.min.js"
        }
    );
}

Page 399 of Beginning ASP.NET 4.5.1 in C# and VB provides a discussion on the benefit of unobtrusive validation and a walkthrough for configuring it.

For those looking for RouteConfig. It is added automatically when you make a new project in visual studio to the App_Code folder. The contents look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace @default
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
        }
    }
}

How to extract file name from path?

The simplest approach if you are sure the file physically exists on the disk:

Dim fileName, filePath As String
filePath = "C:\Documents\myfile.pdf"
fileName = Dir(filePath)

If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:

fileName = Mid(filePath, InStrRev(filePath, "\") + 1)

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Batch files: How to read a file?

A code that displays the contents of the myfile.txt file on the screen

set %filecontent%=0
type %filename% >> %filecontent%
echo %filecontent%

In Python, how do I use urllib to see if a website is 404 or 200?

For Python 3:

import urllib.request, urllib.error

url = 'http://www.google.com/asdfsf'
try:
    conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
    # Return code error (e.g. 404, 501, ...)
    # ...
    print('HTTPError: {}'.format(e.code))
except urllib.error.URLError as e:
    # Not an HTTP-specific error (e.g. connection refused)
    # ...
    print('URLError: {}'.format(e.reason))
else:
    # 200
    # ...
    print('good')

How to run mysql command on bash?

Use double quotes while using BASH variables.

mysql --user="$user" --password="$password" --database="$database" --execute="DROP DATABASE $user; CREATE DATABASE $database;"

BASH doesn't expand variables in single quotes.

Making a div vertically scrollable using CSS

For 100% viewport height use:

overflow: auto;
max-height: 100vh;

How to create exe of a console application

For .NET Core 2.2 you can publish the application and set the target to be a self-contained executable.

In Visual Studio right click your console application project. Select publish to folder and set the profile settings like so:

Visual Studio Publish Menu

You'll find your compiled code with the .exe in the publish folder.

Implement division with bit-wise operator

For integers:

public class Division {

    public static void main(String[] args) {
        System.out.println("Division: " + divide(100, 9));
    }

    public static int divide(int num, int divisor) {
        int sign = 1;
        if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
            sign = -1;

        return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
    }

    public static int divide(int num, int divisor, int sum) {
        if (sum > num) {
            return 0;
        }

        return 1 + divide(num, divisor, sum + divisor);
    }
}

Is it possible to create a temporary table in a View and drop it after select?

You can achieve what you are trying to do, using a Stored Procedure which returns a query result. Views are not suitable / developed for operations like this one.

String replacement in Objective-C

NSString objects are immutable (they can't be changed), but there is a mutable subclass, NSMutableString, that gives you several methods for replacing characters within a string. It's probably your best bet.

Pandas: convert dtype 'object' to int

Documenting the answer that worked for me based on the comment by @piRSquared.

I needed to convert to a string first, then an integer.

>>> df['purchase'].astype(str).astype(int)

How to install .MSI using PowerShell

#Variables
$computername = Get-Content 'M:\Applications\Powershell\comp list\Test.txt'
$sourcefile = "\\server\Apps\LanSchool 7.7\Windows\Student.msi"
#This section will install the software 
foreach ($computer in $computername) 
{
    $destinationFolder = "\\$computer\C$\download\LanSchool"
    #This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
    if (!(Test-Path -path $destinationFolder))
    {
        New-Item $destinationFolder -Type Directory
    }
    Copy-Item -Path $sourcefile -Destination $destinationFolder
    Invoke-Command -ComputerName $computer -ScriptBlock { & cmd /c "msiexec.exe /i c:\download\LanSchool\Student.msi" /qn ADVANCED_OPTIONS=1 CHANNEL=100}
}

I've searched all over for this myself and came up with zilch but have finally cobbled this working script together. It's working great! Thought I'd post here hopefully someone else can benefit. It pulls in a list of computers, copies the files down to the local machines and runs it. :) party on!

How to make a smaller RatingBar?

How to glue the code given here ...

Step-1. You need your own rating stars in res/drawable ...

A full star

Empty star

Step-2 In res/drawable you need ratingstars.xml as follow ...

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
          android:drawable="@drawable/star_empty" />
    <item android:id="@android:id/secondaryProgress"
          android:drawable="@drawable/star_empty" />
    <item android:id="@android:id/progress"
          android:drawable="@drawable/star" />
</layer-list>

Step-3 In res/values you need styles.xml as follow ...

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="foodRatingBar" parent="@android:style/Widget.RatingBar">
        <item name="android:progressDrawable">@drawable/ratingstars</item>
        <item name="android:minHeight">22dip</item>
        <item name="android:maxHeight">22dip</item>
    </style>
</resources>

Step-4 In your layout ...

<RatingBar 
      android:id="@+id/rtbProductRating"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:numStars="5"
      android:rating="3.5"
      android:isIndicator="false"
      style="@style/foodRatingBar"    
/>  

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

How to enable DataGridView sorting when user clicks on the column header?

your data grid needs to be bound to a sortable list in the first place.

Create this event handler:

    void MakeColumnsSortable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        //Add this as an event on DataBindingComplete
        DataGridView dataGridView = sender as DataGridView;
        if (dataGridView == null)
        {
            var ex = new InvalidOperationException("This event is for a DataGridView type senders only.");
            ex.Data.Add("Sender type", sender.GetType().Name);
            throw ex;
        }

        foreach (DataGridViewColumn column in dataGridView.Columns)
            column.SortMode = DataGridViewColumnSortMode.Automatic;
    }

And initialize the event of each of your datragrids like this:

        dataGridView1.DataBindingComplete += MakeColumnsSortable_DataBindingComplete;

Using :: in C++

The :: are used to dereference scopes.

const int x = 5;

namespace foo {
  const int x = 0;
}

int bar() {
  int x = 1;
  return x;
}

struct Meh {
  static const int x = 2;
}

int main() {
  std::cout << x; // => 5
  {
    int x = 4;
    std::cout << x; // => 4
    std::cout << ::x; // => 5, this one looks for x outside the current scope
  }
  std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
  std::cout << foo::x; // => 0, use the definition of x inside foo
  std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}

unrelated: cout and cin are not functions, but instances of stream objects.

EDIT fixed as Keine Lust suggested

Reading content from URL with Node.js

the data object is a buffer of bytes. Simply call .toString() to get human-readable code:

console.log( data.toString() );

reference: Node.js buffers

For loop example in MySQL

You can exchange this local variable for a global, it would be easier.

DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      SET @a = 0;
      simple_loop: LOOP
         SET @a=@a+1;
         select @a;
         IF @a=5 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

How to check which locks are held on a table

You can find details via the below script.

-- List all Locks of the Current Database 
SELECT TL.resource_type AS ResType 
      ,TL.resource_description AS ResDescr 
      ,TL.request_mode AS ReqMode 
      ,TL.request_type AS ReqType 
      ,TL.request_status AS ReqStatus 
      ,TL.request_owner_type AS ReqOwnerType 
      ,TAT.[name] AS TransName 
      ,TAT.transaction_begin_time AS TransBegin 
      ,DATEDIFF(ss, TAT.transaction_begin_time, GETDATE()) AS TransDura 
      ,ES.session_id AS S_Id 
      ,ES.login_name AS LoginName 
      ,COALESCE(OBJ.name, PAROBJ.name) AS ObjectName 
      ,PARIDX.name AS IndexName 
      ,ES.host_name AS HostName 
      ,ES.program_name AS ProgramName 
FROM sys.dm_tran_locks AS TL 
     INNER JOIN sys.dm_exec_sessions AS ES 
         ON TL.request_session_id = ES.session_id 
     LEFT JOIN sys.dm_tran_active_transactions AS TAT 
         ON TL.request_owner_id = TAT.transaction_id 
            AND TL.request_owner_type = 'TRANSACTION' 
     LEFT JOIN sys.objects AS OBJ 
         ON TL.resource_associated_entity_id = OBJ.object_id 
            AND TL.resource_type = 'OBJECT' 
     LEFT JOIN sys.partitions AS PAR 
         ON TL.resource_associated_entity_id = PAR.hobt_id 
            AND TL.resource_type IN ('PAGE', 'KEY', 'RID', 'HOBT') 
     LEFT JOIN sys.objects AS PAROBJ 
         ON PAR.object_id = PAROBJ.object_id 
     LEFT JOIN sys.indexes AS PARIDX 
         ON PAR.object_id = PARIDX.object_id 
            AND PAR.index_id = PARIDX.index_id 
WHERE TL.resource_database_id  = DB_ID() 
      AND ES.session_id <> @@Spid -- Exclude "my" session 
      -- optional filter  
      AND TL.request_mode <> 'S' -- Exclude simple shared locks 
ORDER BY TL.resource_type 
        ,TL.request_mode 
        ,TL.request_type 
        ,TL.request_status 
        ,ObjectName 
        ,ES.login_name;



--TSQL commands
SELECT 
       db_name(rsc_dbid) AS 'DATABASE_NAME',
       case rsc_type when 1 then 'null'
                             when 2 then 'DATABASE' 
                             WHEN 3 THEN 'FILE'
                             WHEN 4 THEN 'INDEX'
                             WHEN 5 THEN 'TABLE'
                             WHEN 6 THEN 'PAGE'
                             WHEN 7 THEN 'KEY'
                             WHEN 8 THEN 'EXTEND'
                             WHEN 9 THEN 'RID ( ROW ID)'
                             WHEN 10 THEN 'APPLICATION' end  AS 'REQUEST_TYPE',

       CASE req_ownertype WHEN 1 THEN 'TRANSACTION'
                                     WHEN 2 THEN 'CURSOR'
                                     WHEN 3 THEN 'SESSION'
                                     WHEN 4 THEN 'ExSESSION' END AS 'REQUEST_OWNERTYPE',

       OBJECT_NAME(rsc_objid ,rsc_dbid) AS 'OBJECT_NAME', 
       PROCESS.HOSTNAME , 
       PROCESS.program_name , 
       PROCESS.nt_domain , 
       PROCESS.nt_username , 
       PROCESS.program_name ,
       SQLTEXT.text 
FROM sys.syslockinfo LOCK JOIN 
     sys.sysprocesses PROCESS
  ON LOCK.req_spid = PROCESS.spid
CROSS APPLY sys.dm_exec_sql_text(PROCESS.SQL_HANDLE) SQLTEXT
where 1=1
and db_name(rsc_dbid) = db_name()



--Lock on a specific object
SELECT * 
FROM sys.dm_tran_locks
WHERE resource_database_id = DB_ID()
AND resource_associated_entity_id = object_id('Specific Table');

Limiting the number of characters per line with CSS

Depending on what font you're using you can set max-width on the paragraph with a calculated value. It will not be exact, but I've found that in most cases that does not matter.

p {
  max-width: calc(30em * 0.5);
}

The number you multiply with depends on what font it is, and how much a character takes up in a em square. More characters = less accurate.

How do I count the number of occurrences of a char in a String?

Try this method:

StringTokenizer stOR = new StringTokenizer(someExpression, "||");
int orCount = stOR.countTokens()-1;

jquery live hover

jQuery 1.4.1 now supports "hover" for live() events, but only with one event handler function:

$("table tr").live("hover",

function () {

});

Alternatively, you can provide two functions, one for mouseenter and one for mouseleave:

$("table tr").live({
    mouseenter: function () {

    },
    mouseleave: function () {

    }
});

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

I faced a bit of a different issue that returned the same error.

Skipping JaCoCo execution due to missing execution data /target/jacoco.exec

The truth is, this error is returned for many, many reasons. We experimented with the different solutions on Stack Overflow, but found this resource to be best. It tears down the many different potential reasons why Jacoco could be returning the same error.

For us, the solution was to add a prepare-agent to the configuration.

<execution>
   <id>default-prepare-agent</id>
   <goals>
       <goal>prepare-agent</goal>
   </goals>
</execution>

I would imagine most users will be experiencing it for different reasons, so take a look at the aforementioned resource!

GIT commit as different user without email / or only email

The

standard A U Thor <[email protected]> format

Seems to be defined as followed: ( as far as i know, with absolutely no warranty )

A U Thor = required username

  • The separation of the characters probably indicates that spaces are allowed, it could also be resembling initials.
  • The username has to be followed by 1 space, extra spaces will be truncated

<[email protected]> = optional email address

  • Must always be between < > signs.
  • The email address format isn't validated, you can pretty much enter whatever you want
  • Optional, you can omit this explicitly by using <>

If you don't use this exact syntax, git will search through the existing commits and use the first commit that contains your provided string.

Examples:

  1. Only user name

    Omit the email address explicitly:

    git commit --author="John Doe <>" -m "Impersonation is evil."
    
  2. Only email

    Technically this isn't possible. You can however enter the email address as the username and explicitly omit the email address. This doesn't seem like it's very useful. I think it would make even more sense to extract the user name from the email address and then use that as the username. But if you have to:

    git commit --author="[email protected] <>" -m "Impersonation is evil." 
    

I ran in to this when trying to convert a repository from mercurial to git. I tested the commands on msysgit 1.7.10.

What is the difference between java and core java?

"Core Java" is Oracle's definition and refers to subset of Java SE technologies.

This actually is not related to Java language itself but rather to set of some 'basic' packages. As a result it affects development approaches.

Currently Java Core is defined as a following set:

  • Basic technologies
  • CORBA
  • HotSpot VM
  • Java Naming and Directory Interface (JNDI)
  • Application monitoring and management
  • Tools API
  • XML

But as you probably understand even term 'basic technologies' is somewhat unclear ;-) so this is not so strict definition. Here is official page for this term:

Here is another picture illustrating Java Core API / technologies inside Java SE platform.

Declaring variable workbook / Worksheet vba

If the worksheet you want to retrieve exists at compile-time in ThisWorkbook (i.e. the workbook that contains the VBA code you're looking at), then the simplest and most consistently reliable way to refer to that Worksheet object is to use its code name:

Debug.Print Sheet1.Range("A1").Value

You can set the code name to anything you need (as long as it's a valid VBA identifier), independently of its "tab name" (which the user can modify at any time), by changing the (Name) property in the Properties toolwindow (F4):

Sheet1 properties

The Name property refers to the "tab name" that the user can change on a whim; the (Name) property refers to the code name of the worksheet, and the user can't change it without accessing the Visual Basic Editor.

VBA uses this code name to automatically declare a global-scope Worksheet object variable that your code gets to use anywhere to refer to that sheet, for free.

In other words, if the sheet exists in ThisWorkbook at compile-time, there's never a need to declare a variable for it - the variable is already there!


If the worksheet is created at run-time (inside ThisWorkbook or not), then you need to declare & assign a Worksheet variable for it.

Use the Worksheets property of a Workbook object to retrieve it:

Dim wb As Workbook
Set wb = Application.Workbooks.Open(path)

Dim ws As Worksheet
Set ws = wb.Worksheets(nameOrIndex)

Important notes...

  • Both the name and index of a worksheet can easily be modified by the user (accidentally or not), unless workbook structure is protected. If workbook isn't protected, you simply cannot assume that the name or index alone will give you the specific worksheet you're after - it's always a good idea to validate the format of the sheet (e.g. verify that cell A1 contains some specific text, or that there's a table with a specific name, that contains some specific column headings).

  • Using the Sheets collection contains Worksheet objects, but can also contain Chart instances, and a half-dozen more legacy sheet types that are not worksheets. Assigning a Worksheet reference from whatever Sheets(nameOrIndex) returns, risks throwing a type mismatch run-time error for that reason.

  • Not qualifying the Worksheets collection is an implicit ActiveWorkbook reference - meaning the Worksheets collection is pulling from whatever workbook is active at the moment the instruction is executing. Such implicit references make the code frail and bug-prone, especially if the user can navigate and interact with the Excel UI while code is running.

  • Unless you mean to activate a specific sheet, you never need to call ws.Activate in order to do 99% of what you want to do with a worksheet. Just use your ws variable instead.

Saving lists to txt file

@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.

PHP: HTML: send HTML select option attribute in POST

You will have to use JavaScript. The browser will only send the value of the selected option (so its not PHP's fault).

What your JS should do is hook into the form's submit event and create a hidden field with the value of the selected option's stud_name value. This hidden field will then get sent to the server.

That being said ... you shouldn't relay on the client to provide the correct data. You already know what stud_name should be for a given value on the server (since you are outputting it). So just apply the same logic when you are processing the form.

How to prevent the "Confirm Form Resubmission" dialog?

I was having this problem and added this JavaScript to the bottom of my page (read it at https://www.webtrickshome.com/faq/how-to-stop-form-resubmission-on-page-refresh) and it seemed to work. It seems much simpler a solution. Any drawbacks?

<script>
if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}
</script>

Thanks,

doug

How to add Options Menu to Fragment in Android

You need to use menu.clear() before inflating menus.

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

and

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

Using the slash character in Git branch name

It is possible to have hierarchical branch names (branch names with slash). For example in my repository I have such branch(es). One caveat is that you can't have both branch 'foo' and branch 'foo/bar' in repository.

Your problem is not with creating branch with slash in name.

$ git branch foo/bar
error: unable to resolve reference refs/heads/labs/feature: Not a directory
fatal: Failed to lock ref for update: Not a directory

The above error message talks about 'labs/feature' branch, not 'foo/bar' (unless it is a mistake in copy'n'paste, i.e you edited parts of session). What is the result of git branch or git rev-parse --symbolic-full-name HEAD?

Pass parameter to controller from @Html.ActionLink MVC 4

The problem must be with the value Model.Id which is null. You can confirm by assigning a value, e.g

@{         
     var blogPostId = 1;          
 }

If the error disappers, then u need to make sure that your model Id has a value before passing it to the view

How do I parse a YAML file in Ruby?

Here is the one liner i use, from terminal, to test the content of yml file(s):

$ ruby  -r yaml -r pp  -e 'pp YAML.load_file("/Users/za/project/application.yml")'
{"logging"=>
  {"path"=>"/var/logs/",
   "file"=>"TacoCloud.log",
   "level"=>
    {"root"=>"WARN", "org"=>{"springframework"=>{"security"=>"DEBUG"}}}}}

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

How do I programmatically click a link with javascript?

Many of the above methods have been deprecated. It is now recommended to use the constructor found here

function clickAnchorTag() {
    var event = document.createEvent('MouseEvent');
    event = new CustomEvent('click');
    var a = document.getElementById('nameOfID');
    a.dispatchEvent(event);
}

This will cause the anchor tag to be clicked, but it wont show if pop-up blockers are active so the user will need to allow pop-ups.

How do I find the install time and date of Windows?

Very simple way from PowerShell:

(Get-CimInstance -Class Win32_OperatingSystem).InstallDate

Extracted from: https://www.sysadmit.com/2019/10/windows-cuando-fue-instalado.html

jQuery detect if string contains something

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.

  1. Data can be passed as a string using the @ string literal, pass string value, one way binding.
  2. Data can be passed as an object using the = string literal, pass object, 2 ways binding.
  3. Data can be passed as a function the & string literal, calls external function, can pass data from directive to controller.

How can I view array structure in JavaScript with alert()?

A very basic approach is alert(arrayObj.join('\n')), which will display each array element in a row.

Using Position Relative/Absolute within a TD?

Contents of table cell, variable height, could be more than 60px;

<div style="position: absolute; bottom: 0px;">
    Notice
</div>

Php $_POST method to get textarea value

Use htmlspecialchars():

echo htmlspecialchars($_POST['contact_list']);

You can even improve your form processing by stripping all tags with strip_tags() and remove all white spaces with trim():

function processText($text) {
    $text = strip_tags($text);
    $text = trim($text);
    $text = htmlspecialchars($text);
    return $text;
}

echo processText($_POST['contact_list']);

What is difference between mutable and immutable String in java

What is difference between mutable and immutable String in java

immutable exist, mutable don't.

Postgres ERROR: could not open file for reading: Permission denied

Copy the CSV file to /tmp

For me this solved the issue.

C++ string to double conversion

If you are reading from a file then you should hear the advice given and just put it into a double.

On the other hand, if you do have, say, a string you could use boost's lexical_cast.

Here is a (very simple) example:

int Foo(std::string anInt)
{
   return lexical_cast<int>(anInt);
}

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Go to:

Settings -> Preferences You will see a dialog box. There click the Backup / Auto-completion tab where you can set the auto complete option :)

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

How to implement a custom AlertDialog View

The easiest way to do this is by using android.support.v7.app.AlertDialog instead of android.app.AlertDialog where public AlertDialog.Builder setView (int layoutResId) can be used below API 21.

new AlertDialog.Builder(getActivity())
    .setTitle(title)
    .setView(R.layout.dialog_basic)
    .setPositiveButton(android.R.string.ok,
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                //Do something
            }
        }
    )
    .setNegativeButton(android.R.string.cancel,
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                //Do something
            }
        }
    )
    .create();

How can I enable or disable the GPS programmatically on Android?

All these answers are not allowed now. Here is the correct one:

For all those still looking for the Answer:

Here is how OLA Cabs and other such apps are doing it.

Add this in your onCreate

if (googleApiClient == null) {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(Login.this).build();
    googleApiClient.connect();
            LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);

    // **************************
    builder.setAlwaysShow(true); // this is the key ingredient
    // **************************

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
            .checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result
                    .getLocationSettingsStates();
            switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                // All location settings are satisfied. The client can
                // initialize location
                // requests here.
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                // Location settings are not satisfied. But could be
                // fixed by showing the user
                // a dialog.
                try {
                    // Show the dialog by calling
                    // startResolutionForResult(),
                    // and check the result in onActivityResult().
                    status.startResolutionForResult(Login.this, 1000);
                } catch (IntentSender.SendIntentException e) {
                    // Ignore the error.
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                // Location settings are not satisfied. However, we have
                // no way to fix the
                // settings so we won't show the dialog.
                break;
            }
        }
    });
}

These are the implmented methods:

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

Here is the Android Documentation for the same.

This is to help other guys if they are still struggling:

Edit: Adding Irfan Raza's comment for more help.

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == 1000) {
         if(resultCode == Activity.RESULT_OK){
             String result=data.getStringExtra("result"); 
         } if (resultCode == Activity.RESULT_CANCELED) {
             //Write your code if there's no result 
         } 
    } 
} 

How can I export Excel files using JavaScript?

Create an AJAX postback method which writes a CSV file to your webserver and returns the url.. Set a hidden IFrame in the browser to the location of the CSV file on the server.

Your user will then be presented with the CSV download link.

jQuery find parent form

see also jquery/js -- How do I select the parent form based on which submit button is clicked?

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

How to change an input button image using CSS?

If you're wanting to style the button using CSS, make it a type="submit" button instead of type="image". type="image" expects a SRC, which you can't set in CSS.

Note that Safari won't let you style any button in the manner you're looking for. If you need Safari support, you'll need to place an image and have an onclick function that submits the form.

maven error: package org.junit does not exist

if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit

if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:

see JUNIT conflict

Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3

Move layouts up when soft keyboard is shown?

I tried a method of Diego Ramírez, it works. In AndroidManifest:

    <activity
        android:name=".MainActivity"
        android:windowSoftInputMode="stateHidden|adjustResize">
        ...
    </activity>

In activity_main.xml:

<LinearLayout ...
    android:orientation="vertical">

<Space
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1" />

<EditText
    android:id="@+id/edName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="@string/first_name"
    android:inputType="textPersonName" />

<EditText ...>
...
</LinearLayout>

Div Scrollbar - Any way to style it?

This one does well its scrolling job. It's very easy to understand, just really few lines of code, well written and totally readable.

How do you express binary literals in Python?

I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().

EDIT: lbrandy's answer is correct in all cases.

Ansible: Store command's stdout in new variable?

I'm a newbie in Ansible, but I would suggest next solution:

playbook.yml

...
vars:
  command_output_full:
    stdout: will be overriden below
  command_output: {{ command_output_full.stdout }}
...
...
...
tasks:
  - name: Create variable from command
    command: "echo Hello"
    register: command_output_full
  - debug: msg="{{ command_output }}"

It should work (and works for me) because Ansible uses lazy evaluation. But it seems it checks validity before the launch, so I have to define command_output_full.stdout in vars.

And, of course, if it is too many such vars in vars section, it will look ugly.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

How to change font size in html?

Give them a class and add your style to the class.

<style>
  p {
    color: red;
  }
  .paragraph1 {
    font-size: 18px;
  }
  .paragraph2 {
    font-size: 13px;
  }
</style>

<p class="paragraph1">Paragraph 1</p>
<p class="paragraph2">Paragraph 2</p>

Check this EXAMPLE

How do I limit the number of rows returned by an Oracle query after ordering?

(untested) something like this may do the job

WITH
base AS
(
    select *                   -- get the table
    from sometable
    order by name              -- in the desired order
),
twenty AS
(
    select *                   -- get the first 30 rows
    from base
    where rownum < 30
    order by name              -- in the desired order
)
select *                       -- then get rows 21 .. 30
from twenty
where rownum > 20
order by name                  -- in the desired order

There is also the analytic function rank, that you can use to order by.

CSS two divs next to each other

This won't be the answer for everyone, since it is not supported in IE7-, but you could use it and then use an alternate answer for IE7-. It is display: table, display: table-row and display: table-cell. Note that this is not using tables for layout, but styling divs so that things line up nicely with out all the hassle from above. Mine is an html5 app, so it works great.

This article shows an example: http://www.sitepoint.com/table-based-layout-is-the-next-big-thing/

Here is what your stylesheet will look like:

 .container {
    display: table;
    width:100%;
 }

 .left-column {
    display: table-cell;
 }

 .right-column {
    display: table-cell;
    width: 200px;
 }

Java: how to represent graphs?

Even at the time of this question, over 3 years ago, Sage (which is completely free) existed and was pretty good at graph theory. But, in 2012 it is about the best graph theory tool there is. Thus, Sage already has a huge amount of graph theory material built in, including other free and open source stuff that is out there. So, simply messing around with various things to learn more is easy as no programming is required.

And, if you are interested in the programming part as well, first Sage is open source so you can see any code that already exists. And, second, you can re-program any function you want if you really want to practice, or you can be the first to program something that does not already exist. In the latter case, you can even submit that new functionality and make Sage better for all other users.

At this time, this answer may not be that useful to the OP (since it has been 3 years), but hopefully it is useful to any one else who sees this question in the future.

Node.js: get path from the request

A more modern solution that utilises the URL WebAPI:

(req, res) => {
  const { pathname } = new URL(req.url || '', `https://${req.headers.host}`)
}

How do I get a UTC Timestamp in JavaScript?

I think this is a better solution

// UTC milliseconds
new Date(Date.now()+(new Date().getTimezoneOffset()*60000)).getTime()

// UTC seconds
new Date(Date.now()+(new Date().getTimezoneOffset()*60000)).getTime()/1000|0

How do I clone a generic List in Java?

This should also work:

ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()

How to link html pages in same or different folders?

Within the same folder, just use the file name:

<a href="thefile.html">my link</a>

Within the parent folder's directory:

<a href="../thefile.html">my link</a>

Within a sub-directory:

<a href="subdir/thefile.html">my link</a>

Kill some processes by .exe file name

Quick Answer:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(leave off .exe from process name)

How to display a date as iso 8601 format with PHP

Procedural style :

echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00

Object oriented style :

$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00

Hybrid 1 :

echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00

Hybrid 2 :

echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00

Notes :

1) You could also use 'Y-m-d\TH:i:sP' as an alternative to 'c' for your format.

2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :

echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00

3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :

echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00

Finding first blank row, then writing to it

I know this is an older thread however I needed to write a function that returned the first blank row WITHIN a range. All of the code I found online actually searches the entire row (even the cells outside of the range) for a blank row. Data in ranges outside the search range was triggering a used row. This seemed to me to be a simple solution:

Function FirstBlankRow(ByVal rngToSearch As Range) As Long
   Dim R As Range
   Dim C As Range
   Dim RowIsBlank As Boolean

   For Each R In rngToSearch.Rows
      RowIsBlank = True
      For Each C In R.Cells
         If IsEmpty(C.Value) = False Then RowIsBlank = False
      Next C
      If RowIsBlank Then
         FirstBlankRow = R.Row
         Exit For
      End If
   Next R
End Function

Installing Google Protocol Buffers on mac

To install Protocol Buffer (as of today version v3.7.0)

  1. Go to this website
  2. download the zip file according to your OS (e.g.: protoc-3.7.0-osx-x86_64.zip). This applies also to other OS.

  3. Move the executable in protoc-3/bin/protoc to one of your directories in PATH. In Mac I suggest to put it into /usr/local/bin

Now your good to go

(optional) There is also an include file, you can add. This is a snippet of the README.md

If you intend to use the included well known types then don't forget to
copy the contents of the 'include' directory somewhere as well, for example
into '/usr/local/include/'.

Please refer to our official github site for more installation instructions:
https://github.com/protocolbuffers/protobuf

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

In your case removing ./ should solve the issue. I had another case wherein I was using a directory from the parent directory and docker can only access files present below the directory where Dockerfile is present so if I have a directory structure /root/dir and Dockerfile /root/dir/Dockerfile

I cannot copy do the following

COPY root/src /opt/src

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Try this to get value from select element by Element Name

$("select[name=elementnamehere]").val();

Regex: Remove lines containing "help", etc

Another way to do this in Notepad++ is all in the Find/Replace dialog and with regex:

  • Ctrl + h to bring up the find replace dialog.

  • In the Find what: text box include your regex: .*help.*\r?\n (where the \r is optional in case the file doesn't have Windows line endings).

  • Leave the Replace with: text box empty.

  • Make sure the Regular expression radio button in the Search Mode area is selected. Then click Replace All and voila! All lines containing your search term help have been removed.

How-To Line Replace in N++

Nested JSON: How to add (push) new items to an object?

library is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.

Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.

What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.

How do I URl encode something in Node.js?

Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).

This is correct if you plan on using the string later as a query string:

> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'

If you don't want ASCII characters like /, : and ? to be escaped, use encodeURI instead:

> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'

However, for other use-cases, you might need uri-js instead:

> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

Like it has been already mentioned, you are reading the file in binary mode and then creating a list of bytes. In your following for loop you are comparing string to bytes and that is where the code is failing.

Decoding the bytes while adding to the list should work. The changed code should look as follows:

with open(fname, 'rb') as f:
    lines = [x.decode('utf8').strip() for x in f.readlines()]

The bytes type was introduced in Python 3 and that is why your code worked in Python 2. In Python 2 there was no data type for bytes:

>>> s=bytes('hello')
>>> type(s)
<type 'str'>

Detect if PHP session exists

function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

'default' => env('DB_CONNECTION', 'mysql'),

add this in your code

How can I get the full/absolute URL (with domain) in Django?

If anyone is interested in fetching the absolute reverse url with parameters in a template , the cleanest way is to create your own absolute version of the {% url %} template tag by extending and using existing default code.

Here is my code:

from django import template
from django.template.defaulttags import URLNode, url

register = template.Library()

class AbsURLNode(URLNode):
    def __init__(self, view_name, args, kwargs, asvar):
        super().__init__(view_name, args, kwargs, asvar)

    def render(self, context):
        url     = super().render(context)
        request = context['request']

        return request.build_absolute_uri(url)


@register.tag
def abs_url(parser, token):

    urlNode = url(parser, token)
    return AbsURLNode( urlNode.view_name, urlNode.args, urlNode.kwargs, urlNode.asvar  )

Usage in templates:

{% load wherever_your_stored_this_tag_file %}
{% abs_url 'view_name' parameter %}

will render(example):

http://example.com/view_name/parameter/

instead of

/view_name/parameter/

Jquery DatePicker Set default date

Today date:

$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });

15 days from today:

$( ".selector" ).datepicker( "setDate", 15);
// Or on the init
$( ".selector" ).datepicker({ defaultDate: 15 });

jQuery ui docs

Add click event on div tag using javascript

Pure Javascript

document.getElementsByClassName('drill_cursor')[0]
        .addEventListener('click', function (event) {
            // do something
        });

jQuery

$(".drill_cursor").click(function(){
//do something
});

Redirect within component Angular 2

first configure routing

import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';

and

@RouteConfig([
  { path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
  { path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])

then in your component import and then inject Router

import {Router} from 'angular2/router'

export class AddDisplay {
  constructor(private router: Router)
}

the last thing you have to do is to call

this.router.navigateByUrl('<pathDefinedInRouteConfig>');

or

this.router.navigate(['<aliasInRouteConfig>']);

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

TypeError: 'int' object is not callable

Stop stomping on round somewhere else by binding an int to it.

How to show what a commit did?

This is one way I know of. With git, there always seems to be more than one way to do it.

git log -p commit1 commit2

how can get index & count in vuejs

The optional SECOND argument is the index, starting at 0. So to output the index and total length of an array called 'some_list':

<div>Total Length: {{some_list.length}}</div>
<div v-for="(each, i) in some_list">
  {{i + 1}} : {{each}}
</div>

If instead of a list, you were looping through an object, then the second argument is key of the key/value pair. So for the object 'my_object':

var an_id = new Vue({
  el: '#an_id',
  data: {
    my_object: {
        one: 'valueA',
        two: 'valueB'
    }
  }
})

The following would print out the key : value pairs. (you can name 'each' and 'i' whatever you want)

<div id="an_id">
  <span v-for="(each, i) in my_object">
    {{i}} : {{each}}<br/>
  </span>
</div>

For more info on Vue list rendering: https://vuejs.org/v2/guide/list.html

Python: SyntaxError: keyword can't be an expression

I guess many of us who came to this page have a problem with Scikit Learn, one way to solve it is to create a dictionary with parameters and pass it to the model:

params = {'C': 1e9, 'gamma': 1e-07}
cls = SVC(**params)    

Android Studio - Gradle sync project failed

After applying this fix that was found here... https://code.google.com/p/android/issues/detail?id=208295

in file $SDK/ndk_bundle/source.properties replace "12.0.2753695 beta 1" to "12.0.2753695-beta1"

My project was built successfully and ran on device and emulators although 5 warnings still remains.

Right align and left align text in same HTML table cell

You could use something like:

<td> 
  <div style="float:left;width:49%;text-align:left;">this is left</div> 
  <div style="float:right;width:49%;text-align:right;">this is right</div> 
</td>

The 49% is to give some room for the renderer to wrap things around.

And you can use either <div> or <span>

Difference between a script and a program?

I take a different view.

A "script" is code that acts upon some system in an external or independent manner and can be removed or disabled without disabling the system itself.

A "program" is code that constitutes a system. The program's code may be written in a modular manner, with good separation of concerns, but the code is fundamentally internal to, and a dependency of, the system itself.

Scripts are often interpreted, but not always. Programs are often compiled, but not always.

Fork() function in C

int a = fork(); 

Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.

The child getting 0 returned, and the parent getting the new pid.

Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.

At each fork, only one value is modified - the return value from fork.

How to use OUTPUT parameter in Stored Procedure

You need to close the connection before you can use the output parameters. Something like this

con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());

When to use NSInteger vs. int

On iOS, it currently does not matter if you use int or NSInteger. It will matter more if/when iOS moves to 64-bits.

Simply put, NSIntegers are ints in 32-bit code (and thus 32-bit long) and longs on 64-bit code (longs in 64-bit code are 64-bit wide, but 32-bit in 32-bit code). The most likely reason for using NSInteger instead of long is to not break existing 32-bit code (which uses ints).

CGFloat has the same issue: on 32-bit (at least on OS X), it's float; on 64-bit, it's double.

Update: With the introduction of the iPhone 5s, iPad Air, iPad Mini with Retina, and iOS 7, you can now build 64-bit code on iOS.

Update 2: Also, using NSIntegers helps with Swift code interoperability.

Read XLSX file in Java

I'm not very happy with any of the options so I ended up requesting the file in Excel 97 formate. The POI works great for that. Thanks everyone for the help.

Clone private git repo with dockerfile

Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.

As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY the required files into your final image.

Additionally if we LABEL our intermediate layers, we can even delete them from the machine when finished.

# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate

# Take an SSH key as a build argument.
ARG SSH_KEY

# Install dependencies required to git clone.
RUN apk update && \
    apk add --update git && \
    apk add --update openssh

# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
    echo "$SSH_KEY" > /root/.ssh/id_rsa && \
    chmod -R 600 /root/.ssh/ && \
    ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git

# Choose the base image for our final image
FROM alpine

# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md

We can then build:

MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .

Prove our SSH keys are gone:

docker run -ti --rm clone-example cat /root/.ssh/id_rsa

Clean intermediate images from the build machine:

docker rmi -f $(docker images -q --filter label=stage=intermediate)

In C can a long printf statement be broken up into multiple lines?

Just some other formatting options:

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
        a,        b,        c,        d);

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
              a,        b,        c,            d);

printf("name: %s\t"      "args: %s\t"      "value %d\t"      "arraysize %d\n", 
        very_long_name_a, very_long_name_b, very_long_name_c, very_long_name_d);

You can add variations on the theme. The idea is that the printf() conversion speficiers and the respective variables are all lined up "nicely" (for some values of "nicely").

C# - Making a Process.Start wait until the process has start-up

Are you sure the Start method returns before the child process starts? I was always under the impression that Start starts the child process synchronously.

If you want to wait until your child process finishes some sort of initialization then you need inter-process communication - see Interprocess communication for Windows in C# (.NET 2.0).

Delete keychain items when an app is uninstalled

Just add an app setting bundle and implement a toggle to reset the keychain on app restart or something based on the value selected through settings (available through userDefaults)

MySQL query to select events between start/end date

Here lot of good answer but i think this will help someone

select id  from campaign where ( NOW() BETWEEN start_date AND end_date) 

What is a .NET developer?

Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).

As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.

How to install PyQt4 on Windows using pip?

You can't use pip. You have to download from the Riverbank website and run the installer for your version of python. If there is no install for your version, you will have to install Python for one of the available installers, or build from source (which is rather involved). Other answers and comments have the links.

Choosing the default value of an Enum type without having to change values

The default value for an enumeration type is 0:

  • "By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1."

  • "The value type enum has the value produced by the expression (E)0, where E is the enum identifier."

You can check the documentation for C# enum here, and the documentation for C# default values table here.

Edit a commit message in SourceTree Windows (already pushed to remote)

Here are the steps to edit the commit message of a previous commit (which is not the most recent commit) using SourceTree for Windows version 1.5.2.0:

Step 1

Select the commit immediately before the commit that you want to edit. For example, if I want to edit the commit with message "FOOBAR!" then I need to select the commit that comes right before it:

Selecting commit before the one that I want to edit.

Step 2

Right-click on the selected commit and click Rebase children...interactively:

Selecting "Rebase children interactively".

Step 3

Select the commit that you want to edit, then click Edit Message at the bottom. In this case, I'm selecting the commit with the message "FOOBAR!":

Select the commit that you want to edit.

Step 4

Edit the commit message, and then click OK. In my example, I've added "SHAZBOT! SKADOOSH!"

Edit the commit message

Step 5

When you return to interactive rebase window, click on OK to finish the rebase:

Click OK to finish.

Step 6

At this point, you'll need to force-push your new changes since you've rebased commits that you've already pushed. However, the current 1.5.2.0 version of SourceTree for Windows does not allow you to force-push through the GUI, so you'll need to use Git from the command line anyways in order to do that.

Click Terminal from the GUI to open up a terminal.

Click Terminal

Step 7

From the terminal force-push with the following command,

git push origin <branch> -f

where <branch> is the name of the branch that you want to push, and -f means to force the push. The force push will overwrite your commits on your remote repo, but that's OK in your case since you said that you're not sharing your repo with other people.

That's it! You're done!

PHP If Statement with Multiple Conditions

An elegant way is building an array on the fly and using in_array():

if (in_array($var, array("abc", "def", "ghi")))

The switch statement is also an alternative:

switch ($var) {
case "abc":
case "def":
case "hij":
    echo "yes";
    break;
default:
    echo "no";
}

Compiler warning - suggest parentheses around assignment used as truth value

It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have == in there. You can make the warning go away by adding another set of parentheses:

while ((list = list->next))

Recursively counting files in a Linux directory

You can use the command ncdu. It will recursively count how many files a Linux directory contains. Here is an example of output:

enter image description here

It has a progress bar, which is convenient if you have many files:

enter image description here

To install it on Ubuntu:

sudo apt-get install -y ncdu

Benchmark: I used https://archive.org/details/cv_corpus_v1.tar (380390 files, 11 GB) as the folder where one has to count the number of files.

  • find . -type f | wc -l: around 1m20s to complete
  • ncdu: around 1m20s to complete

Python: PIP install path, what is the correct location for this and other addons?

Also, when you uninstall the package, the first item listed is the directory to the executable.

How to check iOS version?

A more generic version in Obj-C++ 11 (you could probably replace some of this stuff with the NSString/C functions, but this is less verbose. This gives you two mechanisms. splitSystemVersion gives you an array of all the parts which is useful if you just want to switch on the major version (e.g. switch([self splitSystemVersion][0]) {case 4: break; case 5: break; }).

#include <boost/lexical_cast.hpp>

- (std::vector<int>) splitSystemVersion {
    std::string version = [[[UIDevice currentDevice] systemVersion] UTF8String];
    std::vector<int> versions;
    auto i = version.begin();

    while (i != version.end()) {
        auto nextIllegalChar = std::find_if(i, version.end(), [] (char c) -> bool { return !isdigit(c); } );
        std::string versionPart(i, nextIllegalChar);
        i = std::find_if(nextIllegalChar, version.end(), isdigit);

        versions.push_back(boost::lexical_cast<int>(versionPart));
    }

    return versions;
}

/** Losslessly parse system version into a number
 * @return <0>: the version as a number,
 * @return <1>: how many numeric parts went into the composed number. e.g.
 * X.Y.Z = 3.  You need this to know how to compare again <0>
 */
- (std::tuple<int, int>) parseSystemVersion {
    std::string version = [[[UIDevice currentDevice] systemVersion] UTF8String];
    int versionAsNumber = 0;
    int nParts = 0;

    auto i = version.begin();
    while (i != version.end()) {
        auto nextIllegalChar = std::find_if(i, version.end(), [] (char c) -> bool { return !isdigit(c); } );
        std::string versionPart(i, nextIllegalChar);
        i = std::find_if(nextIllegalChar, version.end(), isdigit);

        int part = (boost::lexical_cast<int>(versionPart));
        versionAsNumber = versionAsNumber * 100 + part;
        nParts ++;
    }

    return {versionAsNumber, nParts};
}


/** Assume that the system version will not go beyond X.Y.Z.W format.
 * @return The version string.
 */
- (int) parseSystemVersionAlt {
    std::string version = [[[UIDevice currentDevice] systemVersion] UTF8String];
    int versionAsNumber = 0;
    int nParts = 0;

    auto i = version.begin();
    while (i != version.end() && nParts < 4) {
        auto nextIllegalChar = std::find_if(i, version.end(), [] (char c) -> bool { return !isdigit(c); } );
        std::string versionPart(i, nextIllegalChar);
        i = std::find_if(nextIllegalChar, version.end(), isdigit);

        int part = (boost::lexical_cast<int>(versionPart));
        versionAsNumber = versionAsNumber * 100 + part;
        nParts ++;
    }

    // don't forget to pad as systemVersion may have less parts (i.e. X.Y).
    for (; nParts < 4; nParts++) {
        versionAsNumber *= 100;
    }

    return versionAsNumber;
}

How to push to History in React Router v4?

React router V4 now allows the history prop to be used as below:

this.props.history.push("/dummy",value)

The value then can be accessed wherever the location prop is available as state:{value} not component state.

SQL: Combine Select count(*) from multiple tables

select sum(counts) from (
select count(1) as counts from foo 
union all
select count(1) as counts from bar)

How do I exit from the text window in Git?

On windows I used the following command

:wq

and it aborts the previous commit because of the empty commit message

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

This might happen when you attempt to grant all privileges on all tables to another user, because the mysql.users table is considered off-limits for a user other than root.

The following however, should work:

GRANT ALL PRIVILEGES ON `%`.* TO '[user]'@'[hostname]' IDENTIFIED BY '[password]' WITH GRANT OPTION;

Note that we use `%`.* instead of *.*

Class Not Found Exception when running JUnit test

Check if your project is opened as a Maven project and not just a regular Java project. Actually a no-brainer, but that is exactly the same reason why you might miss it.

SET NAMES utf8 in MySQL?

Not only PDO. If sql answer like '????' symbols, preset of you charset (hope UTF-8) really recommended:

if (!$mysqli->set_charset("utf8")) 
 { printf("Can't set utf8: %s\n", $mysqli->error); }

or via procedure style mysqli_set_charset($db,"utf8")

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

Column/Vertical selection with Keyboard in SublimeText 3

I know notepad++ has a feature that lets you select blocks of text independent of line/column by holding control + alt + drag. So you can select just about any block of text you want.

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

How to find SQL Server running port?

Perhaps not the best options but just another way is to read the Windows Registry in the host machine, on elevated PowerShell prompt you can do something like this:

#Get SQL instance's Port number using Windows Registry:
$instName = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances[0]
$tcpPort = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$instName\MSSQLServer\SuperSocketNetLib\Tcp").TcpPort
Write-Host The SQL Instance:  `"$instName`"  is listening on `"$tcpPort`"  "TcpPort."

enter image description here Ensure to run this PowerShell script in the Host Server (that hosts your SQL instance / SQL Server installation), which means you have to first RDP into the SQL Server/Box/VM, then run this code.

HTH

Remove all HTMLtags in a string (with the jquery text() function)

If you need to remove the HTML but does not know if it actually contains any HTML tags, you can't use the jQuery method directly because it returns empty wrapper for non-HTML text.

$('<div>Hello world</div>').text(); //returns "Hello world"
$('Hello world').text(); //returns empty string ""

You must either wrap the text in valid HTML:

$('<div>' + 'Hello world' + '</div>').text();

Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:

var html = $.parseHTML('Hello world'); //parseHTML return HTMLCollection
var text = $(html).text(); //use $() to get .text() method

Plus parseHTML removes script tags completely which is useful as anti-hacking protection for user inputs.

$('<p>Hello world</p><script>console.log(document.cookie)</script>').text();
//returns "Hello worldconsole.log(document.cookie)"

$($.parseHTML('<p>Hello world</p><script>console.log(document.cookie)</script>')).text();
//returns "Hello world"

Sqlite convert string to date

convert a string into date little issue think with indexing mmm 3,3 but works added a month on to the date string

SELECT substr('12Jan20',1,2) as dday,
date(substr('12Jan20',6,7) ||'00-' || case substr('12Jan20',3,3) when 'Jan' then '01'
when 'Feb' then '02'
when 'Mar' then '03'
when 'Apr' then '04'
when 'May' then '05' 
when 'Jun' then '06'
when 'Jul' then '07'
when 'Aug' then '08'
when 'Sep' then '09'
when 'Oct' then '10'
when 'Nov' then '11'
when 'Dec' then '12' end  || '-'||substr('12Jan20',1,2), '+1 month') as tt

How to assign text size in sp value using java code

By default setTextSize, without units work in SP (scales pixel)

public void setTextSize (float size) 
Added in API level 1
Set the default text size to the given value, interpreted as "scaled pixel" units. This 
size is adjusted based on the current density and user font size preference.

SUM OVER PARTITION BY

In my opinion, I think it's important to explain the why behind the need for a GROUP BY in your SQL when summing with OVER() clause and why you are getting repeated lines of data when you are expecting one row per BrandID.

Take this example: You need to aggregate the total sale price of each order line, per specific order category, between two dates, but you also need to retain individual order data in your final results. A SUM() on the SalesPrice column would not allow you to get the correct totals because it would require a GROUP BY, therefore squashing the details because you wouldn't be able to keep the individual order lines in the select statement.

Many times we see a #temp table, @table variable, or CTE filled with the sum of our data and grouped up so we can join to it again later to get a column of the sums we need. This can add processing time and extra lines of code. Instead, use OVER(PARTITION BY ()) like this:

SELECT
  OrderLine, 
  OrderDateTime, 
  SalePrice, 
  OrderCategory,
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

Notice we are not grouping and we have individual order lines column selected. The PARTITION BY in the last column will return us a sales price total for each row of data in each category. What the last column essentially says is, we want the sum of the sale price (SUM(SalePrice)) over a partition of my results and by a specified category (OVER(PARTITION BY CategoryHere)).

If we remove the other columns from our select statement, and leave our final SUM() column, like this:

SELECT
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

The results will still repeat this sum for each row in our original result set. The reason is this method does not require a GROUP BY. If you don't need to retain individual line data, then simply SUM() without the use of OVER() and group up your data appropriately. Again, if you need an additional column with specific totals, you can use the OVER(PARTITION BY ()) method described above without additional selects to join back to.

The above is purely for explaining WHY he is getting repeated lines of the same number and to help understand what this clause provides. This method can be used in many ways and I highly encourage further reading from the documentation here:

Over Clause

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

  1. Add Internet permission in Androidmanifest.xml file

uses-permission android:name="android.permission.INTERNET

  1. Open cmd in windows
  2. type "ipconfig" then press enter
  3. find IPv4 Address. . . . . . . . . . . : 192.168.X.X
  4. use this URL "http://192.168.X.X:your_virtual_server_port/your_service.php"

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

How to pass anonymous types as parameters?

"dynamic" can also be used for this purpose.

var anonymousType = new { Id = 1, Name = "A" };

var anonymousTypes = new[] { new { Id = 1, Name = "A" }, new { Id = 2, Name = "B" };

private void DisplayAnonymousType(dynamic anonymousType)
{
}

private void DisplayAnonymousTypes(IEnumerable<dynamic> anonymousTypes)
{
   foreach (var info in anonymousTypes)
   {

   }
}

Command /usr/bin/codesign failed with exit code 1

I had the exact same problem and this did the trick for me:

Xcode > Preferences > Accounts > View Details > And just refresh the Provisioning Profile

Seems like the accounts in Xcode were not updated with the latest provisioning profiles so a quick refresh sorted this out.

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

How do I make Visual Studio pause after executing a console application in debug mode?

Boost test offers the following usage recommendations for Visual Studio that would enable you to run the unit tests automatically at the end of compilation and capture the output into the build window.

The nice side effect of this trick is it enable you to treat test failures as compilation errors. "...you could jump through these errors using usual keyboard shortcuts/mouse clicks you use for compilation error analysis..."

How to convert string to double with proper cultureinfo

Convert.ToDouble(x) can also have a second parameter that indicates the CultureInfo and when you set it to System.Globalization.CultureInfo InvariantCulture the result will allways be the same.

Is the buildSessionFactory() Configuration method deprecated in Hibernate

In hibernate 5.3.1, you can try this:

ServiceRegistry standardRegistry = 
                new StandardServiceRegistryBuilder().configure().build();

Metadata sources = new MetadataSources(standardRegistry).addAnnotatedClass(MyEntity.class).getMetadataBuilder().build();

SessionFactory sf = sources.buildSessionFactory();

Single TextView with multiple colored text

yes, if you format the String with html's font-color property then pass it to the method Html.fromHtml(your text here)

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

Single selection in RecyclerView

The following might be helpful for RecyclerView with Single Choice.

Three steps to do that, 1) Declare a global integer variable,

private int mSelectedItem = -1;

2) in onBindViewHolder

 mRadio.setChecked(position == mSelectedItem);

3) in onClickListener

mSelectedItem = getAdapterPosition();
notifyItemRangeChanged(0, mSingleCheckList.size());
mAdapter.onItemHolderClick(SingleCheckViewHolder.this);

How to get object size in memory?

The following code fragment should return the size in bytes of any object passed to it, so long as it can be serialized. I got this from a colleague at Quixant to resolve a problem of writing to SRAM on a gaming platform. Hope it helps out. Credit and thanks to Carlo Vittuci.

/// <summary>
/// Calculates the lenght in bytes of an object 
/// and returns the size 
/// </summary>
/// <param name="TestObject"></param>
/// <returns></returns>
private int GetObjectSize(object TestObject)
{
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    byte[] Array;
    bf.Serialize(ms, TestObject);
    Array = ms.ToArray();
    return Array.Length;
}

Class Diagrams in VS 2017

Woo-hoo! It works with some hack!

According to this comment you need to:

  1. Manually edit Microsoft.CSharp.DesignTime.targets located in C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed (for VS Community edition, modify path for other editions), append ClassDesigner value to ProjectCapability (right pane):File diff

  2. Restart VS.

  3. Manually create text file, say MyClasses.cd with following content: <?xml version="1.0" encoding="utf-8"?> <ClassDiagram MajorVersion="1" MinorVersion="1"> <Font Name="Segoe UI" Size="9" /> </ClassDiagram>

Bingo. Now you may open this file in VS. You will see error message "Object reference not set to an instance of object" once after VS starts, but diagram works.

Checked on VS 2017 Community Edition, v15.3.0 with .NETCore 2.0 app/project:

enter image description here

GitHub issue expected to fix in v15.5

Maven 3 warnings about build.plugins.plugin.version

Maven 3 is more restrictive with the POM-Structure. You have to set versions of Plugins for instance.

With maven 3.1 these warnings may break you build. There are more changes between maven2 and maven3: https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

Reading specific XML elements from XML file

XDocument xdoc = XDocument.Load(path_to_xml);
var word = xdoc.Elements("word")
               .SingleOrDefault(w => (string)w.Element("category") == "verb");

This query will return whole word XElement. If there is more than one word element with category verb, than you will get an InvalidOperationException. If there is no elements with category verb, result will be null.

Bash: infinite sleep (infinite blocking)

while :; do read; done

no waiting for child sleeping process.

How to create a generic array in Java?

private E a[];
private int size;

public GenSet(int elem)
{
    size = elem;
    a = (E[]) new E[size];
}

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

Check if checkbox is checked with jQuery

Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!

Here are the syntaxes :

var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */

/* The DOM way - The fastest */
if(checkbox[0].checked == true)
   alert('Checkbox is checked!!');

/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
   alert('Checkbox is checked!!');

/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
   alert('Checkbox is checked!!');

I personally prefer .prop(). Unlike .is(), It can also be used to set the value.

Changing the size of a column referenced by a schema-bound view in SQL Server

ALTER TABLE [table_name] ALTER COLUMN [column_name] varchar(150)

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

This problem happens when you install the JDK by _uncompressing_ it instead of _executing_ it.

By example:

unzip jdk-6u45-linux-x64.bin  (wrong)

sh ./jdk-6u45-linux-x64.bin   (right)

In the first scenario, the runtime libraries, as rt.jar, don't get automatically uncompresessed (thus, you can find the rt.pack files, etc. instead of the .jar ones).

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

You can also upgrade Mehrdad Afshari's solution by rewriting the extention method to faster (and better looking) one:

static class EnumerableExtensions
{
    public static T MaxElement<T, R>(this IEnumerable<T> container, Func<T, R> valuingFoo) where R : IComparable
    {
        var enumerator = container.GetEnumerator();
        if (!enumerator.MoveNext())
            throw new ArgumentException("Container is empty!");

        var maxElem = enumerator.Current;
        var maxVal = valuingFoo(maxElem);

        while (enumerator.MoveNext())
        {
            var currVal = valuingFoo(enumerator.Current);

            if (currVal.CompareTo(maxVal) > 0)
            {
                maxVal = currVal;
                maxElem = enumerator.Current;
            }
        }

        return maxElem;
    }
}

And then just use it:

var maxObject = list.MaxElement(item => item.Height);

That name will be clear to people using C++ (because there is std::max_element in there).

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

In my opinion SET XACT_ABORT ON was made obsolete by the addition of BEGIN TRY/BEGIN CATCH in SQL 2k5. Before exception blocks in Transact-SQL it was really difficult to handle errors and unbalanced procedures were all too common (procedures that had a different @@TRANCOUNT at exit compared to entry).

With the addition of Transact-SQL exception handling is much easier to write correct procedures that are guaranteed to properly balance the transactions. For instance I use this template for exception handling and nested transactions:

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

        -- Do the actual work here

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

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

It allows me to write atomic procedures that rollback only their own work in case of recoverable errors.

One of the main issues Transact-SQL procedures face is data purity: sometimes the parameters received or the data in the tables are just plain wrong, resulting in duplicate key errors, referential constrain errors, check constrain errors and so on and so forth. After all, that's exactly the role of these constrains, if these data purity errors would be impossible and all caught by the business logic, the constrains would be all obsolete (dramatic exaggeration added for effect). If XACT_ABORT is ON then all these errors result in the entire transaction being lost, as opposed to being able to code exception blocks that handle the exception gracefully. A typical example is trying to do an INSERT and reverting to an UPDATE on PK violation.

Is it possible to get a list of files under a directory of a website? How?

If you have directory listing disabled in your webserver, then the only way somebody will find it is by guessing or by finding a link to it.

That said, I've seen hacking scripts attempt to "guess" a whole bunch of these common names. "secret.html" would probably be in such a guess list.

The more reasonable solution is to restrict access using a username/password via a htaccess file (for apache) or the equivalent setting for whatever webserver you're using.

How to get size of mysql database?

mysqldiskusage  --server=root:MyPassword@localhost  pics

+----------+----------------+
| db_name  |         total  |
+----------+----------------+
| pics     | 1,179,131,029  |
+----------+----------------+

If not installed, this can be installed by installing the mysql-utils package which should be packaged by most major distributions.

How can javascript upload a blob?

2019 Update

This updates the answers with the latest Fetch API and doesn't need jQuery.

Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.

Basic Fetch

It could be as simple as:

  fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                .then(response => console.log(response.text()))

Fetch with Error Handling

After adding error handling, it could look like:

fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
            .then(response => {
                if (response.ok) return response;
                else throw Error(`Server returned ${response.status}: ${response.statusText}`)
            })
            .then(response => console.log(response.text()))
            .catch(err => {
                alert(err);
            });

PHP Code

This is the server-side code in upload.php.

<?php    
    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("path/to/file", "wb");

    fwrite($fp, $data);
    fclose($fp);
?>

How to check the installed version of React-Native

Check your Package.json file to know react-native version.

OR

Open terminal and run command react-native -v

How to exclude records with certain values in sql select

SELECT  DISTINCT a.StoreID
FROM    tableName a
        LEFT JOIN tableName b 
          ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE   b.StoreID IS NULL

OUTPUT

+---------+
¦ STOREID ¦
¦---------¦
¦       3 ¦
+---------+

Best font for coding

I like Consolas a lot. This top-10 list is a good resource for others. It includes examples and descriptions.

Phonegap Cordova installation Windows

I have found this Multi-Device Hybrid Apps for Visual Studio Documentation for CTP1.1 Last updated: May 29, 2014 .

Some of the content from the documentation as follows.

This release supports building apps for the following device targets:

Android 4+ (4.4 providing the optimal developer experience) iOS 6 & 7 Windows 8.0 (Store) Windows Phone 8.0

Requirements: Windows 8.1

Visual Studio 2013 Update 2 - Professional, Ultimate, or Premium with the following optional features installed:

Tools for Maintaining Store apps for Windows 8 Windows Phone 8.0 SDK

Additional system requirements vary by device platform:

The Android emulator works best with PCs capable of installing the Intel HAXM driver

Windows Phone 8 requires a Hyper-V capable PC to run the emulator Building for iOS and using the iOS Simulator requires a Mac capable of running Xcode 5.1

Third Party Dependencies :

Joyent Node.js – Enables Visual Studio to integrate with the Apache Cordova Command Line Interface (CLI) and Apache Ripple™ Emulator Git CLI – Required only if you need to manually add git URIs for plugins

Google Chrome – Required to run the Apache Ripple emulator for iOS and Android

Apache Ant 1.8.0+ – Required as a dependency for the Android build process

Oracle Java JDK 7 – Required as a dependency for the Android build process

Android SDK – Required as a dependency for the Android build process and Ripple

SQLLite for Windows Runtime – required to add SQL connectivity to Windows apps (for the WebSQL Polyfill plugin)

Apple iTunes – Required for deploying an app to an iOS device connected to your Windows PC

enter image description here

How to use a ViewBag to create a dropdownlist?

Try using @Html.DropDownList instead:

<td>Account: </td>
<td>@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>

@Html.DropDownListFor expects a lambda as its first argument, not a string for the ID as you specify.

Other than that, without knowing what getUserAccounts() consists of, suffice to say it needs to return some sort of collection (IEnumerable for example) that has at least 1 object in it. If it returns null the property in the ViewBag won't have anything.

Check if a div exists with jquery

The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.

How do you POST to a page using the PHP header() function?

There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I solved this problem by deleting the empty users creating by MySQL. I only have root user and my own user. I deleted the rest.

Assert a function/method was not called using Mock

With python >= 3.5 you can use mock_object.assert_not_called().

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

PHP - get base64 img string decode and save as jpg (resulting empty image )

Decode and save image as PNG

header('content-type: image/png');

           ob_start();

        $ret = fopen($fullurl, 'r', true, $context);
        $contents = stream_get_contents($ret);
        $base64 = 'data:image/PNG;base64,' . base64_encode($contents);
        echo "<img src=$base64 />" ;


        ob_end_flush();

HAX kernel module is not installed

Actual error

enter image description here

follow bellow two simple steps to fix.

Step 1:- update "Intel x86 Emulator Accelerator (HAXM installer)" Ref. bellow img enter image description here

Step2:-

After installing the installer, you have to run it to install it on your system. Open the directory where your Android SDK is located. Go inside the extras\Intel\Hardware_Accelerated_Execution_Manager directory and you should see the intelhaxm-android.exe file.

enter image description here

If you got the error "This computer meets requirements for HAXM, but VT-x is not turned on..." during installation try to turn it on in your BIOS and check your antivirus software settings also. (Check this stackoverflow post). Thats it! its working for me.

How to use google maps without api key

Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.

Tooltips for cells in HTML table (no Javascript)

The highest-ranked answer by Mudassar Bashir using the "title" attribute seems the easiest way to do this, but it gives you less control over how the comment/tooltip is displayed.

I found that The answer by Christophe for a custom tooltip class seems to give much more control over the behavior of the comment/tooltip. Since the provided demo does not include a table, as per the question, here is a demo that includes a table.

Note that the "position" style for the parent element of the span (a in this case), must be set to "relative" so that the comment does not push the table contents around when it is displayed. It took me a little while to figure that out.

_x000D_
_x000D_
#MyTable{_x000D_
  border-style:solid;_x000D_
  border-color:black;_x000D_
  border-width:2px_x000D_
}_x000D_
_x000D_
#MyTable td{_x000D_
  border-style:solid;_x000D_
  border-color:black;_x000D_
  border-width:1px;_x000D_
  padding:3px;_x000D_
}_x000D_
_x000D_
.CellWithComment{_x000D_
  position:relative;_x000D_
}_x000D_
_x000D_
.CellComment{_x000D_
  display:none;_x000D_
  position:absolute; _x000D_
  z-index:100;_x000D_
  border:1px;_x000D_
  background-color:white;_x000D_
  border-style:solid;_x000D_
  border-width:1px;_x000D_
  border-color:red;_x000D_
  padding:3px;_x000D_
  color:red; _x000D_
  top:20px; _x000D_
  left:20px;_x000D_
}_x000D_
_x000D_
.CellWithComment:hover span.CellComment{_x000D_
  display:block;_x000D_
}
_x000D_
<table id="MyTable">_x000D_
  <caption>Cell 1,2 Has a Comment</caption>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <td>Heading 1</td>_x000D_
      <td>Heading 2</td>_x000D_
      <td>Heading 3</td>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr></tr>_x000D_
      <td>Cell 1,1</td>_x000D_
      <td class="CellWithComment">Cell 1,2_x000D_
        <span class="CellComment">Here is a comment</span>_x000D_
      </td>_x000D_
      <td>Cell 1,3</td>_x000D_
    <tr>_x000D_
      <td>Cell 2,1</td>_x000D_
      <td>Cell 2,2</td>_x000D_
      <td>Cell 2,3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to update a value in a json file and save it through node.js

// read file and make object
let content = JSON.parse(fs.readFileSync('file.json', 'utf8'));
// edit or add property
content.expiry_date = 999999999999;
//write file
fs.writeFileSync('file.json', JSON.stringify(content));

jquery function val() is not equivalent to "$(this).value="?

You want:

this.value = ''; // straight JS, no jQuery

or

$(this).val(''); // jQuery

With $(this).value = '' you're assigning an empty string as the value property of the jQuery object that wraps this -- not the value of this itself.

How do I find the difference between two values without knowing which is larger?

abs(x-y) will do exactly what you're looking for:

In [1]: abs(1-2)
Out[1]: 1

In [2]: abs(2-1)
Out[2]: 1

How to access command line arguments of the caller inside a function?

#!/usr/bin/env bash

echo name of script is $0
echo first argument is $1
echo second argument is $2
echo seventeenth argument is $17
echo number of arguments is $#

Edit: please see my comment on question

CSS: transition opacity on mouse-out?

You're applying transitions only to the :hover pseudo-class, and not to the element itself.

.item {   
  height:200px;
  width:200px;
  background:red; 
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

.item:hover {
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
}

Demo: http://jsfiddle.net/7uR8z/6/

If you don't want the transition to affect the mouse-over event, but only mouse-out, you can turn transitions off for the :hover state :

.item:hover {
  -webkit-transition: none;
  -moz-transition: none;
  -ms-transition: none;
  -o-transition: none;
  transition: none;
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
}

Demo: http://jsfiddle.net/7uR8z/3/

Coding Conventions - Naming Enums

This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.

As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.

So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

Add foo1.c , foo2.c , foo3.c and makefile in one folder the type make in bash

if you do not want to use the makefile, you can run the command

gcc -c foo1.c foo2.c foo3.c

then

gcc -o output foo1.o foo2.o foo3.o

foo1.c

#include <stdio.h>
#include <string.h>

void funk1();

void funk1() {
    printf ("\nfunk1\n");
}


int main(void) {

    char *arg2;
    size_t nbytes = 100;

    while ( 1 ) {

        printf ("\nargv2 = %s\n" , arg2);
        printf ("\n:> ");
        getline (&arg2 , &nbytes , stdin);
        if( strcmp (arg2 , "1\n") == 0 ) {
            funk1 ();
        } else if( strcmp (arg2 , "2\n") == 0 ) {
            funk2 ();
        } else if( strcmp (arg2 , "3\n") == 0 ) {
            funk3 ();
        } else if( strcmp (arg2 , "4\n") == 0 ) {
            funk4 ();
        } else {
            funk5 ();
        }
    }
}

foo2.c

#include <stdio.h>
void funk2(){
    printf("\nfunk2\n");
}
void funk3(){
    printf("\nfunk3\n");
}

foo3.c

#include <stdio.h>

void funk4(){
    printf("\nfunk4\n");
}
void funk5(){
    printf("\nfunk5\n");
}

makefile

outputTest: foo1.o foo2.o foo3.o
    gcc -o output foo1.o foo2.o foo3.o
    make removeO

outputTest.o: foo1.c foo2.c foo3.c
    gcc -c foo1.c foo2.c foo3.c

clean:
    rm -f *.o output

removeO:
    rm -f *.o

how to get text from textview

If it is the sum of all the numbers you want, I made a little snippet for you that can handle both + and - using a regex (I left some print-calls in there to help visualise what happens):

    final String string = "  " + 5 + "\n" + "-" + " " + 9+"\n"+"+"+" "+5; //Or get the value from a TextView
    final Pattern pattern = Pattern.compile("(-?).?(\\d+)");
    Matcher matcher = pattern.matcher(string);

    System.out.print(string);
    System.out.print('\n');
    int sum = 0;

    while( matcher.find() ){
        System.out.print(matcher.group(1));
        System.out.print(matcher.group(2));
        System.out.print('\n');
        sum += Integer.parseInt(matcher.group(1)+matcher.group(2));
    }
    System.out.print("\nSum: "+sum);

This code prints the following:

  5
- 9
+ 5
5
-9
5

Sum: 1

Edit: sorry if I misunderstood your question, it was a little bit unclear what you wanted to do. I assumed you wanted to get the sum of the numbers as an integer rather than a string.

Edit2: to get the numbers separate from each other, do something like this instead:

    final String string = "  " + 5 + "\n" + "-" + " " + 9+"\n"+"+"+" "+5; //Or get the value from a TextView
    final Pattern pattern = Pattern.compile("(-?).?(\\d+)");
    Matcher matcher = pattern.matcher(string);
    ArrayList<Integer> numbers = new ArrayList<Integer>();

    while( matcher.find() ){
        numbers.add(Integer.parseInt(matcher.group(1)+matcher.group(2)));
    }

How to know when a web page was last updated?

Take a look at archive.org

You can find almost everything about the past of a website there.

git discard all changes and pull from upstream

You can do it in a single command:

git fetch --all && git reset --hard origin/master

Or in a pair of commands:

git fetch --all
git reset --hard origin/master

Note than you will lose ALL your local changes

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

How to implement if-else statement in XSLT?

Originally from this blog post. We can achieve if else by using below code

<xsl:choose>
    <xsl:when test="something to test">

    </xsl:when>
    <xsl:otherwise>

    </xsl:otherwise>
</xsl:choose>

So here is what I did

<h3>System</h3>
    <xsl:choose>
        <xsl:when test="autoIncludeSystem/autoincludesystem_info/@mdate"> <!-- if attribute exists-->
            <p>
                <dd><table border="1">
                    <tbody>
                        <tr>
                            <th>File Name</th>
                            <th>File Size</th>
                            <th>Date</th>
                            <th>Time</th>
                            <th>AM/PM</th>
                        </tr>
                        <xsl:for-each select="autoIncludeSystem/autoincludesystem_info">
                            <tr>
                                <td valign="top" ><xsl:value-of select="@filename"/></td>
                                <td valign="top" ><xsl:value-of select="@filesize"/></td>
                                <td valign="top" ><xsl:value-of select="@mdate"/></td>
                                <td valign="top" ><xsl:value-of select="@mtime"/></td>
                                <td valign="top" ><xsl:value-of select="@ampm"/></td>
                            </tr>
                        </xsl:for-each>
                    </tbody>
                </table>
                </dd>
            </p>
        </xsl:when>
        <xsl:otherwise> <!-- if attribute does not exists -->
            <dd><pre>
                <xsl:value-of select="autoIncludeSystem"/><br/>
            </pre></dd> <br/>
        </xsl:otherwise>
    </xsl:choose>

My Output

enter image description here

How to override !important?

Override using JavaScript

$('.mytable td').attr('style', 'display: none !important');

Worked for me.

How to return a boolean method in java?

You can also do this, for readability's sake

boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());

if(!passwordVerified ){
    txtaError.setEditable(true);
    txtaError.setText("*Password didn't match!");
    txtaError.setForeground(Color.red);
    txtaError.setEditable(false);
}else{
    addNewUser();
}
return passwordVerified;

How to delete from multiple tables in MySQL?

I found this article which showing you how to delete data from multiple tables by using MySQL DELETE JOIN statement with good explanation.

enter image description here

What is the difference between Scrum and Agile Development?

As mentioned above by others,

Scrum is an iterative and incremental agile software development method for managing software projects and product or application development. So Scrum is in fact a type of Agile approach which is used widely in software developments.

So, Scrum is a specific flavor of Agile, specifically it is referred to as an agile project management framework.

Also Scrum has mainly two roles inside it, which are: 1. Main/Core Role 2. Ancillary Role

Main/Core role: It consists of mainly three roles: a). Scrum Master, b). Product Owner, c). Development Team.

Ancillary Role: The ancillary roles in Scrum teams are those with no formal role and infrequent involvement in the Scrum procession but nonetheless, they must be taken into account. viz. Stakeholders, Managers.

Scrum Master:- There are 6 types of meetings in scrum:

  • Daily Scrum / Standup
  • Backlog grooming: storyline
  • Scrum of Scrums
  • Sprint Planning meeting
  • Sprint review meeting
  • Sprint retrospective

Let me know if any one need more inputs on this.

Android Studio emulator does not come with Play Store for API 23

Here's the script i used on linux for an instance Nexus 5 API 24 x86 WITHOUT GoogleApis.

#!/bin/sh

~/Android/Sdk/tools/emulator @A24x86 -no-boot-anim -writable-system & #where A24x86 is the name i gave to my instance
~/Android/Sdk/platform-tools/adb wait-for-device
~/Android/Sdk/platform-tools/adb root
~/Android/Sdk/platform-tools/adb shell stop
~/Android/Sdk/platform-tools/adb remount
~/Android/Sdk/platform-tools/adb push ~/gapps/PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/GoogleLoginService.apk /system/priv-app/GoogleLoginService/GoogleLoginService.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/PrebuiltGmsCore /system/priv-app/GoogleServicesFramework"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleLoginService /system/priv-app/Phonesky"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleLoginService/GoogleLoginService.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/Phonesky/Phonesky.apk"
~/Android/Sdk/platform-tools/adb shell start

This one did it for me.

IMPORTANT: in order to stop the app from crashing remember to grant google play services location permissions.

Configuration->Apps->Config(Gear icon)->App permissions->Location->(Top right menú)->Show system->Enable Google Play services

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

thank you everyone I tried running mongo it was not running finally I found there was no space in my hard disc I emptied some of the space and finally re installed it the same installation procedure as followed to install as given in mongodb docs finally restarted the server and it is running.

https://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu

Using iFrames In ASP.NET

How about:

<asp:HtmlIframe ID="yourIframe" runat="server" />

Is supported since .Net Framework 4.5

If you have Problems using this control, you might take a look here.

Failed to connect to mailserver at "localhost" port 25

On windows, nearly all AMPP (Apache,MySQL,PHP,PHPmyAdmin) packages don't include a mail server (but nearly all naked linuxes do have!). So, when using PHP under windows, you need to setup a mail server!

Imo the best and most simple tool ist this: http://smtp4dev.codeplex.com/

SMTP4Dev is a simple one-file mail server tool that does collect the mails it send (so it does not really sends mail, it just keeps them for development). Perfect tool.

How do I get the logfile from an Android device?

Thanks to user1354692 I could made it more easy, with only one line! the one he has commented:

try {
    File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()));
    Runtime.getRuntime().exec("logcat -d -v time -f " + file.getAbsolutePath());}catch (IOException e){}

How can I list all collections in the MongoDB shell?

 1. show collections; // Display all collections
 2. show tables     // Display all collections
 3. db.getCollectionNames();   // Return array of collection. Example :[ "orders", "system.profile" ]

Detailed information for every collection:

db.runCommand( { listCollections: 1.0, authorizedCollections: true, nameOnly: true } )
  • For users with the required access (privileges that grant listCollections action on the database), the method lists the names of all collections for the database.
  • For users without the required access, the method lists only the collections for which the users has privileges. For example, if a user has find on a specific collection in a database, the method would return just that collection.

To list collections list based on a search string.

db.getCollectionNames().filter(function (CollectionName) { return /<Search String>/.test(CollectionName) })

Example: Find all collection having "import" in the name

db.getCollectionNames().filter(function (CollectionName) { return /import/.test(CollectionName) })

Convert string to hex-string in C#

var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));

OR

var result  =string.Join("", 
                input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));

Why is Dictionary preferred over Hashtable in C#?

Since .NET Framework 3.5 there is also a HashSet<T> which provides all the pros of the Dictionary<TKey, TValue> if you need only the keys and no values.

So if you use a Dictionary<MyType, object> and always set the value to null to simulate the type safe hash table you should maybe consider switching to the HashSet<T>.

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

base_url() function not working in codeigniter

If you don't want to use the url helper, you can get the same results by using the following variable:

$this->config->config['base_url']

It will return the base url for you with no extra steps required.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

How are parameters sent in an HTTP POST request?

Some of the webservices require you to place request data and metadata separately. For example a remote function may expect that the signed metadata string is included in a URI, while the data is posted in a HTTP-body.

The POST request may semantically look like this:

POST /?AuthId=YOURKEY&Action=WebServiceAction&Signature=rcLXfkPldrYm04 HTTP/1.1
Content-Type: text/tab-separated-values; charset=iso-8859-1
Content-Length: []
Host: webservices.domain.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)

name    id
John    G12N
Sarah   J87M
Bob     N33Y

This approach logically combines QueryString and Body-Post using a single Content-Type which is a "parsing-instruction" for a web-server.

Please note: HTTP/1.1 is wrapped with the #32 (space) on the left and with #10 (Line feed) on the right.

How do you create a daemon in Python?

I am afraid the daemon module mentioned by @Dustin didn't work for me. Instead I installed python-daemon and used the following code:

# filename myDaemon.py
import sys
import daemon
sys.path.append('/home/ubuntu/samplemodule') # till __init__.py
from samplemodule import moduleclass 

with daemon.DaemonContext():
    moduleclass.do_running() # I have do_running() function and whatever I was doing in __main__() in module.py I copied in it.

Running is easy

> python myDaemon.py

just for completeness here is samplemodule directory content

>ls samplemodule
__init__.py __init__.pyc moduleclass.py

The content of moduleclass.py can be

class moduleclass():
    ...

def do_running():
    m = moduleclass()
    # do whatever daemon is required to do.

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

Wordpress keeps redirecting to install-php after migration

It seems that in general, this happens when Wordpress doesn't find the site information in the expected places (tables) in the database. It thinks no site has been created yet, so it starts going through the installation process.

This situation means that:

  1. Wordpress WAS ABLE to connect to a database. If it didn't, it would say there was an error and refuse to install or do anything else

AND

  1. it didn't find the things it was looking for in the expected places in the database it connected to.

Just to be clear, both 1) and 2) are happening when you see this symptom.

Possible causes:

  • Wrong database. You're working on several projects and you copied and pasted wrong database name, database host, or table prefix to the wp-config file. So now, you're unwittingly destroying ANOTHER client's website while agonizing over why isn't THIS website working at all.

  • Wrong database prefix. You can put several Wordpress sites in one database by using different prefixes for each. Make sure the tables in the database have the same prefixes as you entered in your wp-config. So, if wp-config says: $table_prefix = 'wp_'; Check that the tables in your database are called "wp_options", etc. and not "WP_options", "mysite_options" or something like that.

  • The data in the database is corrupted. Maybe you messed up while importing the sql dump, you imported a truncated file, a file belonging to some other project, or whatever.

Pass a simple string from controller to a view MVC3

If you are trying to simply return a string to a View, try this:

public string Test()
{
     return "test";
}

This will return a view with the word test in it. You can insert some html in the string.

You can also try this:

public ActionResult Index()
{
    return Content("<html><b>test</b></html>");
}