Programs & Examples On #Ibm doors

DXL (DOORS Extension Language) is a scripting language for IBM Rational DOORS.

How to get Wikipedia content using Wikipedia's API?

You can download the Wikipedia database directly and parse all pages to XML with Wiki Parser, which is a standalone application. The first paragraph is a separate node in the resulting XML.

Alternatively, you can extract the first paragraph from its plain-text output.

How do I get the absolute directory of a file in bash?

To get the full path use:

readlink -f relative/path/to/file

To get the directory of a file:

dirname relative/path/to/file

You can also combine the two:

dirname $(readlink -f relative/path/to/file)

If readlink -f is not available on your system you can use this*:

function myreadlink() {
  (
  cd "$(dirname $1)"         # or  cd "${1%/*}"
  echo "$PWD/$(basename $1)" # or  echo "$PWD/${1##*/}"
  )
}

Note that if you only need to move to a directory of a file specified as a relative path, you don't need to know the absolute path, a relative path is perfectly legal, so just use:

cd $(dirname relative/path/to/file)

if you wish to go back (while the script is running) to the original path, use pushd instead of cd, and popd when you are done.


* While myreadlink above is good enough in the context of this question, it has some limitation relative to the readlink tool suggested above. For example it doesn't correctly follow a link to a file with different basename.

Git add and commit in one command

pretty sure you can use:

git commit -am "commit all the things"

What's the best way to cancel event propagation between nested ng-click calls?

Use $event.stopPropagation():

<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
    <img src="http://some_src" ng-click="nextImage(); $event.stopPropagation()" />
</div>

Here's a demo: http://plnkr.co/edit/3Pp3NFbGxy30srl8OBmQ?p=preview

ASP.NET MVC controller actions that return JSON or partial html

    public ActionResult GetExcelColumn()
    {            
            List<string> lstAppendColumn = new List<string>();
            lstAppendColumn.Add("First");
            lstAppendColumn.Add("Second");
            lstAppendColumn.Add("Third");
  return Json(new { lstAppendColumn = lstAppendColumn,  Status = "Success" }, JsonRequestBehavior.AllowGet);
            }
        }

Is Eclipse the best IDE for Java?

IntelliJ is good one but its not free!!Then NetBeans is also a good option.Also if you are IBM suite WSAD is good

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

bchhun's answer got me on the right track, but I wanted to check for actual space available between the source and the viewport edge. I also wanted to respect the data-placement attribute as a preference with appropriate fallbacks if there wasn't enough space. That way "right" would always go right unless there wasn't enough space for the popover to show on the right side, for example. This was the way I handled it. It works for me, but it feels a bit cumbersome. If anyone has any ideas for a cleaner, more concise solution, I'd be interested to see it.

var options = {
  placement: function (context, source) {
    var $win, $source, winWidth, popoverWidth, popoverHeight, offset, toRight, toLeft, placement, scrollTop;

    $win = $(window);
    $source = $(source);
    placement = $source.attr('data-placement');
    popoverWidth = 400;
    popoverHeight = 110;
    offset = $source.offset();

    // Check for horizontal positioning and try to use it.
    if (placement.match(/^right|left$/)) {
      winWidth = $win.width();
      toRight = winWidth - offset.left - source.offsetWidth;
      toLeft = offset.left;

      if (placement === 'left') {
        if (toLeft > popoverWidth) {
          return 'left';
        }
        else if (toRight > popoverWidth) {
          return 'right';
        }
      }
      else {
        if (toRight > popoverWidth) {
          return 'right';
        }
        else if (toLeft > popoverWidth) {
          return 'left';
        }
      }
    }

    // Handle vertical positioning.
    scrollTop = $win.scrollTop();
    if (placement === 'bottom') {
      if (($win.height() + scrollTop) - (offset.top + source.offsetHeight) > popoverHeight) {
        return 'bottom';
      }
      return 'top';
    }
    else {
      if (offset.top - scrollTop > popoverHeight) {
        return 'top';
      }
      return 'bottom';
    }
  },
  trigger: 'click'
};
$('.infopoint').popover(options);

PHP If Statement with Multiple Conditions

I don't know if $var is a string and you want to find only those expressions but here it goes either way.

Try to use preg_match http://php.net/manual/en/function.preg-match.php

if(preg_match('abc', $val) || preg_match('def', $val) || ...)
   echo "true"

html table cell width for different rows

with 5 columns and colspan, this is possible (click here) (but doesn't make much sense to me):

<table width="100%" border="1" bgcolor="#ffffff">
    <colgroup>
        <col width="25%">
        <col width="25%">
        <col width="25%">
        <col width="5%">
        <col width="20%">
    </colgroup>
    <tr>
        <td>25</td>
        <td colspan="2">50</td>
        <td colspan="2">25</td>     
    </tr>
    <tr>
        <td colspan="2">50</td>
        <td colspan="2">30</td>
        <td>20</td>
    </tr>
</table>

What is difference between mutable and immutable String in java


String in Java is immutable. However what does it mean to be mutable in programming context is the first question. Consider following class,

public class Dimension {
    private int height;

    private int width;

    public Dimenstion() {
    }

    public void setSize(int height, int width) {
        this.height = height;
        this.width = width;
    }

    public getHeight() {
        return height;
    }

    public getWidth() {
        return width;
    }
}

Now after creating the instance of Dimension we can always update it's attributes. Note that if any of the attribute, in other sense state, can be updated for instance of the class then it is said to be mutable. We can always do following,

Dimension d = new Dimension();
d.setSize(10, 20);// Dimension changed
d.setSize(10, 200);// Dimension changed
d.setSize(100, 200);// Dimension changed

Let's see in different ways we can create a String in Java.

String str1 = "Hey!";
String str2 = "Jack";
String str3 = new String("Hey Jack!");
String str4 = new String(new char[] {'H', 'e', 'y', '!'});
String str5 = str1 + str2;
str1 = "Hi !";
// ...

So,

  1. str1 and str2 are String literals which gets created in String constant pool
  2. str3, str4 and str5 are String Objects which are placed in Heap memory
  3. str1 = "Hi!"; creates "Hi!" in String constant pool and it's totally different reference than "Hey!" which str1 referencing earlier.

Here we are creating the String literal or String Object. Both are different, I would suggest you to read following post to understand more about it.

In any String declaration, one thing is common, that it does not modify but it gets created or shifted to other.

String str = "Good"; // Create the String literal in String pool
str = str + " Morning"; // Create String with concatenation of str + "Morning"
|_____________________|
       |- Step 1 : Concatenate "Good"  and " Morning" with StringBuilder
       |- Step 2 : assign reference of created "Good Morning" String Object to str

How String became immutable ?

It's non changing behaviour, means, the value once assigned can not be updated in any other way. String class internally holds data in character array. Moreover, class is created to be immutable. Take a look at this strategy for defining immutable class.

Shifting the reference does not mean you changed it's value. It would be mutable if you can update the character array which is behind the scene in String class. But in reality that array will be initialized once and throughout the program it remains the same.

Why StringBuffer is mutable ?

As you already guessed, StringBuffer class is mutable itself as you can update it's state directly. Similar to String it also holds value in character array and you can manipulate that array by different methods i.e. append, delete, insert etc. which directly changes the character value array.

Switching users inside Docker image to a non-root user

As a different approach to the other answer, instead of indicating the user upon image creation on the Dockerfile, you can do so via command-line on a particular container as a per-command basis.

With docker exec, use --user to specify which user account the interactive terminal will use (the container should be running and the user has to exist in the containerized system):

docker exec -it --user [username] [container] bash

See https://docs.docker.com/engine/reference/commandline/exec/

HTTP Error 404 when running Tomcat from Eclipse

Check the server configuration and folders' routes:

  1. Open servers view (Window -> Open view... -> Others... -> Search for 'servers'.

  2. Right click on server (mine is Tomcat v6.0) -> properties -> Click on 'Swicth Location' (check that location's like /servers...

  3. Double click on the server. This will open a new servers page. In the 'Servers Locations' area, check the 'Use Tomcat Installation (takes control of Tomcat Installation)' option.

  4. Restart your server.

  5. Enjoy!

Redirect to Action in another controller

Use this:

return RedirectToAction("LogIn", "Account", new { area = "" });

This will redirect to the LogIn action in the Account controller in the "global" area.

It's using this RedirectToAction overload:

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    Object routeValues
)

MSDN

How to use Git for Unity3D source control?

Only the Assets and ProjectSettings folders need to be under git version control.

You can make a gitignore like this.

[Ll]ibrary/
[Tt]emp/
[Oo]bj/

# Autogenerated VS/MD solution and project files
*.csproj
*.unityproj
*.sln
*.suo
*.userprefs

# Mac
.DS_Store
*.swp
*.swo

Thumbs.db
Thumbs.db.meta

.vs/

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Force add despite the .gitignore file

See man git-add:

   -f, --force
       Allow adding otherwise ignored files.

So run this

git add --force my/ignore/file.foo

Truncating a table in a stored procedure

All DDL statements in Oracle PL/SQL should use Execute Immediate before the statement. Hence you should use:

execute immediate 'truncate table schema.tablename';

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

Delete %LocalAppData%\Microsoft\VisualStudio\14.0\ComponentModelCache and restart Visual Studio.

Alternatively, use the Clear MEF Component Cache extension.

Searching for Text within Oracle Stored Procedures

 SELECT * FROM ALL_source WHERE UPPER(text) LIKE '%BLAH%'

EDIT Adding additional info:

 SELECT * FROM DBA_source WHERE UPPER(text) LIKE '%BLAH%'

The difference is dba_source will have the text of all stored objects. All_source will have the text of all stored objects accessible by the user performing the query. Oracle Database Reference 11g Release 2 (11.2)

Another difference is that you may not have access to dba_source.

How to trigger SIGUSR1 and SIGUSR2?

terminal 1

dd if=/dev/sda of=debian.img

terminal 2

killall -SIGUSR1 dd

go back to terminal 1

34292201+0 records in
34292200+0 records out
17557606400 bytes (18 GB) copied, 1034.7 s, 17.0 MB/s

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

Visual Studio Code pylint: Unable to import 'protorpc'

Open the settings file of your Visual Studio Code (settings.json) and add the library path to the "python.autoComplete.extraPaths" list.

"python.autoComplete.extraPaths": [
    "~/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2",
    "~/google-cloud-sdk/platform/google_appengine",
    "~/google-cloud-sdk/lib",
    "~/google-cloud-sdk/platform/google_appengine/lib/endpoints-1.0",
    "~/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0"
],

Get only specific attributes with from Laravel Collection

use User::get(['id', 'name', 'email']), it will return you a collection with the specified columns and if you want to make it an array, just use toArray() after the get() method like so:

User::get(['id', 'name', 'email'])->toArray()

Most of the times, you won't need to convert the collection to an array because collections are actually arrays on steroids and you have easy-to-use methods to manipulate the collection.

Send email by using codeigniter library via localhost

$insert = $this->db->insert('email_notification', $data);
                $this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");

                //require ("plugins/mailer/PHPMailerAutoload.php");
                $mail = new PHPMailer;
                $mail->SMTPOptions = array(
                    'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                ),
                );

                $message="
                     Your Account Has beed created successfully by Admin:
                    Username: ".$this->input->post('username')." <br><br>
                    Email: ".$this->input->post('sender_email')." <br><br>
                    Regargs<br>
                    <div class='background-color:#666;color:#fff;padding:6px;
                    text-align:center;'>
                         Bookly Admin.
                    </div>
                ";
                $mail->isSMTP(); // Set mailer to use SMTP
                $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
                $mail->SMTPAuth = true; 
                $subject = "Hello  ".$this->input->post('username');
                $mail->SMTDebug=2;
                $email = $this->input->post('sender_email'); //this email is user email
                $from_label = "Account Creation";
                $mail->Username = 'your email'; // SMTP username
                $mail->Password = 'password'; // SMTP password
                $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
                $mail->Port = 465;
                $mail->setFrom($from_label);
                $mail->addAddress($email, 'Bookly Admin');
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message;
                $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
             if($mail->send()){

                  }

Inheriting constructors

Constructors are not inherited. They are called implicitly or explicitly by the child constructor.

The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.

class A
{
public: 
    explicit A(int x) {}
};

class B: public A
{
public:
    explicit B(int x) : A(x) { }
};

UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

Your mail won't be sent online unless you complete the two-step verification for your g-mail account and use that password.

Reading NFC Tags with iPhone 6 / iOS 8

At the moment, Apple has not opened any access to the embedded NFC chip to developers as suggested by many articles such as these ones :

The list goes on. The main reason seems (like lots the other hardware features added to the iPhone in the past) that Apple wants to ensure the security of such technology before releasing any API for developers to let them do whatever they want. So at first, they will use it internally for their needs only (such as Apple Pay at launch time).

"At the moment, there isn't any open access to the NFC controller," said RapidNFC, a provider of NFC tags. "There are currently no NFC APIs in the iOS 8 GM SDK".

But eventually, I think we can all agree that they will develop such API, it's only a matter of time.

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

  • View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.

  • Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

  • ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().

Data-frame Object has no Attribute

Quick fix: Change how excel converts imported files. Go to 'File', then 'Options', then 'Advanced'. Scroll down and uncheck 'Use system seperators'. Also change 'Decimal separator' to '.' and 'Thousands separator' to ',' . Then simply 're-save' your file in the CSV (Comma delimited) format. The root cause is usually associated with how the csv file is created. Trust that helps. Point is, why use extra code if not necessary? Cross-platform understanding and integration is key in engineering/development.

how to set radio option checked onload with jQuery

 $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);

Mercurial undo last commit

Since you can't rollback you should merge that commit into the new head you got when you pulled. If you don't want any of the work you did in it you can easily do that using this tip.

So if you've pulled and updated to their head you can do this:

hg --config ui.merge=internal:local merge

keeps all the changes in the currently checked out revision, and none of the changes in the not-checked-out revision (the one you wrote that you no longer want).

This is a great way to do it because it keeps your history accurate and complete. If 2 years from now someone finds a bug in what you pulled down you can look in your (unused but saved) implementation of the same thing and go, "oh, I did it right". :)

How to set default value for form field in Symfony2?

Can be use during the creation easily with :

->add('myfield', 'text', array(
     'label' => 'Field',
     'empty_data' => 'Default value'
))

Array Length in Java

It should be:

int a = arr.length;

Parenthesis should be avoided.

VB.net Need Text Box to Only Accept Numbers

Simplest ever solution for TextBox Validation in VB.NET

TextBox Validation for Visual Basic (VB.NET)

First, add new VB code file in your project.

  1. Go To Solution Explorer
  2. Right Click to your project
  3. Select Add > New item...
  4. Add new VB code file (i.e. example.vb)

or press Ctrl+Shift+A

COPY & PASTE following code into this file and give it a suitable name. (i.e. KeyValidation.vb)

Imports System.Text.RegularExpressions
Module Module1
    Public Enum ValidationType
        Only_Numbers = 1
        Only_Characters = 2
        Not_Null = 3
        Only_Email = 4
        Phone_Number = 5
    End Enum
    Public Sub AssignValidation(ByRef CTRL As Windows.Forms.TextBox, ByVal Validation_Type As ValidationType)
        Dim txt As Windows.Forms.TextBox = CTRL
        Select Case Validation_Type
            Case ValidationType.Only_Numbers
                AddHandler txt.KeyPress, AddressOf number_Leave
            Case ValidationType.Only_Characters
                AddHandler txt.KeyPress, AddressOf OCHAR_Leave
            Case ValidationType.Not_Null
                AddHandler txt.Leave, AddressOf NotNull_Leave
            Case ValidationType.Only_Email
                AddHandler txt.Leave, AddressOf Email_Leave
            Case ValidationType.Phone_Number
                AddHandler txt.KeyPress, AddressOf Phonenumber_Leave
        End Select
    End Sub
    Public Sub number_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Dim numbers As Windows.Forms.TextBox = sender
        If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub Phonenumber_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Dim numbers As Windows.Forms.TextBox = sender
        If InStr("1234567890.()-+ ", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub OCHAR_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If InStr("1234567890!@#$%^&*()_+=-", e.KeyChar) > 0 Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub NotNull_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim No As Windows.Forms.TextBox = sender
        If No.Text.Trim = "" Then
            MsgBox("This field Must be filled!")
            No.Focus()
        End If
    End Sub
    Public Sub Email_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Email As Windows.Forms.TextBox = sender
        If Email.Text <> "" Then
            Dim rex As Match = Regex.Match(Trim(Email.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
            If rex.Success = False Then
                MessageBox.Show("Please Enter a valid Email Address", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Email.BackColor = Color.Red
                Email.Focus()
                Exit Sub
            Else
                Email.BackColor = Color.White
            End If
        End If
    End Sub
End Module

Now use following code to Form Load Event like below.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AssignValidation(Me.TextBox1, ValidationType.Only_Digits)
        AssignValidation(Me.TextBox2, ValidationType.Only_Characters)
        AssignValidation(Me.TextBox3, ValidationType.No_Blank)
        AssignValidation(Me.TextBox4, ValidationType.Only_Email)
End Sub

Done..!

Django URL Redirect

If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:

(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),  

You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:

(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),  

This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

I got this error when working in the Designer. I had been developing in VS 2012, but "upgraded" to 2017 over the past couple days. Solution was to close and reopen VS.

It may be related to a bug which I've seen reported elsewhere, where the Reference Manager does not work? In that situation, the following error message is encountered when trying to add a reference in the Solution Explorer:

"Error HRESULT E_FAIL has been returned from a call to a COM component."

My workaround was to close the solution, reopen in VS2012, add the reference, close 2012 and reopen 2017. Ridiculous that 2017 should have been released with such an obvious bug.

Magento: get a static block as html in a phtml file

Following code will work when you Call CMS-Static Block in Magento.

<?php echo 

$this->getLayout()->createBlock('cms/block')->setBlockId('block_identifier')->toHtml();

?>

How can strings be concatenated?

For cases of appending to end of existing string:

string = "Sec_"
string += "C_type"
print(string)

results in

Sec_C_type

PHP How to fix Notice: Undefined variable:

I would guess your query isn't running as expected and you are getting to the return line with undefined variables.

Also, the way you are doing the variable assignment, you would be overwriting the same variable with each loop iteration, so you wouldn't return the entire result set.

Finally, it seems odd to return a numerically-keyed result set instead of an associatively-keyed one. Consider naming only the fields needed in the SELECT and keeping the key assignments. So something like this:

Function ShowDataPatient($idURL){
       $query =" select * from cmu_list_insurance,cmu_home,cmu_patient where cmu_home.home_id = (select home_id from cmu_patient where patient_hn like '%$idURL%')
                 AND cmu_patient.patient_hn like '%$idURL%'
                 AND cmu_list_insurance.patient_id like (select patient_id from cmu_patient where patient_hn like '%$idURL%') ";

   $result = pg_query($query) or die('Query failed: ' . pg_last_error());

   $return = array();
   while ($row = pg_fetch_array($result)){
       $return[] = $row;
   }          

   return $return;
}

You might also consider opening a question about how to improve your query, is it is pretty heinous as it stands now.

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

enum Values to NSString (iOS)

If I can offer another solution that has the added benefit of type checking, warnings if you are missing an enum value in your conversion, readability, and brevity.

For your given example: typedef enum { value1, value2, value3 } myValue; you can do this:

NSString *NSStringFromMyValue(myValue type) {
    const char* c_str = 0;
#define PROCESS_VAL(p) case(p): c_str = #p; break;
    switch(type) {
            PROCESS_VAL(value1);
            PROCESS_VAL(value2);
            PROCESS_VAL(value3);
    }
#undef PROCESS_VAL

    return [NSString stringWithCString:c_str encoding:NSASCIIStringEncoding];
}

As a side note. It is a better approach to declare your enums as so:

typedef NS_ENUM(NSInteger, MyValue) {
    Value1 = 0,
    Value2,
    Value3
}

With this you get type-safety (NSInteger in this case), you set the expected enum offset (= 0).

Really killing a process in Windows

setup an AT command to run task manager or process explorer as SYSTEM.

AT 12:34 /interactive "C:/procexp.exe"

If process explorer was in your root C drive then this would open it as SYSTEM and you could kill any process without getting any access denied errors. Set this for like a minute in the future, then it will pop up for you.

Changing navigation bar color in Swift

My two cents:

a) setting navigationBar.barTintColor / titleTextAttributes do work in any view (pushed, added..and so on in init..

b) setting appearence does not work everywhere:

  • You can call it on AppDelegate
  • " " 1st level view
  • if You call it again in subsequent pushed views, does MNOT work

SwiftUI note:

a) does not apply (no navigationBar, unless you pass via UIViewControllerRepresentable trick..) b) is valid for SwiftUI: same behaviour.

Uninstall Node.JS using Linux command line?

I think Manoj Gupta had the best answer from what I'm seeing. However, the remove command doesn't get rid of any configuration folders or files that may be leftover. Use:

sudo apt-get purge --auto-remove nodejs

The purge command should remove the package and then clean up any configuration files. (see this question for more info on the difference between purge and remove). The auto-remove flag will do the same for packages that were installed by NodeJS.

See the accepted answer on this question for a better explanation.

Although don't forget to handle NPM! Josh's answer covers that.

psql: could not connect to server: No such file or directory (Mac OS X)

I was facing a similar issue here I solved this issue as below.

Actually the postgres process is dead, to see the status of postgres run the following command

sudo /etc/init.d/postgres status

It will says the process is dead`just start the process

sudo /etc/init.d/postgres start

When should I use a struct rather than a class in C#?

Structure types in C# or other .net languages are generally used to hold things that should behave like fixed-sized groups of values. A useful aspect of structure types is that the fields of a structure-type instance can be modified by modifying the storage location in which it is held, and in no other way. It's possible to code a structure in such a way that the only way to mutate any field is to construct a whole new instance and then use a struct assignment to mutate all the fields of the target by overwriting them with values from the new instance, but unless a struct provides no means of creating an instance where its fields have non-default values, all of its fields will be mutable if and if the struct itself is stored in a mutable location.

Note that it's possible to design a structure type so that it will essentially behave like a class type, if the structure contains a private class-type field, and redirects its own members to that of the wrapped class object. For example, a PersonCollection might offer properties SortedByName and SortedById, both of which hold an "immutable" reference to a PersonCollection (set in their constructor) and implement GetEnumerator by calling either creator.GetNameSortedEnumerator or creator.GetIdSortedEnumerator. Such structs would behave much like a reference to a PersonCollection, except that their GetEnumerator methods would be bound to different methods in the PersonCollection. One could also have a structure wrap a portion of an array (e.g. one could define an ArrayRange<T> structure which would hold a T[] called Arr, an int Offset, and an int Length, with an indexed property which, for an index idx in the range 0 to Length-1, would access Arr[idx+Offset]). Unfortunately, if foo is a read-only instance of such a structure, current compiler versions won't allow operations like foo[3]+=4; because they have no way to determine whether such operations would attempt to write to fields of foo.

It's also possible to design a structure to behave a like a value type which holds a variable-sized collection (which will appear to be copied whenever the struct is) but the only way to make that work is to ensure that no object to which the struct holds a reference will ever be exposed to anything which might mutate it. For example, one could have an array-like struct which holds a private array, and whose indexed "put" method creates a new array whose content is like that of the original except for one changed element. Unfortunately, it can be somewhat difficult to make such structs perform efficiently. While there are times that struct semantics can be convenient (e.g. being able to pass an array-like collection to a routine, with the caller and callee both knowing that outside code won't modify the collection, may be better than requiring both caller and callee to defensively copy any data they're given), the requirement that class references point to objects that will never be mutated is often a pretty severe constraint.

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

How to configure custom PYTHONPATH with VM and PyCharm?

Latest 12/2019 selections for PYTHONPATH for a given interpreter. enter image description here

Various ways to remove local Git changes

Reason for adding an answer at this moment:

So far I was adding the conclusion and ‘answers’ to my initial question itself, making the question very lengthy, hence moving to separate answer.

I have also added more frequently used git commands that helps me on git, to help someone else too.

Basically to clean all local commits $ git reset --hard and $ git clean -d -f


First step before you do any commits is to configure your username and email that appears along with your commit.

#Sets the name you want attached to your commit transactions

$ git config --global user.name "[name]"

#Sets the email you want atached to your commit transactions

$ git config --global user.email "[email address]"

#List the global config

$ git config --list

#List the remote URL

$ git remote show origin

#check status

git status

#List all local and remote branches

git branch -a

#create a new local branch and start working on this branch

git checkout -b "branchname" 

or, it can be done as a two step process

create branch: git branch branchname work on this branch: git checkout branchname

#commit local changes [two step process:- Add the file to the index, that means adding to the staging area. Then commit the files that are present in this staging area]

git add <path to file>

git commit -m "commit message"

#checkout some other local branch

git checkout "local branch name"

#remove all changes in local branch [Suppose you made some changes in local branch like adding new file or modifying existing file, or making a local commit, but no longer need that] git clean -d -f and git reset --hard [clean all local changes made to the local branch except if local commit]

git stash -u also removes all changes

Note: It's clear that we can use either (1) combination of git clean –d –f and git reset --hard OR (2) git stash -u to achieve the desired result.

Note 1: Stashing, as the word means 'Store (something) safely and secretly in a specified place.' This can always be retreived using git stash pop. So choosing between the above two options is developer's call.

Note 2: git reset --hard will delete working directory changes. Be sure to stash any local changes you want to keep before running this command.

# Switch to the master branch and make sure you are up to date.

git checkout master

git fetch [this may be necessary (depending on your git config) to receive updates on origin/master ]

git pull

# Merge the feature branch into the master branch.

git merge feature_branch

# Reset the master branch to origin's state.

git reset origin/master

#Accidentally deleted a file from local , how to retrieve it back? Do a git status to get the complete filepath of the deleted resource

git checkout branchname <file path name>

that's it!

#Merge master branch with someotherbranch

git checkout master
git merge someotherbranchname

#rename local branch

git branch -m old-branch-name new-branch-name

#delete local branch

git branch -D branch-name

#delete remote branch

git push origin --delete branchname

or

git push origin :branch-name

#revert a commit already pushed to a remote repository

git revert hgytyz4567

#branch from a previous commit using GIT

git branch branchname <sha1-of-commit>

#Change commit message of the most recent commit that's already been pushed to remote

git commit --amend -m "new commit message"
git push --force origin <branch-name>

# Discarding all local commits on this branch [Removing local commits]

In order to discard all local commits on this branch, to make the local branch identical to the "upstream" of this branch, simply run

git reset --hard @{u}

Reference: http://sethrobertson.github.io/GitFixUm/fixup.html or do git reset --hard origin/master [if local branch is master]

# Revert a commit already pushed to a remote repository?

$ git revert ab12cd15

#Delete a previous commit from local branch and remote branch

Use-Case: You just commited a change to your local branch and immediately pushed to the remote branch, Suddenly realized , Oh no! I dont need this change. Now do what?

git reset --hard HEAD~1 [for deleting that commit from local branch. 1 denotes the ONE commit you made]

git push origin HEAD --force [both the commands must be executed. For deleting from remote branch]. Currently checked out branch will be referred as the branch where you are making this operation.

#Delete some of recent commits from local and remote repo and preserve to the commit that you want. ( a kind of reverting commits from local and remote)

Let's assume you have 3 commits that you've pushed to remote branch named 'develop'

commitid-1 done at 9am
commitid-2 done at 10am
commitid-3 done at 11am. // latest commit. HEAD is current here.

To revert to old commit ( to change the state of branch)

git log --oneline --decorate --graph // to see all your commitids

git clean -d -f // clean any local changes

git reset --hard commitid-1 // locally reverting to this commitid

git push -u origin +develop // push this state to remote. + to do force push

# Remove local git merge: Case: I am on master branch and merged master branch with a newly working branch phase2

$ git status

On branch master

$ git merge phase2 $ git status

On branch master

Your branch is ahead of 'origin/master' by 8 commits.

Q: How to get rid of this local git merge? Tried git reset --hard and git clean -d -f Both didn't work. The only thing that worked are any of the below ones:

$ git reset --hard origin/master

or

$ git reset --hard HEAD~8

or

$ git reset --hard 9a88396f51e2a068bb7 [sha commit code - this is the one that was present before all your merge commits happened]

#create gitignore file

touch .gitignore // create the file in mac or unix users

sample .gitignore contents:

.project
*.py
.settings

Reference link to GIT cheat sheet: https://services.github.com/on-demand/downloads/github-git-cheat-sheet.pdf

Get an array of list element contents in jQuery

And in clean javascript:

var texts = [], lis = document.getElementsByTagName("li");
for(var i=0, im=lis.length; im>i; i++)
  texts.push(lis[i].firstChild.nodeValue);

alert(texts);

How to Clear Console in Java?

Try this code

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}

Now when the Java process is connected to a console, it will clear the console.

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

in my case, I must to set path in properties file, in many hours I find the way:

application.properties file:

webdriver.gecko.driver="/lib/geckodriver-v0.26.0-win64/geckodriver.exe"

in java code:

private static final Logger log = Logger.getLogger(Login.class.getName());
private FirefoxDriver driver;
private FirefoxProfile firefoxProfile;
private final String BASE_URL = "https://www.myweb.com/";
private static final String RESOURCE_NAME = "main/resources/application.properties"; // could also be a constant
private Properties properties;

public Login() {
    init();
}

private void init() {
    properties = new Properties();
    try(InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME)) {
        properties.load(resourceStream);
    } catch (IOException e) {
        System.err.println("Could not open Config file");
        log.log(Level.SEVERE, "Could not open Config file", e);
    }
    // open incognito tab by default
    firefoxProfile = new FirefoxProfile();
    firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
    // geckodriver driver path to run
    String gekoDriverPath = properties.getProperty("webdriver.gecko.driver");
    log.log(Level.INFO, gekoDriverPath);
    System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + gekoDriverPath);
    log.log(Level.INFO, System.getProperty("webdriver.gecko.driver"));
    System.setProperty("webdriver.gecko.driver", System.getProperty("webdriver.gecko.driver").replace("\"", ""));
    if (driver == null) {
        driver = new FirefoxDriver();
    }

}

Iterating a JavaScript object's properties using jQuery

Note: Most modern browsers will now allow you to navigate objects in the developer console. This answer is antiquated.

This method will walk through object properties and write them to the console with increasing indent:

function enumerate(o,s){

    //if s isn't defined, set it to an empty string
    s = typeof s !== 'undefined' ? s : "";

    //if o is null, we need to output and bail
    if(typeof o == "object" && o === null){

       console.log(s+k+": null");

    } else {    

        //iterate across o, passing keys as k and values as v
        $.each(o, function(k,v){

            //if v has nested depth
           if(typeof v == "object" && v !== null){

                //write the key to the console
                console.log(s+k+": ");

                //recursively call enumerate on the nested properties
                enumerate(v,s+"  ");

            } else {

                //log the key & value
                console.log(s+k+": "+String(v));
            }
        });
    }
}

Just pass it the object you want to iterate through:

    var response = $.ajax({
        url: myurl,
        dataType: "json"
    })
    .done(function(a){
       console.log("Returned values:");
       enumerate(a);
    })
    .fail(function(){ console.log("request failed");});

How to wait until an element exists?

I used this approach to wait for an element to appear so I can execute the other functions after that.

Let's say doTheRestOfTheStuff(parameters) function should only be called after the element with ID the_Element_ID appears or finished loading, we can use,

var existCondition = setInterval(function() {
 if ($('#the_Element_ID').length) {
    console.log("Exists!");
    clearInterval(existCondition);
    doTheRestOfTheStuff(parameters);
 }
}, 100); // check every 100ms

Java 8 LocalDate Jackson format

I was never able to get this to work simple using annotations. To get it to work, I created a ContextResolver for ObjectMapper, then I added the JSR310Module (update: now it is JavaTimeModule instead), along with one more caveat, which was the need to set write-date-as-timestamp to false. See more at the documentation for the JSR310 module. Here's an example of what I used.

Dependency

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.4.0</version>
</dependency>

Note: One problem I faced with this is that the jackson-annotation version pulled in by another dependency, used version 2.3.2, which cancelled out the 2.4 required by the jsr310. What happened was I got a NoClassDefFound for ObjectIdResolver, which is a 2.4 class. So I just needed to line up the included dependency versions

ContextResolver

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {  
    private final ObjectMapper MAPPER;

    public ObjectMapperContextResolver() {
        MAPPER = new ObjectMapper();
        // Now you should use JavaTimeModule instead
        MAPPER.registerModule(new JSR310Module());
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return MAPPER;
    }  
}

Resource class

@Path("person")
public class LocalDateResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getPerson() {
        Person person = new Person();
        person.birthDate = LocalDate.now();
        return Response.ok(person).build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createPerson(Person person) {
        return Response.ok(
                DateTimeFormatter.ISO_DATE.format(person.birthDate)).build();
    }

    public static class Person {
        public LocalDate birthDate;
    }
}

Test

curl -v http://localhost:8080/api/person
Result: {"birthDate":"2015-03-01"}

curl -v -POST -H "Content-Type:application/json" -d "{\"birthDate\":\"2015-03-01\"}" http://localhost:8080/api/person
Result: 2015-03-01


See also here for JAXB solution.

UPDATE

The JSR310Module is deprecated as of version 2.7 of Jackson. Instead, you should register the module JavaTimeModule. It is still the same dependency.

self.tableView.reloadData() not working in Swift

In my case the table was updated correctly, but setNeedDisplay() was not called for the image so I mistakenly thought that the data was not reloaded.

How to merge multiple lists into one list in python?

a = ['it']
b = ['was']
c = ['annoying']

a.extend(b)
a.extend(c)

# a now equals ['it', 'was', 'annoying']

How to delete SQLite database from Android programmatically

Once you have your Context and know the name of the database, use:

context.deleteDatabase(DATABASE_NAME);

When this line gets run, the database should be deleted.

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

You get that error because you haven't saved your file, save it for example "holamundo.py" then run it Ctrl + B

AutoComplete TextBox Control

There are two ways to accomplish this textbox effect:

enter image description here

Either using the graphic user interface (GUI); or with code

Using the Graphic User Interface:
Go to: "Properties" Tab; then set the following properties:

enter image description here

However; the best way is to create this by code. See example below.

AutoCompleteStringCollection sourceName = new AutoCompleteStringCollection();

foreach (string name in listNames)
{    
    sourceName.Add(name);
}

txtName.AutoCompleteCustomSource = sourceName;
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Update multiple rows using select statement

None of above answers worked for me in MySQL, the following query worked though:

UPDATE
    Table1 t1
    JOIN
    Table2 t2 ON t1.ID=t2.ID 
SET
    t1.value =t2.value
WHERE
    ...

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

1· Do I need these DLL's?

It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.

  1. Where can I get them?

most dlls can be found at https://www.dll-files.com

I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll

For me leshims.dll can be placed at C:\Windows\System32\. Context: windows 7 64bit.

How to convert a string with comma-delimited items to a list in Python?

The following Python code will turn your string into a list of strings:

import ast
teststr = "['aaa','bbb','ccc']"
testarray = ast.literal_eval(teststr)

Sum all the elements java arraylist

Java 8+ version for Integer, Long, Double and Float

    List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
    List<Long> longs = Arrays.asList(1L, 2L, 3L, 4L, 5L);
    List<Double> doubles = Arrays.asList(1.2d, 2.3d, 3.0d, 4.0d, 5.0d);
    List<Float> floats = Arrays.asList(1.3f, 2.2f, 3.0f, 4.0f, 5.0f);

    long intSum = ints.stream()
            .mapToLong(Integer::longValue)
            .sum();

    long longSum = longs.stream()
            .mapToLong(Long::longValue)
            .sum();

    double doublesSum = doubles.stream()
            .mapToDouble(Double::doubleValue)
            .sum();

    double floatsSum = floats.stream()
            .mapToDouble(Float::doubleValue)
            .sum();

    System.out.println(String.format(
            "Integers: %s, Longs: %s, Doubles: %s, Floats: %s",
            intSum, longSum, doublesSum, floatsSum));

15, 15, 15.5, 15.5

How should I pass an int into stringWithFormat?

Do this:

label.text = [NSString stringWithFormat:@"%d", count];

How to roundup a number to the closest ten?

Use ROUND but with num_digits = -1

=ROUND(A1,-1)

Also applies to ROUNDUP and ROUNDDOWN

From Excel help:

  • If num_digits is greater than 0 (zero), then number is rounded to the specified number of decimal places.
  • If num_digits is 0, then number is rounded to the nearest integer.
  • If num_digits is less than 0, then number is rounded to the left of the decimal point.

EDIT: To get the numbers to always round up use =ROUNDUP(A1,-1)

How can you create pop up messages in a batch script?

I put together a script based on the good answers here & in other posts

You can set title timeout & even sleep to schedule it for latter & \n for new line

also you get back the key press into a variable (%pop.key%).

Here is my code

replace special characters in a string python

One way is to use re.sub, that's my preferred way.

import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string

Output:

hey there

Another way is to use re.escape:

import string
import re

my_str = "hey th~!ere"

chars = re.escape(string.punctuation)
print re.sub(r'['+chars+']', '',my_str)

Output:

hey there

Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars

Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Arrays.asList()

this method returns its own implementation of List.It takes an array as an argument and builds methods and attributes on top of it, since it is not copying any data from an array but using the original array this causes alteration in original array when you modify list returned by the Arrays.asList() method.

on the other hand.
ArrayList(Arrays.asList()); is a constructor of ArrayList class which takes a list as argument and returns an ArrayList that is independent of list ie. Arrays.asList() in this case passed as an argument. that is why you see these results;

Git - Won't add files?

I was having this issue on Visual Studio, what worked for me was: 1- Right click on the added file that is not being recognized by git. 2- Select "Add excluded file to Source Control"

Get the current user, within an ApiController action, without passing the userID as a parameter

None of the suggestions above worked for me. The following did!

HttpContext.Current.Request.LogonUserIdentity.Name

I guess there's a wide variety of scenarios and this one worked for me. My scenario involved an AngularJS frontend and a Web API 2 backend application, both running under IIS. I had to set both applications to run exclusively under Windows Authentication.

No need to pass any user information. The browser and IIS exchange the logged on user credentials and the Web API has access to the user credentials on demand (from IIS I presume).

Remove redundant paths from $PATH variable

In bash you simply can ${var/find/replace}

PATH=${PATH/%:\/home\/wrong\/dir\//}

Or in this case (as the replace bit is empty) just:

PATH=${PATH%:\/home\/wrong\/dir\/}

I came here first but went else ware as I thought there would be a parameter expansion to do this. Easier than sed!.

How to replace placeholder character or word in variable with value from another variable in Bash?

ImportError: cannot import name main when running pip --version command in windows7 32 bit

A simple solution that works with Ubuntu, but may fix the problem on windows too:

Just call

pip install --upgrade pip

Rename Pandas DataFrame Index

For newer pandas versions

df.index = df.index.rename('new name')

or

df.index.rename('new name', inplace=True)

The latter is required if a data frame should retain all its properties.

Get spinner selected items text?

It also can be achieved in a little safer way using String.valueOf() like so

Spinner sp = (Spinner) findViewById(R.id.sp_id);
String selectedText = String.valueOf(sp.getSelectedItem());

without crashing the app when all hell breaks loose. The reason behind its safeness is having the capability of dealing with null objects as the argument. The documentation says

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

So, some insurance there in case of having an empty Spinner for example, which the currently selected item has to be converted to String.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Within the Visual Studio:

1) Remove your aspx.designer.cs file

2) Right click on your aspx file and select "Convert to Web Application" This should add the aspx.designer.cs back and up to date.

If you get an error saying:

"Generation of designer file failed: The method or operation is not implemented."

Try close Visual Studio and then reopen your project and do step number two again

How to generate aspx.designer.cs in visual studio?

Take screenshots in the iOS simulator

Press ?S or go to File > Save screenshot from your simulator menu and you will get the screenshot saved on your desktop.

ggplot combining two plots from different data.frames

As Baptiste said, you need to specify the data argument at the geom level. Either

#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) + 
    geom_point() +
    geom_step(data = df2)
)

or

#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) + 
      geom_point(data = df1) +
      geom_step(data = df2)
)

Specify a Root Path of your HTML directory for script links?

I recommend using the HTML <base> element:

<head>
    <base href="http://www.example.com/default/">
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
</head>

In this example, the stylesheet is located in http://www.example.com/default/style.css, the script in http://www.example.com/default/script.js. The advantage of <base> over / is that it is more flexible. Your whole website can be located in a subdirectory of a domain, and you can easily alter the default directory of your website.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

This Works For me !!!

Call a Function without Parameter

$("#CourseSelect").change(function(e1) {
   loadTeachers();
});

Call a Function with Parameter

$("#CourseSelect").change(function(e1) {
    loadTeachers($(e1.target).val());
});

How to center a "position: absolute" element

An absolute object inside a relative object is relative to its parent, the problem here is that you need a static width for the container #slideshowWrapper , and the rest of the solution is like the other users says

body {
    text-align: center;
}

#slideshowWrapper {
    margin-top: 50px;
    text-align:center;
    width: 500px;
}

ul#slideshow {
    list-style: none;
    position: relative;
    margin: auto;
}

ul#slideshow li {
    position: relative;
    left: 50%;
}

ul#slideshow li img {
    border: 1px solid #ccc;
    padding: 4px;
    height: 450px;
}

http://jsfiddle.net/ejRTU/10/

javascript check for not null

It's because val is not null, but contains 'null' as a string.

Try to check with 'null'

if ('null' != val)

For an explanation of when and why this works, see the details below.

Passing Multiple route params in Angular2

      new AsyncRoute({path: '/demo/:demoKey1/:demoKey2', loader: () => {
      return System.import('app/modules/demo/demo').then(m =>m.demoComponent);
       }, name: 'demoPage'}),
       export class demoComponent {
       onClick(){
            this._router.navigate( ['/demoPage', {demoKey1: "123", demoKey2: "234"}]);
          }
        }

How to get system time in Java without creating a new Date

Use System.currentTimeMillis() or System.nanoTime().

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

Try below:

SELECT CONVERT(VARCHAR(20), GETDATE(), 101)

What does yield mean in PHP?

This function is using yield:

function a($items) {
    foreach ($items as $item) {
        yield $item + 1;
    }
}

It is almost the same as this one without:

function b($items) {
    $result = [];
    foreach ($items as $item) {
        $result[] = $item + 1;
    }
    return $result;
}

The only one difference is that a() returns a generator and b() just a simple array. You can iterate on both.

Also, the first one does not allocate a full array and is therefore less memory-demanding.

Is there any way to delete local commits in Mercurial?

In addition to Samaursa's excelent answer, you can use the evolve extension's prune as a safe and recoverable version of strip that will allow you to go back in case you do anything wrong.

I have these alias on my .hgrc:

 # Prunes all draft changesets on the current repository
 reset-tree = prune -r "outgoing() and not obsolete()"
 # *STRIPS* all draft changesets on current repository. This deletes history.
 force-reset-tree = strip 'roots(outgoing())'

Note that prune also has --keep, just like strip, to keep the working directory intact allowing you to recommit the files.

How to get current route

This applies if you are using it with an authguard

this.router.events.subscribe(event => {
        if(event instanceof NavigationStart){
            console.log('this is what your looking for ', event.url);  
         }
       } 
   );

Is it possible to simulate key press events programmatically?

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

The model should do:

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

Then for each character:

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

Then, optionally for most:

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

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

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

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

Below code may help you to achieve session attribution inside java script:

var name = '<%= session.getAttribute("username") %>';

Thread Safe C# Singleton Pattern

In almost every case (that is: all cases except the very first ones), instance won't be null. Acquiring a lock is more costly than a simple check, so checking once the value of instance before locking is a nice and free optimization.

This pattern is called double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking

android set button background programmatically

For not changing the size of button on setting the background color:

button.getBackground().setColorFilter(button.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

this didn't change the size of the button and works with the old android versions too.

Why should I use var instead of a type?

It's really just a coding style. The compiler generates the exact same for both variants.

See also here for the performance question:

C++ printing spaces or tabs given a user input integer

Simply add spaces for { 2 3 4 5 6 } like these:

cout<<"{";

for(){
    cout<<" "<<n;    //n is the element to print !
}

cout<<" }";

Tests not running in Test Explorer

Check in your project file for references to NUnit of different versions:

In my case, I had installed version 3.11.0 of both NUnit and NUnit3TestAdapter, but there were old references to version 2.6.4, in the project file, that weren't removed with the new installation.

  • Solution (Recomended to fix references issues, see docs):

    Reinstall NUnit and NUnit3TestAdapter, this fixed the references in my project.
PM> Update-Package NUnit -reinstall
...
PM> Update-Package NUnit3TestAdapter -reinstall
  • Solution 2 (In case of reinstalling didn't fix the references):

    Uninstall and install NUnit and NUnit3TestAdapter.
PM> Uninstall-Package NUnit
...
PM> Uninstall-Package NUnit3TestAdapter
...
PM> Install-Package NUnit
...
PM> Install-Package NUnit3TestAdapter

Rename multiple files by replacing a particular pattern in the filenames using a shell script

for file in *.jpg ; do mv $file ${file//IMG/myVacation} ; done

Again assuming that all your image files have the string "IMG" and you want to replace "IMG" with "myVacation".

With bash you can directly convert the string with parameter expansion.

Example: if the file is IMG_327.jpg, the mv command will be executed as if you do mv IMG_327.jpg myVacation_327.jpg. And this will be done for each file found in the directory matching *.jpg.

IMG_001.jpg -> myVacation_001.jpg
IMG_002.jpg -> myVacation_002.jpg
IMG_1023.jpg -> myVacation_1023.jpg
etcetera...

Scanner method to get a char

Console cons = System.console();

The above code line creates cons as a null reference. The code and output are given below:

Console cons = System.console();
if (cons != null) {
    System.out.println("Enter single character: ");
    char c = (char) cons.reader().read();
    System.out.println(c);
}else{
    System.out.println(cons);
}

Output :

null

The code was tested on macbook pro with java version "1.6.0_37"

range() for floats

A solution without numpy etc dependencies was provided by kichik but due to the floating point arithmetics, it often behaves unexpectedly. As noted by me and blubberdiblub, additional elements easily sneak into the result. For example naive_frange(0.0, 1.0, 0.1) would yield 0.999... as its last value and thus yield 11 values in total.

A robust version is provided here:

def frange(x, y, jump=1.0):
    '''Range for floats.'''
    i = 0.0
    x = float(x)  # Prevent yielding integers.
    x0 = x
    epsilon = jump / 2.0
    yield x  # yield always first value
    while x + epsilon < y:
        i += 1.0
        x = x0 + i * jump
        yield x

Because the multiplication, the rounding errors do not accumulate. The use of epsilon takes care of possible rounding error of the multiplication, even though issues of course might rise in the very small and very large ends. Now, as expected:

> a = list(frange(0.0, 1.0, 0.1))
> a[-1]
0.9
> len(a)
10

And with somewhat larger numbers:

> b = list(frange(0.0, 1000000.0, 0.1))
> b[-1]
999999.9
> len(b)
10000000

The code is also available as a GitHub Gist.

How to write a multidimensional array to a text file?

You can simply traverse the array in three nested loops and write their values to your file. For reading, you simply use the same exact loop construction. You will get the values in exactly the right order to fill your arrays correctly again.

Get column from a two dimensional array

You can use the following array methods to obtain a column from a 2D array:

Array.prototype.map()

const array_column = (array, column) => array.map(e => e[column]);

Array.prototype.reduce()

const array_column = (array, column) => array.reduce((a, c) => {
  a.push(c[column]);
  return a;
}, []);

Array.prototype.forEach()

const array_column = (array, column) => {
  const result = [];

  array.forEach(e => {
    result.push(e[column]);
  });

  return result;
};

If your 2D array is a square (the same number of columns for each row), you can use the following method:

Array.prototype.flat() / .filter()

const array_column = (array, column) => array.flat().filter((e, i) => i % array.length === column);

How can I delete all Git branches which have been merged?

There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.

If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)

$ git rev-list master | grep $(git rev-parse myTopicBranch)

You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

As written in How to pop fragment off backstack and by LarsH here, we can pop several fragments from top down to specifical tag (together with the tagged fragment) using this method:

fragmentManager?.popBackStack ("frag", FragmentManager.POP_BACK_STACK_INCLUSIVE);

Substitute "frag" with your fragment's tag. Remember that first we should add the fragment to backstack with:

fragmentTransaction.addToBackStack("frag")

If we add fragments with addToBackStack(null), we won't pop fragments that way.

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

JPA & Criteria API - Select only specific columns

First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):

List<T> results = session.createCriteria(entityClazz)
    .setProjection( Projections.projectionList()
        .add( Property.forName("ID") )
        .add( Property.forName("VERSION") )
    )
    .setResultTransformer(Transformers.aliasToBean(entityClazz); 
    .list();

This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.

Insert string in beginning of another string

It is better if you find quotation marks by using the indexof() method and then add a string behind that index.

string s="hai";
int s=s.indexof(""");

How do I use an image as a submit button?

Use CSS :

input[type=submit] {

background:url("BUTTON1.jpg");

}

For HTML :

<input type="submit" value="Login" style="background:url("BUTTON1.jpg");">

Returning JSON response from Servlet to Javascript/JSP page

I used JSONObject as shown below in Servlet.

    JSONObject jsonReturn = new JSONObject();

    NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);

    map = new HashMap<String, String>();
    map.put("Status", "Success");
    map.put("FailureReason", "None");
    map.put("DataElements", "2");

    jsonReturn = new JSONObject();
    jsonReturn.accumulate("Header", map);

    List<String> list = new ArrayList<String>();
    list.add(NhAdminTree);
    list.add(userName);

    jsonReturn.accumulate("Elements", list);

The Servlet returns this JSON object as shown below:

    response.setContentType("application/json");
    response.getWriter().write(jsonReturn.toString());

This Servlet is called from Browser using AngularJs as below

$scope.GetNeighborhoodTreeUsingPost = function(){
    alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );

    $http({

        method: 'POST',
        url : 'http://localhost:8080/EPortal/xlEPortalService',
        headers: {
           'Content-Type': 'application/json'
         },
        data : {
            'action': 64,
            'userName' : $scope.userName
        }
    }).success(function(data, status, headers, config){
        alert("DATA.header.status : " + data.Header.Status);
        alert("DATA.header.FailureReason : " + data.Header.FailureReason);
        alert("DATA.header.DataElements : " + data.Header.DataElements);
        alert("DATA.elements : " + data.Elements);

    }).error(function(data, status, headers, config) {
        alert(data + " : " + status + " : " + headers + " : " + config);
    });

};

This code worked and it is showing correct data in alert dialog box:

Data.header.status : Success

Data.header.FailureReason : None

Data.header.DetailElements : 2

Data.Elements : Coma seperated string values i.e. NhAdminTree, userName

C#: Waiting for all threads to complete

Since the question got bumped I will go ahead and post my solution.

using (var finished = new CountdownEvent(1)) 
{ 
  for (DataObject data in dataList) 
  {   
    finished.AddCount();
    var localData = (DataObject)data.Clone(); 
    var thread = new Thread( 
        delegate() 
        {
          try
          {
            DoThreadStuff(localData); 
            threadFinish.Set();
          }
          finally
          {
            finished.Signal();
          }
        } 
    ); 
    thread.Start(); 
  }  
  finished.Signal(); 
  finished.Wait(YOUR_TIMEOUT); 
} 

Getting Chrome to accept self-signed localhost certificate

UPDATE 11/2017: This answer probably won't work for most newer versions of Chrome.

UPDATE 02/2016: Better Instructions for Mac Users Can be Found Here.

  1. On the site you want to add, right-click the red lock icon in the address bar:enter image description here

    1. Click the tab labeled Connection, then click Certificate Information

    2. Click the Details tab, the click the button Copy to File.... This will open the Certificate Export Wizard, click Next to get to the Export File Format screen.

    3. Choose DER encoded binary X.509 (.CER), click Next

    4. Click Browse... and save the file to your computer. Name it something descriptive. Click Next, then click Finish.

    5. Open Chrome settings, scroll to the bottom, and click Show advanced settings...

    6. Under HTTPS/SSL, click Manage certificates...

    7. Click the Trusted Root Certification Authorities tab, then click the Import... button. This opens the Certificate Import Wizard. Click Next to get to the File to Import screen.

    8. Click Browse... and select the certificate file you saved earlier, then click Next.

    9. Select Place all certificates in the following store. The selected store should be Trusted Root Certification Authorities. If it isn't, click Browse... and select it. Click Next and Finish

    10. Click Yes on the security warning.

    11. Restart Chrome.

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
    // changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

How to insert new cell into UITableView in Swift

Here is your code for add data into both tableView:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var table1Text: UITextField!
    @IBOutlet weak var table2Text: UITextField!
    @IBOutlet weak var table1: UITableView!
    @IBOutlet weak var table2: UITableView!

    var table1Data = ["a"]
    var table2Data = ["1"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func addData(sender: AnyObject) {

        //add your data into tables array from textField
        table1Data.append(table1Text.text)
        table2Data.append(table2Text.text)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //reload your tableView
            self.table1.reloadData()
            self.table2.reloadData()
        })


        table1Text.resignFirstResponder()
        table2Text.resignFirstResponder()
    }

    //delegate methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == table1 {
            return table1Data.count
        }else if tableView == table2 {
            return table2Data.count
        }
        return Int()
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if tableView == table1 {
            let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table1Data[row]

            return cell
        }else if tableView == table2 {

            let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table2Data[row]

            return cell
        }

        return UITableViewCell()
    }
}

And your result will be:

enter image description here

How to serialize an object to XML without getting xmlns="..."?

If you are unable to get rid of extra xmlns attributes for each element, when serializing to xml from generated classes (e.g.: when xsd.exe was used), so you have something like:

<manyElementWith xmlns="urn:names:specification:schema:xsd:one" />

then i would share with you what worked for me (a mix of previous answers and what i found here)

explicitly set all your different xmlns as follows:

Dim xmlns = New XmlSerializerNamespaces()
xmlns.Add("one", "urn:names:specification:schema:xsd:one")
xmlns.Add("two",  "urn:names:specification:schema:xsd:two")
xmlns.Add("three",  "urn:names:specification:schema:xsd:three")

then pass it to the serialize

serializer.Serialize(writer, object, xmlns);

you will have the three namespaces declared in the root element and no more needed to be generated in the other elements which will be prefixed accordingly

<root xmlns:one="urn:names:specification:schema:xsd:one" ... />
   <one:Element />
   <two:ElementFromAnotherNameSpace /> ...

How can I align the columns of tables in Bash?

To have the exact same output as you need, you need to format the file like that :

a very long string..........\t     112232432\t     anotherfield\n
a smaller string\t      123124343\t     anotherfield\n

And then using :

$ column -t -s $'\t' FILE
a very long string..........  112232432  anotherfield
a smaller string              123124343  anotherfield

How do I set the driver's python version in spark?

I came across the same error message and I have tried three ways mentioned above. I listed the results as a complementary reference to others.

  1. Change the PYTHON_SPARK and PYTHON_DRIVER_SPARK value in spark-env.sh does not work for me.
  2. Change the value inside python script using os.environ["PYSPARK_PYTHON"]="/usr/bin/python3.5" os.environ["PYSPARK_DRIVER_PYTHON"]="/usr/bin/python3.5" does not work for me.
  3. Change the value in ~/.bashrc works like a charm~

Button text toggle in jquery

$(".pushme").click(function () {
  var button = $(this);
  button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")           
});

This ternary operator has an implicit return. If the expression before ? is true it returns "DON'T PUSH ME", else returns "PUSH ME"

This if-else statement:

if (condition) { return A }
else { return B }

has the equivalent ternary expression:

condition ? A : B

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

When connecting to SQL Server with Windows Authentication (as opposed to a local SQL Server account), attempting to use a linked server may result in the error message:

Cannot create an instance of OLE DB provider "(OLEDB provider name)"...

The most direct answer to this problem is provided by Microsoft KB 2647989, because "Security settings for the MSDAINITIALIZE DCOM class are incorrect."

The solution is to fix the security settings for MSDAINITIALIZE. In Windows Vista and later, the class is owned by TrustedInstaller, so the ownership of MSDAINITIALIZE must be changed before the security can be adjusted. The KB above has detailed instructions for doing so.

This MSDN blog post describes the reason:

MSDAINITIALIZE is a COM class that is provided by OLE DB. This class can parse OLE DB connection strings and load/initialize the provider based on property values in the connection string. MSDAINITILIAZE is initiated by users connected to SQL Server. If Windows Authentication is used to connect to SQL Server, then the provider is initialized under the logged in user account. If the logged in user is a SQL login, then provider is initialized under SQL Server service account. Based on the type of login used, permissions on MSDAINITIALIZE have to be provided accordingly.

The issue dates back at least to SQL Server 2000; KB 280106 from Microsoft describes the error (see "Message 3") and has the suggested fix of setting the In Process flag for the OLEDB provider.

While setting In Process can solve the immediate problem, it may not be what you want. According to Microsoft,

Instantiating the provider outside the SQL Server process protects the SQL Server process from errors in the provider. When the provider is instantiated outside the SQL Server process, updates or inserts referencing long columns (text, ntext, or image) are not allowed. -- Linked Server Properties doc for SQL Server 2008 R2.

The better answer is to go with the Microsoft guidance and adjust the MSDAINITIALIZE security.

How to use Comparator in Java to sort

Here's an example of a Comparator that will work for any zero arg method that returns a Comparable. Does something like this exist in a jdk or library?

import java.lang.reflect.Method;
import java.util.Comparator;

public class NamedMethodComparator implements Comparator<Object> {

    //
    // instance variables
    //

    private String methodName;

    private boolean isAsc;

    //
    // constructor
    //

    public NamedMethodComparator(String methodName, boolean isAsc) {
        this.methodName = methodName;
        this.isAsc = isAsc;
    }

    /**
     * Method to compare two objects using the method named in the constructor.
     */
    @Override
    public int compare(Object obj1, Object obj2) {
        Comparable comp1 = getValue(obj1, methodName);
        Comparable comp2 = getValue(obj2, methodName);
        if (isAsc) {
            return comp1.compareTo(comp2);
        } else {
            return comp2.compareTo(comp1);
        }
    }

    //
    // implementation
    //

    private Comparable getValue(Object obj, String methodName) {
        Method method = getMethod(obj, methodName);
        Comparable comp = getValue(obj, method);
        return comp;
    }

    private Method getMethod(Object obj, String methodName) {
        try {
            Class[] signature = {};
            Method method = obj.getClass().getMethod(methodName, signature);
            return method;
        } catch (Exception exp) {
            throw new RuntimeException(exp);
        }
    }

    private Comparable getValue(Object obj, Method method) {
        Object[] args = {};
        try {
            Object rtn = method.invoke(obj, args);
            Comparable comp = (Comparable) rtn;
            return comp;
        } catch (Exception exp) {
            throw new RuntimeException(exp);
        }
    }

}

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Hi same problem i have solved you can try this

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.NETWORK

 // SET SSL
public static OkClient setSSLFactoryForClient(OkHttpClient client) {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


        client.setSslSocketFactory(sslSocketFactory);
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new OkClient(client);
}

How to draw a custom UIView that is just a circle - iPhone app

Another way of approaching circle (and other shapes) drawing is by using masks. You draw circles or other shapes by, first, making masks of the shapes you need, second, provide squares of your color and, third, apply masks to those squares of color. You can change either mask or color to get a new custom circle or other shape.

#import <QuartzCore/QuartzCore.h>

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *area1;
@property (weak, nonatomic) IBOutlet UIView *area2;
@property (weak, nonatomic) IBOutlet UIView *area3;
@property (weak, nonatomic) IBOutlet UIView *area4;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.area1.backgroundColor = [UIColor blueColor];
    [self useMaskFor: self.area1];

    self.area2.backgroundColor = [UIColor orangeColor];
    [self useMaskFor: self.area2];

    self.area3.backgroundColor = [UIColor colorWithRed: 1.0 green: 0.0 blue: 0.5 alpha:1.0];
    [self useMaskFor: self.area3];

    self.area4.backgroundColor = [UIColor colorWithRed: 1.0 green: 0.0 blue: 0.5 alpha:0.5];
    [self useMaskFor: self.area4];        
}

- (void)useMaskFor: (UIView *)colorArea {        
    CALayer *maskLayer = [CALayer layer];
    maskLayer.frame = colorArea.bounds;
    UIImage *maskImage = [UIImage imageNamed:@"cirMask.png"];
    maskLayer.contents = (__bridge id)maskImage.CGImage;
    colorArea.layer.mask = maskLayer;
}

@end

Here is the output of the code above:

four circles

Is putting a div inside an anchor ever correct?

No it won't validate, but yes it generally will work in modern browsers. That being said, use a span inside your anchor, and set display: block on it as well, that will definitely work everywhere, and it will validate!

how to insert value into DataGridView Cell?

This is perfect code but it cannot add a new row:

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But this code can insert a new row:

var index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[1].Value = "1";
this.dataGridView1.Rows[index].Cells[2].Value = "Baqar";

VB.NET - Remove a characters from a String

The string class's Replace method can also be used to remove multiple characters from a string:

Dim newstring As String
newstring = oldstring.Replace(",", "").Replace(";", "")

Sql Query to list all views in an SQL Server 2005 database

SELECT  *
FROM    sys.objects
WHERE   type = 'V'

Pandas: drop a level from a multi-level column index?

Another way to do this is to reassign df based on a cross section of df, using the .xs method.

>>> df

    a
    b   c
0   1   2
1   3   4

>>> df = df.xs('a', axis=1, drop_level=True)

    # 'a' : key on which to get cross section
    # axis=1 : get cross section of column
    # drop_level=True : returns cross section without the multilevel index

>>> df

    b   c
0   1   2
1   3   4

Getting the screen resolution using PHP

I found using CSS inside my html inside my php did the trick for me.

<?php             
    echo '<h2 media="screen and (max-width: 480px)">'; 
    echo 'My headline';
    echo '</h2>'; 

    echo '<h1 media="screen and (min-width: 481px)">'; 
    echo 'My headline';
    echo '</h1>'; 

    ?>

This will output a smaller sized headline if the screen is 480px or less. So no need to pass any vars using JS or similar.

Prevent content from expanding grid items

The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Git merge errors

as suggested in git status,

Unmerged paths:                                                                                                                                
(use "git add <file>..." to mark resolution)                                                                                                 

    both modified:   a.jl                                  
    both modified:   b.jl

I used git add to finish the merging, then git checkout works fine.

Can I install Python 3.x and 2.x on the same Windows computer?

The official solution for coexistence seems to be the Python Launcher for Windows, PEP 397 which was included in Python 3.3.0. Installing the release dumps py.exe and pyw.exe launchers into %SYSTEMROOT% (C:\Windows) which is then associated with py and pyw scripts, respectively.

In order to use the new launcher (without manually setting up your own associations to it), leave the "Register Extensions" option enabled. I'm not quite sure why, but on my machine it left Py 2.7 as the "default" (of the launcher).

Running scripts by calling them directly from the command line will route them through the launcher and parse the shebang (if it exists). You can also explicitly call the launcher and use switches: py -3 mypy2script.py.

All manner of shebangs seem to work

  • #!C:\Python33\python.exe
  • #!python3
  • #!/usr/bin/env python3

as well as wanton abuses

  • #! notepad.exe

Date Comparison using Java

It is easier to compare dates using the java.util.Calendar. Here is what you might do:

Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);  
if(!toDate.before(nowDate)) {
    //display your report
} else {
    // don't display the report
}

How do I make a simple makefile for gcc on Linux?

Interesting, I didn't know make would default to using the C compiler given rules regarding source files.

Anyway, a simple solution that demonstrates simple Makefile concepts would be:

HEADERS = program.h headers.h

default: program

program.o: program.c $(HEADERS)
    gcc -c program.c -o program.o

program: program.o
    gcc program.o -o program

clean:
    -rm -f program.o
    -rm -f program

(bear in mind that make requires tab instead of space indentation, so be sure to fix that when copying)

However, to support more C files, you'd have to make new rules for each of them. Thus, to improve:

HEADERS = program.h headers.h
OBJECTS = program.o

default: program

%.o: %.c $(HEADERS)
    gcc -c $< -o $@

program: $(OBJECTS)
    gcc $(OBJECTS) -o $@

clean:
    -rm -f $(OBJECTS)
    -rm -f program

I tried to make this as simple as possible by omitting variables like $(CC) and $(CFLAGS) that are usually seen in makefiles. If you're interested in figuring that out, I hope I've given you a good start on that.

Here's the Makefile I like to use for C source. Feel free to use it:

TARGET = prog
LIBS = -lm
CC = gcc
CFLAGS = -g -Wall

.PHONY: default all clean

default: $(TARGET)
all: default

OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)

%.o: %.c $(HEADERS)
    $(CC) $(CFLAGS) -c $< -o $@

.PRECIOUS: $(TARGET) $(OBJECTS)

$(TARGET): $(OBJECTS)
    $(CC) $(OBJECTS) -Wall $(LIBS) -o $@

clean:
    -rm -f *.o
    -rm -f $(TARGET)

It uses the wildcard and patsubst features of the make utility to automatically include .c and .h files in the current directory, meaning when you add new code files to your directory, you won't have to update the Makefile. However, if you want to change the name of the generated executable, libraries, or compiler flags, you can just modify the variables.

In either case, don't use autoconf, please. I'm begging you! :)

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

CSP helps you whitelisting sources that you trust. All other sources are not allowed access to. Read this Q&A carefully, and then make sure that you whitelist the fonts, socket connections and other sources if you trust them.

If you know what you are doing, you can comment out the meta tag to test, probably everything works. But realise that you / your user is being protected here, so keeping the meta tag is probably a good thing.

How to get all of the immediate subdirectories in Python

One liner using pathlib:

list_subfolders_with_paths = [p for p in pathlib.Path(path).iterdir() if p.is_dir()]

How to read single Excel cell value

The issue with reading single Excel Cell in .Net comes from the fact, that the empty cell is evaluated to a Null. Thus, one cannot use its .Value or .Value2 properties, because an error shows up.

To return an empty string, when the cell is Null the Convert.ToString(Cell) can be used in the following way:

Excel.Workbook wkb = Open(excel, filePath);
Excel.Worksheet wk = (Excel.Worksheet)excel.Worksheets.get_Item(1);

for (int i = 1; i < 5; i++)
{
    string a = Convert.ToString(wk.Cells[i, 1].Value2);
    Console.WriteLine(a);
}

Copy array by value

Use this:

_x000D_
_x000D_
let oldArray = [1, 2, 3, 4, 5];

let newArray = oldArray.slice();

console.log({newArray});
_x000D_
_x000D_
_x000D_

Basically, the slice() operation clones the array and returns a reference to a new array.

Also note that:

For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

The answer are accepted but one thing you could also do is to define the libraries from your project structure. What you can do is :

  1. Comment all the libraries in which problem is coming
  2. Goto your project structure
  3. Add libraries from there and it'll sync automatically and the problem goes off.
  4. If problem persists try looking from the error log that what library is it demanding after following all the above 3 steps.

What happens is the predefined libraries as off now now I'm taking the appcompat:26.0.0-alpha1 it uses the older version of the things when you add something new and tries to resolve it with the old stuffs. When you add it from your project structure, it'll add the same thing but with the new stuffs to resolve it. Your problem would be resolved.

Coarse-grained vs fine-grained

In term of dataset like a text file ,Coarse-grained meaning we can transform the whole dataset but not an individual element on the dataset While fine-grained means we can transform individual element on the dataset.

How do I convert a list into a string with spaces in Python?

I'll throw this in as an alternative just for the heck of it, even though it's pretty much useless when compared to " ".join(my_list) for strings. For non-strings (such as an array of ints) this may be better:

" ".join(str(item) for item in my_list)

When to use @QueryParam vs @PathParam

As theon noted, REST is not a standard. However, if you are looking to implement a standards based URI convention, you might consider the oData URI convention. Ver 4 has been approved as an OASIS standard and libraries exists for oData for various languages including Java via Apache Olingo. Don't let the fact that it's a spawn from Microsoft put you off since it's gained support from other industry player's as well, which include Red Hat, Citrix, IBM, Blackberry, Drupal, Netflix Facebook and SAP

More adopters are listed here

DBMS_OUTPUT.PUT_LINE not printing

For SQL Developer

You have to execute it manually

SET SERVEROUTPUT ON 

After that if you execute any procedure with DBMS_OUTPUT.PUT_LINE('info'); or directly .

This will print the line

And please don't try to add this

 SET SERVEROUTPUT ON

inside the definition of function and procedure, it will not compile and will not work.

"No backupset selected to be restored" SQL Server 2012

Another potential reason for this glitch appears to be Google Drive. Google Drive is compressing bak files or something, so if you want to transfer a database backup via Google Drive, it appears you must zip it first.

How to select first child with jQuery?

As @Roko mentioned you can do this in multiple ways.

1.Using the jQuery first-child selector - SnoopCode

   $(document).ready(function(){
    $(".alldivs onediv:first-child").css("background-color","yellow");
        }
  1. Using jQuery eq Selector - SnoopCode

     $( "body" ).find( "onediv" ).eq(1).addClass( "red" );
    
  2. Using jQuery Id Selector - SnoopCode

       $(document).ready(function(){
         $("#div1").css("background-color: red;");
       });
    

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The error you're seeing means the data you receive from the remote end isn't valid JSON. JSON (according to the specifiation) is normally UTF-8, but can also be UTF-16 or UTF-32 (in either big- or little-endian.) The exact error you're seeing means some part of the data was not valid UTF-8 (and also wasn't UTF-16 or UTF-32, as those would produce different errors.)

Perhaps you should examine the actual response you receive from the remote end, instead of blindly passing the data to json.loads(). Right now, you're reading all the data from the response into a string and assuming it's JSON. Instead, check the content type of the response. Make sure the webpage is actually claiming to give you JSON and not, for example, an error message that isn't JSON.

(Also, after checking the response use json.load() by passing it the file-like object returned by opener.open(), instead of reading all data into a string and passing that to json.loads().)

Get all attributes of an element using jQuery

The attributes property contains them all:

$(this).each(function() {
  $.each(this.attributes, function() {
    // this.attributes is not a plain object, but an array
    // of attribute nodes, which contain both the name and value
    if(this.specified) {
      console.log(this.name, this.value);
    }
  });
});

What you can also do is extending .attr so that you can call it like .attr() to get a plain object of all attributes:

(function(old) {
  $.fn.attr = function() {
    if(arguments.length === 0) {
      if(this.length === 0) {
        return null;
      }

      var obj = {};
      $.each(this[0].attributes, function() {
        if(this.specified) {
          obj[this.name] = this.value;
        }
      });
      return obj;
    }

    return old.apply(this, arguments);
  };
})($.fn.attr);

Usage:

var $div = $("<div data-a='1' id='b'>");
$div.attr();  // { "data-a": "1", "id": "b" }

Can't connect to localhost on SQL Server Express 2012 / 2016

Try changing the User that owns the service to Local System or use your admin account.

Under services, I changed the Service SQL Server (MSSQLSERVER) Log On from NT Service\Sql... To Local System. Right click the service and go to the Log On Tab and select the radio button Local System Account. You could also force another User to run it too if that fits better.

SQL Error: 0, SQLState: 08S01 Communications link failure

The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing. So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.

How to describe "object" arguments in jsdoc?

I see that there is already an answer about the @return tag, but I want to give more details about it.

First of all, the official JSDoc 3 documentation doesn't give us any examples about the @return for a custom object. Please see https://jsdoc.app/tags-returns.html. Now, let's see what we can do until some standard will appear.

  • Function returns object where keys are dynamically generated. Example: {1: 'Pete', 2: 'Mary', 3: 'John'}. Usually, we iterate over this object with the help of for(var key in obj){...}.

    Possible JSDoc according to https://google.github.io/styleguide/javascriptguide.xml#JsTypes

    /**
     * @return {Object.<number, string>}
     */
    function getTmpObject() {
        var result = {}
        for (var i = 10; i >= 0; i--) {
            result[i * 3] = 'someValue' + i;
        }
        return result
    }
    
  • Function returns object where keys are known constants. Example: {id: 1, title: 'Hello world', type: 'LEARN', children: {...}}. We can easily access properties of this object: object.id.

    Possible JSDoc according to https://groups.google.com/forum/#!topic/jsdoc-users/TMvUedK9tC4

    • Fake It.

      /**
       * Generate a point.
       *
       * @returns {Object} point - The point generated by the factory.
       * @returns {number} point.x - The x coordinate.
       * @returns {number} point.y - The y coordinate.
       */
      var pointFactory = function (x, y) {
          return {
              x:x,
              y:y
          }
      }
      
    • The Full Monty.

      /**
       @class generatedPoint
       @private
       @type {Object}
       @property {number} x The x coordinate.
       @property {number} y The y coordinate.
       */
      function generatedPoint(x, y) {
          return {
              x:x,
              y:y
          };
      }
      
      /**
       * Generate a point.
       *
       * @returns {generatedPoint} The point generated by the factory.
       */
      
      var pointFactory = function (x, y) {
          return new generatedPoint(x, y);
      }
      
    • Define a type.

      /**
       @typedef generatedPoint
       @type {Object}
       @property {number} x The x coordinate.
       @property {number} y The y coordinate.
       */
      
      
      /**
       * Generate a point.
       *
       * @returns {generatedPoint} The point generated by the factory.
       */
      
      var pointFactory = function (x, y) {
          return {
              x:x,
              y:y
          }
      }
      

    According to https://google.github.io/styleguide/javascriptguide.xml#JsTypes

    • The record type.

      /**
       * @return {{myNum: number, myObject}}
       * An anonymous type with the given type members.
       */
      function getTmpObject() {
          return {
              myNum: 2,
              myObject: 0 || undefined || {}
          }
      }
      

String.Format not work in TypeScript

You can declare it yourself quite easily:

interface StringConstructor {
    format: (formatString: string, ...replacement: any[]) => string;
}

String.format('','');

This is assuming that String.format is defined elsewhere. e.g. in Microsoft Ajax Toolkit : http://www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

Groovy - How to compare the string?

This line:

if(str2==${str}){

Should be:

if( str2 == str ) {

The ${ and } will give you a parse error, as they should only be used inside Groovy Strings for templating

Maven: Command to update repository after adding dependency to POM

Pay attention to your dependency scope I was having the issue where when I invoke clean compile via Intellij, the pom would get downloaded, but the jar would not. There was a xxx.jar.lastUpdated file created. Then realized that the dependency scope was test, but I was triggering the compile. I deleted the repos, and triggered the mvn test, and issue was resolved.

How to reset par(mfrow) in R

You can reset the mfrow parameter

par(mfrow=c(1,1))

Return single column from a multi-dimensional array

join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))

"Are you missing an assembly reference?" compile error - Visual Studio

I encountered this error with an Azure DevOps Services (MS-hosted) build pipeline on a TFVC repo.

In my case, I was working within a branch and had accidentally added the reference from the package folder in trunk instead of from the branch. Once I added the reference from within the branch, it started compiling successfully.

I.e., while working on \branch-beta\sierra.csproj, I accidentally referenced \trunk\packages\delta.dll. Obviously, I needed to reference \branch-beta\packages\delta.dll instead. The mixup occurred because the path is not prominently displayed in the Add Reference window and I didn’t check carefully enough.

iPhone and WireShark

I have successfully captured HTTP traffic using Fiddler2 as a proxy, which can be installed on any Windows PC on your network.

  1. In Fiddler, Tools -> Fiddler Options -> Connections -> [x] Allow remote computers to connect.
  2. Make sure your windows firewall is disabled.
  3. On the iphone/ipod, go to your wireless settings, use a manual proxy server, enter the fiddler machine's ip address and the same port (defaults to 8888).

Not able to pip install pickle in python 3.6

You can pip install pickle by running command pip install pickle-mixin. Proceed to import it using import pickle. This can be then used normally.

What does void do in java?

You mean the tellItLikeItIs method? Yes, you have to specify void to specify that the method doesn't return anything. All methods have to have a return type specified, even if it's void.

It certainly doesn't return a string - look, there are no return statements anywhere. It's not really clear why you think it is returning a string. It's printing strings to the console, but that's not the same thing as returning one from the method.

Ant if else condition?

The quirky syntax using conditions on the target (described by Mads) is the only supported way to perform conditional execution in core ANT.

ANT is not a programming language and when things get complicated I choose to embed a script within my build as follows:

<target name="prepare-copy" description="copy file based on condition">
    <groovy>
        if (properties["some.condition"] == "true") {
            ant.copy(file:"${properties["some.dir"]}/true", todir:".")
        }
    </groovy>
</target>

ANT supports several languages (See script task), my preference is Groovy because of it's terse syntax and because it plays so well with the build.

Apologies, David I am not a fan of ant-contrib.

Getting command-line password input in Python

import getpass

pswd = getpass.getpass('Password:')

getpass works on Linux, Windows, and Mac.

What is the command to truncate a SQL Server log file?

In management studio:

  • Don't do this on a live environment, but to ensure you shrink your dev db as much as you can:
    • Right-click the database, choose Properties, then Options.
    • Make sure "Recovery model" is set to "Simple", not "Full"
    • Click OK
  • Right-click the database again, choose Tasks -> Shrink -> Files
  • Change file type to "Log"
  • Click OK.

Alternatively, the SQL to do it:

 ALTER DATABASE mydatabase SET RECOVERY SIMPLE
 DBCC SHRINKFILE (mydatabase_Log, 1)

Ref: http://msdn.microsoft.com/en-us/library/ms189493.aspx

Create new user in MySQL and give it full access to one database

To create a user and grant all privileges on a database.

Log in to MySQL:

mysql -u root

Now create and grant

GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';

Anonymous user (for local testing only)

Alternately, if you just want to grant full unrestricted access to a database (e.g. on your local machine for a test instance, you can grant access to the anonymous user, like so:

GRANT ALL PRIVILEGES ON dbTest.* To ''@'hostname'

Be aware

This is fine for junk data in development. Don't do this with anything you care about.

Intel's HAXM equivalent for AMD on Windows OS

This limitation (of Windows) should be publicly announced! The issue for me is the combination of the following: Windows 10 + AMD CPU (with AMD-V/SMV) +/- Hyper Visor

I have no issues running: Intel (with VT-x) + Linux or AMD (with AMD-V) + Linux

Link to Android studio issue here:

https://developer.android.com/studio/run/emulator.html#accel-vm

Xamarin/Visual Studio seems to have a workaround, but I haven't tested it yet:

If you need to use Hyper-V for other emulators then I'd recommend using the Microsoft Android Emulator instead, which uses Hyper-V and can also be used with Xamarin Studio/Visual Studio. You can download it for free from here.

I will update this after I confirm it works. Wish I would have known this before purchasing a new machine.

UPDATE!! It does not work "Requires Intel ..." error message is shown

Final note:

*Must be revision F3 or grater or must be F2 with BIOS support. Presence or absence of SVM Disable or other virtualization options in the bios does not ensure presence of BIOS support. You should contact the OEM to ensure support of Hyper-V.

*Some AMD BIOS's have options to enable/disable SVM (virtualization assistance)

*Some BIOS's list this as SVM Disable and it's a double negative, i.e. you want to disable SVM disable to enable SVM.

*Some BIOS's list this as Secure Virtualization, thus enabling Secure Virtualization will enable SVM

*Must have No-Execute enabled in the BIOS, sometime this is referred to as NX or Execute Disable

*If you want to find CPU's that are F3 see AMD's guide http://products.amd.com/en-us/DesktopCPUFilter.aspx or http://products.amd.com/en-us/OpteronCPUFilter.aspx?f1=Second-Generation+AMD+Opteron%e2%84%a2

How to redirect 'print' output to a file using python?

This works perfectly:

import sys
sys.stdout=open("test.txt","w")
print ("hello")
sys.stdout.close()

Now the hello will be written to the test.txt file. Make sure to close the stdout with a close, without it the content will not be save in the file

how do I strip white space when grabbing text with jQuery?

Javascript has built in trim:

str.trim()

It doesn't work in IE8. If you have to support older browsers, use Tuxmentat's or Paul's answer.

Curl : connection refused

127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.

Finding non-numeric rows in dataframe in pandas?

Already some great answers to this question, however here is a nice snippet that I use regularly to drop rows if they have non-numeric values on some columns:

# Eliminate invalid data from dataframe (see Example below for more context)

num_df = (df.drop(data_columns, axis=1)
         .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

num_df = num_df[num_df[data_columns].notnull().all(axis=1)]

The way this works is we first drop all the data_columns from the df, and then use a join to put them back in after passing them through pd.to_numeric (with option 'coerce', such that all non-numeric entries are converted to NaN). The result is saved to num_df.

On the second line we use a filter that keeps only rows where all values are not null.

Note that pd.to_numeric is coercing to NaN everything that cannot be converted to a numeric value, so strings that represent numeric values will not be removed. For example '1.25' will be recognized as the numeric value 1.25.

Disclaimer: pd.to_numeric was introduced in pandas version 0.17.0

Example:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({"item": ["a", "b", "c", "d", "e"],
   ...:                    "a": [1,2,3,"bad",5],
   ...:                    "b":[0.1,0.2,0.3,0.4,0.5]})

In [3]: df
Out[3]: 
     a    b item
0    1  0.1    a
1    2  0.2    b
2    3  0.3    c
3  bad  0.4    d
4    5  0.5    e

In [4]: data_columns = ['a', 'b']

In [5]: num_df = (df
   ...:           .drop(data_columns, axis=1)
   ...:           .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

In [6]: num_df
Out[6]: 
  item   a    b
0    a   1  0.1
1    b   2  0.2
2    c   3  0.3
3    d NaN  0.4
4    e   5  0.5

In [7]: num_df[num_df[data_columns].notnull().all(axis=1)]
Out[7]: 
  item  a    b
0    a  1  0.1
1    b  2  0.2
2    c  3  0.3
4    e  5  0.5

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

Red lines under the ViewBag was my headache for 3 month ). Just remove the Microsoft.CSharp reference from project and then add it again.

SQL Server Insert if not exists

The INSERT command doesn't have a WHERE clause - you'll have to write it like this:

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   IF NOT EXISTS (SELECT * FROM EmailsRecebidos 
                   WHERE De = @_DE
                   AND Assunto = @_ASSUNTO
                   AND Data = @_DATA)
   BEGIN
       INSERT INTO EmailsRecebidos (De, Assunto, Data)
       VALUES (@_DE, @_ASSUNTO, @_DATA)
   END
END

Convert an array to string

My suggestion:

using System.Linq;

string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());

reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c

Numpy first occurrence of value greater than existing value

In [34]: a=np.arange(-10,10)

In [35]: a
Out[35]:
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])

In [36]: np.where(a>5)
Out[36]: (array([16, 17, 18, 19]),)

In [37]: np.where(a>5)[0][0]
Out[37]: 16

How to find indices of all occurrences of one string in another in JavaScript?

I would recommend Tim's answer. However, this comment by @blazs states "Suppose searchStr=aaa and that str=aaaaaa. Then instead of finding 4 occurences your code will find only 2 because you're making skips by searchStr.length in the loop.", which is true by looking at Tim's code, specifically this line here: startIndex = index + searchStrLen; Tim's code would not be able to find an instance of the string that's being searched that is within the length of itself. So, I've modified Tim's answer:

_x000D_
_x000D_
function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + 1;
    }
    return indices;
}
var searchStr = prompt("Enter a string.");
var str = prompt("What do you want to search for in the string?");
var indices = getIndicesOf(str, searchStr);

document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Changing it to + 1 instead of + searchStrLen will allow the index 1 to be in the indices array if I have an str of aaaaaa and a searchStr of aaa.

P.S. If anyone would like comments in the code to explain how the code works, please say so, and I'll be happy to respond to the request.

How to display div after click the button in Javascript?

<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>

<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>

<div id="toggle" style="display:none">Hello</div>

how to add script inside a php code?

You could use PHP's file_get_contents();

<?php

   $script = file_get_contents('javascriptFile.js');
   echo "<script>".$script."</script>";

?>

For more information on the function:

http://php.net/manual/en/function.file-get-contents.php

How do I configure different environments in Angular.js?

We could also do something like this.

(function(){
    'use strict';

    angular.module('app').service('env', function env() {

        var _environments = {
            local: {
                host: 'localhost:3000',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            dev: {
                host: 'dev.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            test: {
                host: 'test.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            stage: {
                host: 'stage.com',
                config: {
                apiroot: 'staging'
                }
            },
            prod: {
                host: 'production.com',
                config: {
                    apiroot: 'production'
                }
            }
        },
        _environment;

        return {
            getEnvironment: function(){
                var host = window.location.host;
                if(_environment){
                    return _environment;
                }

                for(var environment in _environments){
                    if(typeof _environments[environment].host && _environments[environment].host == host){
                        _environment = environment;
                        return _environment;
                    }
                }

                return null;
            },
            get: function(property){
                return _environments[this.getEnvironment()].config[property];
            }
        }

    });

})();

And in your controller/service, we can inject the dependency and call the get method with property to be accessed.

(function() {
    'use strict';

    angular.module('app').service('apiService', apiService);

    apiService.$inject = ['configurations', '$q', '$http', 'env'];

    function apiService(config, $q, $http, env) {

        var service = {};
        /* **********APIs **************** */
        service.get = function() {
            return $http.get(env.get('apiroot') + '/api/yourservice');
        };

        return service;
    }

})();

$http.get(env.get('apiroot') would return the url based on the host environment.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

Try cleaning the local .m2/repository/ folder manually using rm -rf and then re build the project. Worked for me after trying every possible other alternative(reinstalling eclipse, pointing to the correct maven version in eclipse, proxy settings etc)

Jquery check if element is visible in viewport

Check if element is visible in viewport using jquery:

First determine the top and bottom positions of the element. Then determine the position of the viewport's bottom (relative to the top of your page) by adding the scroll position to the viewport height.

If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially). In simpler terms, when any part of the element is between the top and bottom bounds of your viewport, the element is visible on your screen.

Now you can write an if/else statement, where the if statement only runs when the above condition is met.

The code below executes what was explained above:

// this function runs every time you are scrolling

$(window).scroll(function() {
    var top_of_element = $("#element").offset().top;
    var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
    var top_of_screen = $(window).scrollTop();

    if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        // the element is visible, do something
    } else {
        // the element is not visible, do something else
    }
});

This answer is a summary of what Chris Bier and Andy were discussing below. I hope it helps anyone else who comes across this question while doing research like I did. I also used an answer to the following question to formulate my answer: Show Div when scroll position.

Convert hex to binary

Use Built-in format() function and int() function It's simple and easy to understand. It's little bit simplified version of Aaron answer

int()

int(string, base)

format()

format(integer, # of bits)

Example

# w/o 0b prefix
>> format(int("ABC123EFFF", 16), "040b")
1010101111000001001000111110111111111111

# with 0b prefix
>> format(int("ABC123EFFF", 16), "#042b")
0b1010101111000001001000111110111111111111

# w/o 0b prefix + 64bit
>> format(int("ABC123EFFF", 16), "064b")
0000000000000000000000001010101111000001001000111110111111111111

See also this answer

How to add ID property to Html.BeginForm() in asp.net mvc?

In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details

BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)

Means you should use like this :

Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)

So, it worked in MVC 4

@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
    new { @id = "signupform" }))
{
    <input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
    <input type="submit" value="Create" id="btnSubmit" />
}

Importing project into Netbeans

From Netbeans 8.1 - there is an "Import from ZIP" option.

Go to Main Menu -> File -> Import Project -> from ZIP.

Browse your .ZIP file's location via Browse button.

If you have Java project depending on external Libraries, Netbeans will highlight & ask for "Resolving problems" in project, click on resolve, provide location in your file system containing required library files .e.g JARs etc & you will be good to go.

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

When we use CommandObj.Parameter.Add() it takes 2 parameters, the first is procedure parameter and the second is its data type, while .AddWithValue() takes 2 parameters, the first is procedure parameter and the second is the data variable

CommandObj.Parameter.Add("@ID",SqlDbType.Int).Value=textBox1.Text;

for .AddWithValue

CommandObj.Parameter.AddWitheValue("@ID",textBox1.Text);

where ID is the parameter of stored procedure which data type is Int

Duplicate / Copy records in the same MySQL table

I just wanted to extend Alex's great answer to make it appropriate if you happen to want to duplicate an entire set of records:

SET @x=7;
CREATE TEMPORARY TABLE tmp SELECT * FROM invoices;
UPDATE tmp SET id=id+@x;
INSERT INTO invoices SELECT * FROM tmp;

I just had to do this and found Alex's answer a perfect jumping off point!. Of course, you have to set @x to the highest row number in the table (I'm sure you could grab that with a query). This is only useful in this very specific situation, so be careful using it when you don't wish to duplicate all rows. Adjust the math as necessary.

Create a new Ruby on Rails application using MySQL instead of SQLite

You should use the switch -D instead of -d because it will generate two apps and mysql with no documentation folders.

  rails -D mysql project_name  (less than version 3)

  rails new project_name -D mysql (version 3 and up)

Alternatively you just use the --database option.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

Finishing current activity from a fragment

This does not need assertion, Latest update in fragment in android JetPack

requireActivity().finish();

How to Select Min and Max date values in Linq Query

This should work for you

//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();

//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max(); 

(From here)

Good MapReduce examples

Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.

For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner

Here is a wikipedia article explaining what map-reduce is all about

Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.

Personally, found this link quite useful to understand the concept

Copying the explanation provided in the blog (In case the link goes stale)

Finding Friends

MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.

I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:

3 : the
3 : and
3 : you
4 : then
4 : what
4 : when
5 : steve
5 : where
8 : savannah
8 : research

They get grouped as:

3 : [the, and, you]
4 : [then, what, when]
5 : [steve, where]
8 : [savannah, research]

Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:

3 : 3
4 : 3
5 : 2
8 : 2

The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...

The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.

The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of 1. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.

Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):

Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.

Assume the friends are stored as Person->[List of Friends], our friends list is then:

A -> B C D
B -> A C D E
C -> A B D E
D -> A B C E
E -> B C D

Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:

For map(A -> B C D) :

(A B) -> B C D
(A C) -> B C D
(A D) -> B C D

For map(B -> A C D E) : (Note that A comes before B in the key)

(A B) -> A C D E
(B C) -> A C D E
(B D) -> A C D E
(B E) -> A C D E
For map(C -> A B D E) :

(A C) -> A B D E
(B C) -> A B D E
(C D) -> A B D E
(C E) -> A B D E
For map(D -> A B C E) :

(A D) -> A B C E
(B D) -> A B C E
(C D) -> A B C E
(D E) -> A B C E
And finally for map(E -> B C D):

(B E) -> B C D
(C E) -> B C D
(D E) -> B C D
Before we send these key-value pairs to the reducers, we group them by their keys and get:

(A B) -> (A C D E) (B C D)
(A C) -> (A B D E) (B C D)
(A D) -> (A B C E) (B C D)
(B C) -> (A B D E) (A C D E)
(B D) -> (A B C E) (A C D E)
(B E) -> (A C D E) (B C D)
(C D) -> (A B C E) (A B D E)
(C E) -> (A B D E) (B C D)
(D E) -> (A B C E) (B C D)

Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.

The result after reduction is:

(A B) -> (C D)
(A C) -> (B D)
(A D) -> (B C)
(B C) -> (A D E)
(B D) -> (A C E)
(B E) -> (C D)
(C D) -> (A B E)
(C E) -> (B D)
(D E) -> (B C)

Now when D visits B's profile, we can quickly look up (B D) and see that they have three friends in common, (A C E).

How do I print the key-value pairs of a dictionary in python

Your existing code just needs a little tweak. i is the key, so you would just need to use it:

for i in d:
    print i, d[i]

You can also get an iterator that contains both keys and values. In Python 2, d.items() returns a list of (key, value) tuples, while d.iteritems() returns an iterator that provides the same:

for k, v in d.iteritems():
    print k, v

In Python 3, d.items() returns the iterator; to get a list, you need to pass the iterator to list() yourself.

for k, v in d.items():
    print(k, v)

Remove useless zero digits from decimals in PHP

If you want to remove the zero digits just before to display on the page or template.

You can use the sprintf() function

sprintf('%g','125.00');
//125

??sprintf('%g','966.70');
//966.7

????sprintf('%g',844.011);
//844.011

ReactJS: Warning: setState(...): Cannot update during an existing state transition

From react docs Passing arguments to event handlers

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

Append text to file from command line without using io redirection

You can use the --append feature of tee:

cat file01.txt | tee --append bothFiles.txt 
cat file02.txt | tee --append bothFiles.txt 

Or shorter,

cat file01.txt file02.txt | tee --append bothFiles.txt 

I assume the request for no redirection (>>) comes from the need to use this in xargs or similar. So if that doesn't count, you can mute the output with >/dev/null.

Change status bar text color to light in iOS 9 with Objective-C

If you want to change Status Bar Style from the launch screen, You should take this way.

  1. Go to Project -> Target,

  2. Set Status Bar Style to Light Project Setting

  3. Set View controller-based status bar appearance to NO in Info.plist.

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

PostgreSQL 9.0 or later:

Recent versions of Postgres (since late 2010) have the string_agg(expression, delimiter) function which will do exactly what the question asked for, even letting you specify the delimiter string:

SELECT company_id, string_agg(employee, ', ')
FROM mytable
GROUP BY company_id;

Postgres 9.0 also added the ability to specify an ORDER BY clause in any aggregate expression; otherwise, the order is undefined. So you can now write:

SELECT company_id, string_agg(employee, ', ' ORDER BY employee)
FROM mytable
GROUP BY company_id;

Or indeed:

SELECT string_agg(actor_name, ', ' ORDER BY first_appearance)

PostgreSQL 8.4 or later:

PostgreSQL 8.4 (in 2009) introduced the aggregate function array_agg(expression) which concatenates the values into an array. Then array_to_string() can be used to give the desired result:

SELECT company_id, array_to_string(array_agg(employee), ', ')
FROM mytable
GROUP BY company_id;

string_agg for pre-8.4 versions:

In case anyone comes across this looking for a compatibilty shim for pre-9.0 databases, it is possible to implement everything in string_agg except the ORDER BY clause.

So with the below definition this should work the same as in a 9.x Postgres DB:

SELECT string_agg(name, '; ') AS semi_colon_separated_names FROM things;

But this will be a syntax error:

SELECT string_agg(name, '; ' ORDER BY name) AS semi_colon_separated_names FROM things;
--> ERROR: syntax error at or near "ORDER"

Tested on PostgreSQL 8.3.

CREATE FUNCTION string_agg_transfn(text, text, text)
    RETURNS text AS 
    $$
        BEGIN
            IF $1 IS NULL THEN
                RETURN $2;
            ELSE
                RETURN $1 || $3 || $2;
            END IF;
        END;
    $$
    LANGUAGE plpgsql IMMUTABLE
COST 1;

CREATE AGGREGATE string_agg(text, text) (
    SFUNC=string_agg_transfn,
    STYPE=text
);

Custom variations (all Postgres versions)

Prior to 9.0, there was no built-in aggregate function to concatenate strings. The simplest custom implementation (suggested by Vajda Gabo in this mailing list post, among many others) is to use the built-in textcat function (which lies behind the || operator):

CREATE AGGREGATE textcat_all(
  basetype    = text,
  sfunc       = textcat,
  stype       = text,
  initcond    = ''
);

Here is the CREATE AGGREGATE documentation.

This simply glues all the strings together, with no separator. In order to get a ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together and tested on 8.3.12:

CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$
  BEGIN
    IF acc IS NULL OR acc = '' THEN
      RETURN instr;
    ELSE
      RETURN acc || ', ' || instr;
    END IF;
  END;
$$ LANGUAGE plpgsql;

This version will output a comma even if the value in the row is null or empty, so you get output like this:

a, b, c, , e, , g

If you would prefer to remove extra commas to output this:

a, b, c, e, g

Then add an ELSIF check to the function like this:

CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$
  BEGIN
    IF acc IS NULL OR acc = '' THEN
      RETURN instr;
    ELSIF instr IS NULL OR instr = '' THEN
      RETURN acc;
    ELSE
      RETURN acc || ', ' || instr;
    END IF;
  END;
$$ LANGUAGE plpgsql;