Programs & Examples On #Continuous testing

Handle Button click inside a row in RecyclerView

You can check if you have any similar entries first, if you get a collection with size 0, start a new query to save.

OR

more professional and faster way. create a cloud trigger (before save)

check out this answer https://stackoverflow.com/a/35194514/1388852

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

C# 30 Days From Todays Date

if (cmb_mode_of_service.SelectedItem != null && cmb_term_of_service.SelectedItem != null)
            {
                if (cmb_mode_of_service.SelectedIndex > 0 && cmb_term_of_service.SelectedIndex > 0)
                {
                    if (cmb_mode_of_service.SelectedItem.ToString() == "Single Service/Installation" || cmb_term_of_service.SelectedItem.ToString() == "Single Time")
                    {
                        int c2 = 1;
                        char c1 = 'A';
                        DataRow dr = dt.NewRow();
                        dr["SN"] = c2++;
                        dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                        dr["servicedate"] = service_start_date.Text;
                        dr["servicestatus"] = "Pending";
                        dr["serviceexcutive"] = "Not Alowed";
                        dt.Rows.Add(dr);
                        dataGridView1.DataSource = dt;

                        txtexpirydate.Text = (Convert.ToDateTime(service_start_date.Text).AddDays(1)).ToString();

                    }
                    else
                    {



                        if (cmb_mode_of_service.SelectedItem.ToString() == "Weekly Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(7); dt1 <= Enddate; dt1 = dt1.AddDays(7))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                //txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                        if (cmb_mode_of_service.SelectedItem.ToString() == "Fortnight Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(15); dt1 <= Enddate; dt1 = dt1.AddDays(15))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                //  txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                        if (cmb_mode_of_service.SelectedItem.ToString() == "Monthly Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(30); dt1 <= Enddate; dt1 = dt1.AddDays(30))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                // txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }


                        if (cmb_mode_of_service.SelectedItem.ToString() == "Trimister Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(90); dt1 <= Enddate; dt1 = dt1.AddDays(90))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                // txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                        if (cmb_mode_of_service.SelectedItem.ToString() == "Half Yearly Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(180); dt1 <= Enddate; dt1 = dt1.AddDays(180))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                //  txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                        if (cmb_mode_of_service.SelectedItem.ToString() == "Yearly Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(365); dt1 <= Enddate; dt1 = dt1.AddDays(365))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                //txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                    }
                }

Network usage top/htop on Linux

Another option you could try is iptstate.

Best way to encode text data for XML in Java?

While idealism says use an XML library, IMHO if you have a basic idea of XML then common sense and performance says template it all the way. It's arguably more readable too. Though using the escaping routines of a library is probably a good idea.

Consider this: XML was meant to be written by humans.

Use libraries for generating XML when having your XML as an "object" better models your problem. For example, if pluggable modules participate in the process of building this XML.

Edit: as for how to actually escape XML in templates, use of CDATA or escapeXml(string) from JSTL are two good solutions, escapeXml(string) can be used like this:

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<item>${fn:escapeXml(value)}</item>

What is the difference between Select and Project Operations

select just changes cardinality of the result table but project does change both degree of relation and cardinality.

Call a Vue.js component method from outside the component

I am not sure is it the right way but this one works for me.
First import the component which contains the method you want to call in your component

import myComponent from './MyComponent'

and then call any method of MyCompenent

myComponent.methods.doSomething()

Centering in CSS Grid

You can use flexbox to center your text. By the way no need for extra containers because text is considered as anonymous flex item.

From flexbox specs:

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space (i.e. characters that can be affected by the white-space property) is not rendered (just as if it were display:none).

So just make grid items as flex containers (display: flex), and add align-items: center and justify-content: center to center both vertically and horizontally.

Also performed optimization of HTML and CSS:

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-template-rows: 100vh;_x000D_
  _x000D_
  font-family: Raleway;_x000D_
  font-size: large;_x000D_
}_x000D_
_x000D_
.left_bg,_x000D_
.right_bg {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
  background-color: #3498db;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
  background-color: #ecf0f1;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left_bg">Review my stuff</div>_x000D_
  <div class="right_bg">Hire me!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java 6 Unsupported major.minor version 51.0

add jdk8 or higher version at JAVA_HOME and path.

add JAVA_HOME add C:\ProgramFiles\Java\jdk1.8.0_201

For Path =>

add %MAVEN_HOME%\bin

and finally restart your pc.

How to check the gradle version in Android Studio?

Image shown below. I'm only typing this because of a 30 character minimum imposed by Stackoverflow.

enter image description here

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

So many answers.... all bad!

Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...

But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords.

anything with less than 8 characters OR anything with no numbers OR anything with no uppercase OR anything with no special characters

So:

^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$

If anything matches that, then it's an invalid password.

Matplotlib discrete colorbar

You could follow this example:

#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.

Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""

from pylab import *


delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('PiYG', 11)    # 11 discrete colors

im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()

which produces the following image:

poormans_contour

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size

...

plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

Meaning of delta or epsilon argument of assertEquals for double values

Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!

From the JUnit javadoc:

delta - the maximum delta between expected and actual for which both numbers are still considered equal.

It's probably overkill, but I typically use a really small number, e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertEquals(123.456, 123.456, DELTA);
}

If you're using hamcrest assertions, you can just use the standard equalTo() with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo() (see javadoc), e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertThat(123.456, equalTo(123.456));
    assertThat(123.456, closeTo(123.456, DELTA));
}

FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals() with two doubles. The implementation (if you're interested) is:

private static boolean doublesAreEqual(double value1, double value2) {
    return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}

Prevent Android activity dialog from closing on outside touch

What you actually have is an Activity (even if it looks like a Dialog), therefore you should call setFinishOnTouchOutside(false) from your activity if you want to keep it open when the background activity is clicked.

EDIT: This only works with android API level 11 or greater

Uncaught TypeError: Cannot read property 'value' of undefined

Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.

from jquery $.ajax to angular $http

You may use this :

Download "angular-post-fix": "^0.1.0"

Then add 'httpPostFix' to your dependencies while declaring the angular module.

Ref : https://github.com/PabloDeGrote/angular-httppostfix

How do I suspend painting for a control and its children?

At my previous job we struggled with getting our rich UI app to paint instantly and smoothly. We were using standard .Net controls, custom controls and devexpress controls.

After a lot of googling and reflector usage I came across the WM_SETREDRAW win32 message. This really stops controls drawing whilst you update them and can be applied, IIRC to the parent/containing panel.

This is a very very simple class demonstrating how to use this message:

class DrawingControl
{
    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);

    private const int WM_SETREDRAW = 11; 

    public static void SuspendDrawing( Control parent )
    {
        SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
    }

    public static void ResumeDrawing( Control parent )
    {
        SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
        parent.Refresh();
    }
}

There are fuller discussions on this - google for C# and WM_SETREDRAW, e.g.

C# Jitter

Suspending Layouts

And to whom it may concern, this is similar example in VB:

Public Module Extensions
    <DllImport("user32.dll")>
    Private Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Boolean, ByVal lParam As IntPtr) As Integer
    End Function

    Private Const WM_SETREDRAW As Integer = 11

    ' Extension methods for Control
    <Extension()>
    Public Sub ResumeDrawing(ByVal Target As Control, ByVal Redraw As Boolean)
        SendMessage(Target.Handle, WM_SETREDRAW, True, 0)
        If Redraw Then
            Target.Refresh()
        End If
    End Sub

    <Extension()>
    Public Sub SuspendDrawing(ByVal Target As Control)
        SendMessage(Target.Handle, WM_SETREDRAW, False, 0)
    End Sub

    <Extension()>
    Public Sub ResumeDrawing(ByVal Target As Control)
        ResumeDrawing(Target, True)
    End Sub
End Module

How to pass a textbox value from view to a controller in MVC 4?

When you want to pass new information to your application, you need to use POST form. In Razor you can use the following

View Code:

@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
     @Html.Hidden("id", Model.Id)
     @Html.Hidden("productid", Model.ProductId)
     @Html.TextBox("qty", Model.Quantity)
     @Html.TextBox("unitrate", Model.UnitRate)
     <input type="submit" value="Update" />
}

Controller's actions

[HttpGet]
public ActionResult Update(){
     //[...] retrive your record object
     return View(objRecord);
}

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
      if (ModelState.IsValid){
           int _records = UpdatePrice(id,productid,qty,unitrate);
           if (_records > 0){                    {
              return RedirectToAction("Index1", "Shopping");
           }else{                   
                ModelState.AddModelError("","Can Not Update");
           }
      }
      return View("Index1");
 }

Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity) you can either have an input with the name (respectecting case) "Quantity" or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:

Model

public class Record {
    public string Id { get; set; }
    public string ProductId { get; set; }
    public string Quantity { get; set; }
    public decimal UnitRate { get; set; }
}

View

@using(Html.BeginForm("Update")){
     @Html.HiddenFor(model => model.Id)
     @Html.HiddenFor(model => model.ProductId)
     @Html.TextBoxFor(model=> model.Quantity)
     @Html.TextBoxFor(model => model.UnitRate)
     <input type="submit" value="Update" />
}

Post Action

[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well 
   if(TryValidateModel(rec)){
        //update code
   }
   return View("Index1");
}

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

Use the below code to resolve the issue.

import json
from numpyencoder import NumpyEncoder
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 
15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8',cls=NumpyEncoder))
afile.close()

How to get text box value in JavaScript

+1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.

i am getting only "software".

id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:

<input type="text" name="txtJob" value=software engineer>

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

Strings & VARCHAR.

  • Do not try storing phone numbers as actual numbers. it will ruin the formatting, remove preceding 0s and other undesirable things.

  • You may, if you choose to, restrict user inputs to just numeric values but even in that case, keep your backing persisted data as characters/strings and not numbers.

  • Be aware of the wider world and how their number lengths and formatting differ before you try to implement any sort of length restrictions, validations or masks (eg XXX-XXXX-XX).

  • Non numeric characters can be valid in phone numbers. A prime example being + as a replacement for 00 at the start of an international number.

Edited in from conversation in comments:

  • It is one of the bigger UI mistakes that phone numbers have anything to do with numerics. It is much better to think of and treat them like addresses, it is closer to what they actually are and represent than phone "numbers".

$(document).click() not working correctly on iPhone. jquery

try this, applies only to iPhone and iPod so you're not making everything turn blue on chrome or firefox mobile;

/iP/i.test(navigator.userAgent) && $('*').css('cursor', 'pointer');

basically, on iOS, things aren't "clickable" by default -- they're "touchable" (pfffff) so you make them "clickable" by giving them a pointer cursor. makes total sense, right??

Where does Jenkins store configuration files for the jobs it runs?

Jenkins 1.627, OS X 10.10.5 /Users/Shared/Jenkins/Home/jobs/{project_name}/config.xml

An URL to a Windows shared folder

I think there are two issues:

  1. You need to escape the slashes.
  2. Browser security.

Explanation:

  1. I checked one of mine, I have the pattern:

    <a href="file://///server01\fshare\dir1\dir2\dir3">useful link </a>
    

    Please note that we ended up with 5 slashes after the protocol (file:)

  2. Firefox will try to prevent cross site scripting. My solution was to modify prefs.js in the profile directory. You will add two lines:

    user_pref("capability.policy.localfilelinks.checkloaduri.enabled", "allAccess");
    user_pref("capability.policy.localfilelinks.sites", "http://mysite.company.org");
    

iOS / Android cross platform development

My experience with making something very simple in PhoneGap+jQuery Mobile was fine. I was able to do it quickly for iOS. However, it didn't work on my Android phones without making some changes. The project was a very simple app to take pictures and post them to a web site. And at the end of the day it felt "clunky" compared to a true native app.

I don't believe there will ever be easy cross platform development. I think the browser is as close as you will get. By choosing something like PhoneGap I think you are just trading one set of pain points for a different set of pain points.

Output data with no column headings using PowerShell

In your case, when you just select a single property, the easiest way is probably to bypass any formatting altogether:

get-qadgroupmember 'Domain Admins' | foreach { $_.Name }

This will get you a simple string[] without column headings or empty lines. The Format-* cmdlets are mainly for human consumption and thus their output is not designed to be easily machine-readable or -parseable.

For multiple properties I'd probably go with the -f format operator. Something along the lines of

alias | %{ "{0,-10}{1,-10}{2,-60}" -f $_.COmmandType,$_.Name,$_.Definition }

which isn't pretty but gives you easy and complete control over the output formatting. And no empty lines :-)

How can you find the height of text on an HTML canvas?

This works 1) for multiline text as well 2) and even in IE9!

<div class="measureText" id="measureText">
</div>


.measureText {
  margin: 0;
  padding: 0;
  border: 0;
  font-family: Arial;
  position: fixed;
  visibility: hidden;
  height: auto;
  width: auto;
  white-space: pre-wrap;
  line-height: 100%;
}

function getTextFieldMeasure(fontSize, value) {
    const div = document.getElementById("measureText");

    // returns wrong result for multiline text with last line empty
    let arr = value.split('\n');
    if (arr[arr.length-1].length == 0) {
        value += '.';
    }

    div.innerText = value;
    div.style['font-size']= fontSize + "px";
    let rect = div.getBoundingClientRect();

    return {width: rect.width, height: rect.height};
};

Generate Json schema from XML schema (XSD)

Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.

Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.

Let's take the Purchase Order schema for example. Here's a fragment:

  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>

  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>

You can compile this schema using the provided command-line tool:

java -jar jsonix-schema-compiler-full.jar
    -generateJsonSchema
    -p PO
    schemas/purchaseorder.xsd

The compiler generates Jsonix mappings as well the matching JSON Schema.

Here's what the result looks like (edited for brevity):

{
    "id":"PurchaseOrder.jsonschema#",
    "definitions":{
        "PurchaseOrderType":{
            "type":"object",
            "title":"PurchaseOrderType",
            "properties":{
                "shipTo":{
                    "title":"shipTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                },
                "billTo":{
                    "title":"billTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                }, ...
            }
        },
        "USAddress":{ ... }, ...
    },
    "anyOf":[
        {
            "type":"object",
            "properties":{
                "name":{
                    "$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
                },
                "value":{
                    "$ref":"#/definitions/PurchaseOrderType"
                }
            },
            "elementName":{
                "localPart":"purchaseOrder",
                "namespaceURI":""
            }
        }
    ]
}

Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.

The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).

Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.

Links:

error while loading shared libraries: libncurses.so.5:

On Arch, i fix like this:

sudo ln -s /usr/lib/libncursesw.so.6 /usr/lib/libtinfo.so.6

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

I also use this

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

but I don't get any error.

Did you include the jstl.jar in your library? If not maybe this causing the problem. And also the 'tld' folder do you have it? And how about your web.xml did you map it?

Have a look on the info about jstl for other information.

What should I use to open a url instead of urlopen in urllib3

urllib3 is a different library from urllib and urllib2. It has lots of additional features to the urllibs in the standard library, if you need them, things like re-using connections. The documentation is here: https://urllib3.readthedocs.org/

If you'd like to use urllib3, you'll need to pip install urllib3. A basic example looks like this:

from bs4 import BeautifulSoup
import urllib3

http = urllib3.PoolManager()

url = 'http://www.thefamouspeople.com/singers.php'
response = http.request('GET', url)
soup = BeautifulSoup(response.data)

How to create an empty file at the command line in Windows?

As a VIM user on windows, I failed to find the answer in this question thread.

As a solution from this thread, please install the gvim firstly.
During the installation, please remember to check the option "Create .bat files for command line use" as shown below.

enter image description here

Some bat files like vim.bat and gvim.bat will be installed under C:\Windows. Add C:\Windows to system Path if it's not done.

Relaunch the cmd.exe and type gvim empty_file.txt, you will launch the gvim to edit the empty file from scratch. If you don't want to leave your "Command Prompt" console, type vim empty_file.txt instead.

Hope this answer can help those who want to launch VIM from windows Command Prompt when creating an empty file.

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

AlertDialog styling - how to change style (color) of title, message, etc

It depends how much you want to customize the alert dialog. I have different steps in order to customize the alert dialog. Please visit: https://stackoverflow.com/a/33439849/5475941

enter image description here enter image description here enter image description here enter image description here

In AVD emulator how to see sdcard folder? and Install apk to AVD?

if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command

adb install apklocation.apk

Extracting .jar file with command line

jar xf myFile.jar
change myFile to name of your file
this will save the contents in the current folder of .jar file
that should do :)

JavaScript Promises - reject vs. throw

Yes, the biggest difference is that reject is a callback function that gets carried out after the promise is rejected, whereas throw cannot be used asynchronously. If you chose to use reject, your code will continue to run normally in asynchronous fashion whereas throw will prioritize completing the resolver function (this function will run immediately).

An example I've seen that helped clarify the issue for me was that you could set a Timeout function with reject, for example:

_x000D_
_x000D_
new Promise((resolve, reject) => {
  setTimeout(()=>{reject('err msg');console.log('finished')}, 1000);
  return resolve('ret val')
})
.then((o) => console.log("RESOLVED", o))
.catch((o) => console.log("REJECTED", o));
_x000D_
_x000D_
_x000D_

The above could would not be possible to write with throw.

_x000D_
_x000D_
try{
  new Promise((resolve, reject) => {
    setTimeout(()=>{throw new Error('err msg')}, 1000);
    return resolve('ret val')
  })
  .then((o) => console.log("RESOLVED", o))
  .catch((o) => console.log("REJECTED", o));
}catch(o){
  console.log("IGNORED", o)
}
_x000D_
_x000D_
_x000D_

In the OP's small example the difference in indistinguishable but when dealing with more complicated asynchronous concept the difference between the two can be drastic.

Android: Is it possible to display video thumbnails?

Using the class:

import android.provider.MediaStore.Video.Thumbnails;

We can get two preview thumbnail sizes from the video:

Thumbnails.MICRO_KIND for 96 x 96

Thumbnails.MINI_KIND for 512 x 384 px

This is a code example:

String filePath = "/sdcard/DCIM/Camera/my_video.mp4"; //change the location of your file!

ImageView imageview_mini = (ImageView)findViewById(R.id.thumbnail_mini);
ImageView imageview_micro = (ImageView)findViewById(R.id.thumbnail_micro);

Bitmap bmThumbnail;

//MICRO_KIND, size: 96 x 96 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MICRO_KIND);
imageview_micro.setImageBitmap(bmThumbnail);
     
// MINI_KIND, size: 512 x 384 thumbnail 
bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MINI_KIND);
imageview_mini.setImageBitmap(bmThumbnail);

Recommended way of making React component/div draggable

react-draggable is also easy to use. Github:

https://github.com/mzabriskie/react-draggable

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Draggable from 'react-draggable';

var App = React.createClass({
    render() {
        return (
            <div>
                <h1>Testing Draggable Windows!</h1>
                <Draggable handle="strong">
                    <div className="box no-cursor">
                        <strong className="cursor">Drag Here</strong>
                        <div>You must click my handle to drag me</div>
                    </div>
                </Draggable>
            </div>
        );
    }
});

ReactDOM.render(
    <App />, document.getElementById('content')
);

And my index.html:

<html>
    <head>
        <title>Testing Draggable Windows</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
        <div id="content"></div>
        <script type="text/javascript" src="bundle.js" charset="utf-8"></script>    
    <script src="http://localhost:8080/webpack-dev-server.js"></script>
    </body>
</html>

You need their styles, which is short, or you don't get quite the expected behavior. I like the behavior more than some of the other possible choices, but there's also something called react-resizable-and-movable. I'm trying to get resize working with draggable, but no joy so far.

Javascript + Regex = Nothing to repeat error?

Firstly, in a character class [...] most characters don't need escaping - they are just literals.

So, your regex should be:

"[\[\]?*+|{}\\()@.\n\r]"

This compiles for me.

How to convert a time string to seconds?

Inspired by sverrir-sigmundarson's comment:

def time_to_sec(time_str):
    return sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time_str.split(":"))))

How to hide only the Close (x) button?

Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:

public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}

then you create a menu strip item to exit the application.

cheers

How to pass a parameter to routerLink that is somewhere inside the URL?

constructor(private activatedRoute: ActivatedRoute) {

this.activatedRoute.queryParams.subscribe(params => {
  console.log(params['type'])
  });  }

This works for me!

How to make child process die after parent exits?

I managed to do a portable, non-polling solution with 3 processes by abusing terminal control and sessions.

The trick is:

  • process A is started
  • process A creates a pipe P (and never reads from it)
  • process A forks into process B
  • process B creates a new session
  • process B allocates a virtual terminal for that new session
  • process B installs SIGCHLD handler to die when the child exits
  • process B sets a SIGPIPE handler
  • process B forks into process C
  • process C does whatever it needs (e.g. exec()s the unmodified binary or runs whatever logic)
  • process B writes to pipe P (and blocks that way)
  • process A wait()s on process B and exits when it dies

That way:

  • if process A dies: process B gets a SIGPIPE and dies
  • if process B dies: process A's wait() returns and dies, process C gets a SIGHUP (because when the session leader of a session with a terminal attached dies, all processes in the foreground process group get a SIGHUP)
  • if process C dies: process B gets a SIGCHLD and dies, so process A dies

Shortcomings:

  • process C can't handle SIGHUP
  • process C will be run in a different session
  • process C can't use session/process group API because it'll break the brittle setup
  • creating a terminal for every such operation is not the best idea ever

Moment Js UTC to Local Time

I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!

Full Example on Codesandbox (DEMO):

https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js

How can I open an Excel file in Python?

This code worked for me with Python 3.5.2. It opens and saves and excel. I am currently working on how to save data into the file but this is the code:

import csv
excel = csv.writer(open("file1.csv", "wb"))

 

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Duplicate symbols for architecture x86_64 under Xcode

I found the accepted answer touches on the problem but didn't help me solve it, hopefully this answer will help with this very frustrating issue.

duplicate symbol _OBJC_IVAR_$_BLoginViewController._hud in:

17 duplicate symbols for architecture x86_64

"Means that you have loaded same functions twice. As the issue disappear after removing -ObjC from Other Linker Flags, this means that this option result that functions loads twice:"

In layman's terms this means we have two files in our project with exactly the same name. Maybe you are combining one project into another one? Have a look at the errors above the "duplicate symbols" error to see which folder is duplicated, in my case it was BLoginViewController.

For example, in the image below you can see I have two BImageViewControllers, for me this is what was causing the issue.

As soon as I deleted one then the issue vanished :)

enter image description here

How to configure "Shorten command line" method for whole project in IntelliJ

The latest 2020 build doesn't have the shorten command line option by default we need to add that option from the configuration.

Run > Edit Configurations > Select the corresponding run configuration and click on Modify options for adding the shorten command-line configuration to the UI. enter image description here

Select the shorten command line option enter image description here

Now choose jar manifest from the shorten command line option enter image description here

jquery live hover

As of jQuery 1.4.1, the hover event works with live(). It basically just binds to the mouseenter and mouseleave events, which you can do with versions prior to 1.4.1 just as well:

$("table tr")
    .mouseenter(function() {
        // Hover starts
    })
    .mouseleave(function() {
        // Hover ends
    });

This requires two binds but works just as well.

How can I export tables to Excel from a webpage

This code is IE only so it is only useful in situations where you know all of your users will be using IE (like, for example, in some corporate environments.)

<script Language="javascript">
function ExportHTMLTableToExcel()
{
   var thisTable = document.getElementById("tbl").innerHTML;
   window.clipboardData.setData("Text", thisTable);
   var objExcel = new ActiveXObject ("Excel.Application");
   objExcel.visible = true;

   var objWorkbook = objExcel.Workbooks.Add;
   var objWorksheet = objWorkbook.Worksheets(1);
   objWorksheet.Paste;
}
</script>

Android app unable to start activity componentinfo

The question is answered already, but I want add more information about the causes.

Android app unable to start activity componentinfo

This error often comes with appropriate logs. You can read logs and can solve this issue easily.

Here is a sample log. In which you can see clearly ClassCastException. So this issue came because TextView cannot be cast to EditText.

Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050):     ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109):     ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167):     ... 11 more

Some Common Mistakes.

1.findViewById() of non existing view

Like when you use findViewById(R.id.button) when button id does not exist in layout XML.

2. Wrong cast.

If you wrong cast some class, then you get this error. Like you cast RelativeLayout to LinearLayout or EditText to TextView.

3. Activity not registered in manifest.xml

If you did not register Activity in manifest.xml then this error comes.

4. findViewById() with declaration at top level

Below code is incorrect. This will create error. Because you should do findViewById() after calling setContentView(). Because an View can be there after it is created.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
    //...
  }
}

5. Starting abstract Activity class.

When you try to start an Activity which is abstract, you will will get this error. So just remove abstract keyword before activity class name.

6. Using kotlin but kotlin not configured.

If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.

More information

Read about Downcast and Upcast

Read about findViewById() method of Activity class

Super keyword in Java

How to register activity in manifest

How do I compare two DateTime objects in PHP 5.2.8?

As of PHP 7.x, you can use the following:

$aDate = new \DateTime('@'.(time()));
$bDate = new \DateTime('@'.(time() - 3600));

$aDate <=> $bDate; // => 1, `$aDate` is newer than `$bDate`

Close all infowindows in Google Maps API v3

I encourage you to try goMap jQuery plugin when working with Google Maps. For this kind of situation you can set hideByClick to true when creating markers:

$(function() { 
    $("#map").goMap({ 
        markers: [{  
            latitude: 56.948813, 
            longitude: 24.704004, 
            html: { 
                content: 'Click to marker', 
                popup:true 
            } 
        },{  
            latitude: 54.948813, 
            longitude: 21.704004, 
            html: 'Hello!' 
        }], 
        hideByClick: true 
    }); 
}); 

This is just one example, it has many features to offer like grouping markers and manipulating info windows.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I ran into this issue as well and found this post. Ultimately none of these answers solved my problem, instead I had to put in a rewrite rule to strip out the location /rt as the backend my developers made was not expecting any additional paths:

+-(william@wkstn18)--(Thu, 05 Nov 20)-+
+-(~)--(16:13)->wscat -c ws://WebsocketServerHostname/rt
error: Unexpected server response: 502

Testing with wscat repeatedly gave a 502 response. Nginx error logs provided the same upstream error as above, but notice the upstream string shows the GET Request is attempting to access localhost:12775/rt and not localhost:12775:

 2020/11/05 22:13:32 [error] 10175#10175: *7 upstream prematurely closed
 connection while reading response header from upstream, client: WANIP,
 server: WebsocketServerHostname, request: "GET /rt/socket.io/?transport=websocket
 HTTP/1.1", upstream: "http://127.0.0.1:12775/rt/socket.io/?transport=websocket",
 host: "WebsocketServerHostname"

Since the devs had not coded their websocket (listening on 12775) to expect /rt/socket.io but instead just /socket.io/ (NOTE: /socket.io/ appears to just be a way to specify websocket transport discussed here). Because of this, rather than ask them to rewrite their socket code I just put in a rewrite rule to translate WebsocketServerHostname/rt to WebsocketServerHostname:12775 as below:

upstream websocket-rt {
        ip_hash;

        server 127.0.0.1:12775;
}

server {
        listen 80;
        server_name     WebsocketServerHostname;

        location /rt {
                proxy_http_version 1.1;

                #rewrite /rt/ out of all requests and proxy_pass to 12775
                rewrite /rt/(.*) /$1  break;

                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;

                proxy_pass http://websocket-rt;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection $connection_upgrade;
        }

}

Responsive Google Map?

It's better to use Google Map API. I've created an example here: http://jsfiddle.net/eugenebolotin/8m1s69e5/1/

Key features are using of functions:

//Full example is here: http://jsfiddle.net/eugenebolotin/8m1s69e5/1/

map.setCenter(map_center);
// Scale map to fit specified points
map.fitBounds(path_bounds);

It handles resize event and automaticaly adjusts size.

How do I list one filename per output line in Linux?

Use the -1 option (note this is a "one" digit, not a lowercase letter "L"), like this:

ls -1a

First, though, make sure your ls supports -1. GNU coreutils (installed on standard Linux systems) and Solaris do; but if in doubt, use man ls or ls --help or check the documentation. E.g.:

$ man ls
...
       -1     list one file per line.  Avoid '\n' with -q or -b

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

Cannot delete directory with Directory.Delete(path, true)

Editor's note: Although this answer contains some useful information, it is factually incorrect about the workings of Directory.Delete. Please read the comments for this answer, and other answers to this question.


I ran into this problem before.

The root of the problem is that this function does not delete files that are within the directory structure. So what you'll need to do is create a function that deletes all the files within the directory structure then all the directories before removing the directory itself. I know this goes against the second parameter but it's a much safer approach. In addition, you will probably want to remove READ-ONLY access attributes from the files right before you delete them. Otherwise that will raise an exception.

Just slap this code into your project.

public static void DeleteDirectory(string target_dir)
{
    string[] files = Directory.GetFiles(target_dir);
    string[] dirs = Directory.GetDirectories(target_dir);

    foreach (string file in files)
    {
        File.SetAttributes(file, FileAttributes.Normal);
        File.Delete(file);
    }

    foreach (string dir in dirs)
    {
        DeleteDirectory(dir);
    }

    Directory.Delete(target_dir, false);
}

Also, for me I personally add a restriction on areas of the machine that are allowed to be deleted because do you want someone to call this function on C:\WINDOWS (%WinDir%) or C:\.

the MySQL service on local computer started and then stopped

Nothing was working for me but then I checked here. I ran that command qc sc mysql57 and copied the value of BINARY_PATH_NAME from it. After that I checked this and changed the value of lower_case_table_names from 0 to 2 in my.ini file. Then in the command prompt, I ran this command - << BINARY_PATH_NAME >> --install-manual. After that, I started the MySQL57 service and it worked.

VMWare Player vs VMWare Workstation

from http://www.vmware.com/products/player/faqs.html:

How does VMware Player compare to VMware Workstation? VMware Player enables you to quickly and easily create and run virtual machines. However, VMware Player lacks many powerful features, remote connections to vSphere, drag and drop upload to vSphere, multiple Snapshots and Clones, and much more.

Not being able to revert snapshots it's a big no for me.

Correct Way to Load Assembly, Find Class and Call Run() Method

When you build your assembly, you can call AssemblyBuilder.SetEntryPoint, and then get it back from the Assembly.EntryPoint property to invoke it.

Keep in mind you'll want to use this signature, and note that it doesn't have to be named Main:

static void Run(string[] args)

Example for boost shared_mutex (multiple reads/one write)?

1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.

boost::shared_mutex _access;
void reader()
{
  boost::shared_lock< boost::shared_mutex > lock(_access);
  // do work here, without anyone having exclusive access
}

void conditional_writer()
{
  boost::upgrade_lock< boost::shared_mutex > lock(_access);
  // do work here, without anyone having exclusive access

  if (something) {
    boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
    // do work here, but now you have exclusive access
  }

  // do more work here, without anyone having exclusive access
}

void unconditional_writer()
{
  boost::unique_lock< boost::shared_mutex > lock(_access);
  // do work here, with exclusive access
}

Also Note, unlike a shared_lock, only a single thread can acquire an upgrade_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution.

Javascript use variable as object name

let players = [];
players[something] = {};
players[something].somethingElse = 'test';
console.log(players); 

-> [ something: { somethingElse: 'test' } ];

How to install php-curl in Ubuntu 16.04

This worked for me.

sudo apt-get install php-curl

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")

z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)

w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis

It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.

matplotlib savefig() plots different from show()

I have fixed this in my matplotlib source, but it's not a pretty fix. However, if you, like me, are very particular about how the graph looks, it's worth it.

The issue seems to be in the rendering backends; they each get the correct values for linewidth, font size, etc., but that comes out slightly larger when rendered as a PDF or PNG than when rendered with show().

I added a few lines to the source for PNG generation, in the file matplotlib/backends/backend_agg.py. You could make similar changes for each backend you use, or find a way to make a more clever change in a single location ;)

Added to my matplotlib/backends/backend_agg.py file:

    # The top of the file, added lines 42 - 44
42  # @warning: CHANGED FROM SOURCE to draw thinner lines
43  PATH_SCALAR = .8
44  FONT_SCALAR = .95

    # In the draw_markers method, added lines 90 - 91
89  def draw_markers(self, *kl, **kw):
90      # @warning: CHANGED FROM SOURCE to draw thinner lines
91      kl[0].set_linewidth(kl[0].get_linewidth()*PATH_SCALAR)
92      return self._renderer.draw_markers(*kl, **kw)

    # At the bottom of the draw_path method, added lines 131 - 132:
130 else:
131     # @warning: CHANGED FROM SOURCE to draw thinner lines
132     gc.set_linewidth(gc.get_linewidth()*PATH_SCALAR)
133     self._renderer.draw_path(gc, path, transform, rgbFace)

    # At the bottom of the _get_agg_font method, added line 242 and the *FONT_SCALAR
241     font.clear()
242     # @warning: CHANGED FROM SOURCE to draw thinner lines
243     size = prop.get_size_in_points()*FONT_SCALAR
244     font.set_size(size, self.dpi)

So that suits my needs for now, but, depending on what you're doing, you may want to implement similar changes in other methods. Or find a better way to do the same without so many line changes!

Update: After posting an issue to the matplotlib project at Github, I was able to track down the source of my problem: I had changed the figure.dpi setting in the matplotlibrc file. If that value is different than the default, my savefig() images come out different, even if I set the savefig dpi to be the same as the figure dpi. So, instead of changing the source as above, I just kept the figure.dpi setting as the default 80, and was able to generate images with savefig() that looked like images from show().

Leon, had you also changed that setting?

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

Have you recently changed your MySQL Server root password? If answer is YES, than this is the cause of the error / warning inside phpMyAdmin console. To fix the problem, simply edit your phpMyAdmin’s config-db.php file and setup the proper database password.

First answer is messing too much in my view and second answer did not work for me. So:

In Linux-based servers the file is usually located in:

/etc/phpmyadmin/config-db.php

or:

/etc/phpMyAdmin/config-db.php

Example: (My File looked like this and I changed the user fromphpmyadmin to admin, the username I created for maintaining my database through phpmyadmin, and put in the appropriate password.

$dbuser='phpmyadmin';
$dbpass=''; // set current password between quotes ' '
$basepath='';
$dbname='phpmyadmin';
$dbserver='';
$dbport='';
$dbtype='mysql';

credits: http://tehnoblog.org/phpmyadmin-error-connection-for-controluser-as-defined-in-your-configuration-failed/

How do you remove duplicates from a list whilst preserving order?

x = [1, 2, 1, 3, 1, 4]

# brute force method
arr = []
for i in x:
  if not i in arr:
    arr.insert(x[i],i)

# recursive method
tmp = []
def remove_duplicates(j=0):
    if j < len(x):
      if not x[j] in tmp:
        tmp.append(x[j])
      i = j+1  
      remove_duplicates(i)

      

remove_duplicates()

Can not connect to local PostgreSQL

My gut feeling is that this is (again) a mac/OSX-thing: the front end and the back end assume a different location for the unix-domain socket (which functions as a rendezvous point).

Checklist:

  • Is postgres running: ps aux | grep postgres | grep -v grep should do the trick
  • Where is the socket located: find / -name .s.PGSQL.5432 -ls (the socket used to be in /tmp; you could start looking there)
  • even if you locate the (unix-domain) socket, the client could use a different location. (this happens if you mix distributions, or of you have a distribution installed someplace and have another (eg from source) installation elsewhere), with client and server using different rendez-vous addresses.

If postgres is running, and the socket actually exists, you could use:

  • psql -h /the/directory/where/the/socket/was/found mydbname

(which attempts to connect to the unix-domain socket)

; you should now get the psql prompt: try \d and then \q to quit. You could also try:

  • psql -h localhost mydbname.

(which attempts to connect to localhost (127.0.0.1)

If these attempts fail because of insufficient authorisation, you could alter pg_hba.conf (and SIGHUP or restart) In this case: also check the logs.

A similar question: Can't get Postgres started

Note: If you can get to the psql prompt, the quick fix to this problem is just to change your config/database.yml, add:

host: localhost

or you could try adding:

host: /the/directory/where/the/socket/was/found

In my case, host: /tmp

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

input[type='text'], input[type='password']
{
   // my css
}

That is the correct way to do it. Sadly CSS is not a programming language.

Reporting Services Remove Time from DateTime in Expression

My solution for a Date/Time parameter:

=CDate(Today())

The trick is to convert back to a DateTime as recommend Perhentian.

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

Difference between the Apache HTTP Server and Apache Tomcat?

Apache is an HTTP web server which serve as HTTP.

Apache Tomcat is a java servlet container. It features same as web server but is customized to execute java servlet and JSP pages.

How can I hide/show a div when a button is clicked?

Task can be made simple javascript without jQuery etc.

<script type="text/javascript">
function showhide() {
document.getElementById("wizard").className = (document.getElementById("wizard").className=="swMain") ? swHide : swMain;
}
</script>

This function is simple if statement that looks if wizard has class swMain and change class to swHide and else if it's not swMain then change to swMain. This code doesn't support multiple class attributes but in this case it is just enough.

Now you have to make css class named swHide that has display: none

Then add on to the button onclick="showhide()"

So easy it is.

Finding and removing non ascii characters from an Oracle Varchar2

I had a similar issue and blogged about it here. I started with the regular expression for alpha numerics, then added in the few basic punctuation characters I liked:

select dump(a,1016), a, b
from
 (select regexp_replace(COLUMN,'[[:alnum:]/''%()> -.:=;[]','') a,
         COLUMN b
  from TABLE)
where a is not null
order by a;

I used dump with the 1016 variant to give out the hex characters I wanted to replace which I could then user in a utl_raw.cast_to_varchar2.

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

You must use the column names and then set the values to insert (both ? marks):

//insert 1st row            
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();

Getting a count of rows in a datatable that meet certain criteria

object count =dtFoo.Compute("count(IsActive)", "IsActive='Y'");

How do I print debug messages in the Google Chrome JavaScript Console?

I've had a lot of issues with developers checking in their console.() statements. And, I really don't like debugging Internet Explorer, despite the fantastic improvements of Internet Explorer 10 and Visual Studio 2012, etc.

So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. I also added console.() functions to Internet Explorer (that displays an alert() instead).

// Console extensions...
(function() {
    var __localhost = (document.location.host === "localhost"),
        __allow_examine = true;

    if (!console) {
        console = {};
    }

    console.__log = console.log;
    console.log = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__log === "function") {
                console.__log(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__info = console.info;
    console.info = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__info === "function") {
                console.__info(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__warn = console.warn;
    console.warn = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__warn === "function") {
                console.__warn(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__error = console.error;
    console.error = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__error === "function") {
                console.__error(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__group = console.group;
    console.group = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__group === "function") {
                console.__group(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert("group:\r\n" + msg + "{");
            }
        }
    };

    console.__groupEnd = console.groupEnd;
    console.groupEnd = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__groupEnd === "function") {
                console.__groupEnd(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg + "\r\n}");
            }
        }
    };

    /// <summary>
    /// Clever way to leave hundreds of debug output messages in the code,
    /// but not see _everything_ when you only want to see _some_ of the
    /// debugging messages.
    /// </summary>
    /// <remarks>
    /// To enable __examine_() statements for sections/groups of code, type the
    /// following in your browser's console:
    ///       top.__examine_ABC = true;
    /// This will enable only the console.examine("ABC", ... ) statements
    /// in the code.
    /// </remarks>
    console.examine = function() {
        if (!__allow_examine) {
            return;
        }
        if (arguments.length > 0) {
            var obj = top["__examine_" + arguments[0]];
            if (obj && obj === true) {
                console.log(arguments.splice(0, 1));
            }
        }
    };
})();

Example use:

    console.log("hello");

Chrome/Firefox:

    prints hello in the console window.

Internet Explorer:

    displays an alert with 'hello'.

For those who look closely at the code, you'll discover the console.examine() function. I created this years ago so that I can leave debug code in certain areas around the product to help troubleshoot QA/customer issues. For instance, I would leave the following line in some released code:

    function doSomething(arg1) {
        // ...
        console.examine("someLabel", arg1);
        // ...
    }

And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'):

    top.__examine_someLabel = true;

Then, I will see all of the logged console.examine() statements. It's been a fantastic help many times over.

Text not wrapping inside a div element

Might benefit you to be aware of another option, word-wrap: break-word;

The difference here is that words that can completely fit on 1 line will do that, vs. being forced to break simply because there is no more real estate on the line the word starts on.

See the fiddle for an illustration http://jsfiddle.net/Jqkcp/

How to replace blank (null ) values with 0 for all records?

without 'where's and 'if's ...

Update Table Set MyField = Nz(MyField,0)

Changing WPF title bar background color

You can also create a borderless window, and make the borders and title bar yourself

Problems when trying to load a package in R due to rJava

For reading/writing excel files, you can use :

  • readxl package for reading and writexl package for writing
  • openxlsx package for reading and writing

With xlsx and XLConnect (which use rjava) you will face memory errors if you have large files

List of remotes for a Git repository?

FWIW, I had exactly the same question, but I could not find the answer here. It's probably not portable, but at least for gitolite, I can run the following to get what I want:

$ ssh [email protected] info
hello akim, this is gitolite 2.3-1 (Debian) running on git 1.7.10.4
the gitolite config gives you the following access:
     R   W     android
     R   W     bistro
     R   W     checkpn
...

Using LIKE in an Oracle IN clause

Yes, you can use this query (Instead of 'Specialist' and 'Developer', type any strings you want separated by comma and change employees table with your table)

SELECT * FROM employees em
    WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));

Why my query is better than the accepted answer: You don't need a CREATE TABLE permission to run it. This can be executed with just SELECT permissions.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I was getting the same error when I tried to do :

cordova build ios

except mine said ** ARCHIVE FAILED ** rather than ** BUILD FAILED **.

I fixed it by opening the projectName.xcodeproj file in Xcode and then adjusting these 2 settings :

  1. In Targets > General > Signing ensure you have selected a Team

enter image description here

  1. In Targets > Build Settings > (search for "bitcode") set Enable Bitcode to "Yes"

enter image description here

Then I quit out of Xcode and reran cordova build ios and it worked.

Send Outlook Email Via Python?

This was one I tried using Win32:

import win32com.client as win32
import psutil
import os
import subprocess
import sys

# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification():


    outlook = win32.Dispatch('outlook.application')
    olFormatHTML = 2
    olFormatPlain = 1
    olFormatRichText = 3
    olFormatUnspecified = 0
    olMailItem = 0x0

    newMail = outlook.CreateItem(olMailItem)
    newMail.Subject = sys.argv[1]
    #newMail.Subject = "check"
    newMail.BodyFormat = olFormatHTML    #or olFormatRichText or olFormatPlain
    #newMail.HTMLBody = "test"
    newMail.HTMLBody = sys.argv[2]
    newMail.To = "[email protected]"
    attachment1 = sys.argv[3]
    attachment2 = sys.argv[4]
    newMail.Attachments.Add(attachment1)
    newMail.Attachments.Add(attachment2)

    newMail.display()
    # or just use this instead of .display() if you want to send immediately
    newMail.Send()





# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
def open_outlook():
    try:
        subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
        os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
    except:
        print("Outlook didn't open successfully")     
#

# Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
    p = psutil.Process(item)
    if p.name() == "OUTLOOK.EXE":
        flag = 1
        break
    else:
        flag = 0

if (flag == 1):
    send_notification()
else:
    open_outlook()
    send_notification()

Possible reasons for timeout when trying to access EC2 instance

I had the same problem and I solved it by adding a rule to the security Groups

Inbound SSH 0.0.0.0/0

Or you can add your IP address only

How to read file contents into a variable in a batch file?

Read file contents into a variable:

for /f "delims=" %%x in (version.txt) do set Build=%%x

or

set /p Build=<version.txt

Both will act the same with only a single line in the file, for more lines the for variant will put the last line into the variable, while set /p will use the first.

Using the variable – just like any other environment variable – it is one, after all:

%Build%

So to check for existence:

if exist \\fileserver\myapp\releasedocs\%Build%.doc ...

Although it may well be that no UNC paths are allowed there. Can't test this right now but keep this in mind.

SQL: How to perform string does not equal

Try the following query

select * from table
where NOT (tester = 'username')

How do I get out of 'screen' without typing 'exit'?

In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.

Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".

Convert SVG image to PNG with PHP

I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.

ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.

Command to collapse all sections of code?

In Visual Studio 2017, It seems that this behavior is turned off by default. It can be enabled under Tools > Options > Text Editors > C# > Advanced > Outlining > "Collapse #regions when collapsing to definitions"

Java 8 Lambda function that throws exception?

Sneaky throw idiom enables bypassing CheckedException of Lambda expression. Wrapping a CheckedException in a RuntimeException is not good for strict error handling.

It can be used as a Consumer function used in a Java collection.

Here is a simple and improved version of jib's answer.

import static Throwing.rethrow;

@Test
public void testRethrow() {
    thrown.expect(IOException.class);
    thrown.expectMessage("i=3");

    Arrays.asList(1, 2, 3).forEach(rethrow(e -> {
        int i = e.intValue();
        if (i == 3) {
            throw new IOException("i=" + i);
        }
    }));
}

This just wrapps the lambda in a rethrow. It makes CheckedException rethrow any Exception that was thrown in your lambda.

public final class Throwing {
    private Throwing() {}

    @Nonnull
    public static <T> Consumer<T> rethrow(@Nonnull final ThrowingConsumer<T> consumer) {
        return consumer;
    }

    /**
     * The compiler sees the signature with the throws T inferred to a RuntimeException type, so it
     * allows the unchecked exception to propagate.
     * 
     * http://www.baeldung.com/java-sneaky-throws
     */
    @SuppressWarnings("unchecked")
    @Nonnull
    public static <E extends Throwable> void sneakyThrow(@Nonnull Throwable ex) throws E {
        throw (E) ex;
    }

}

Find a complete code and unit tests here.

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

When is a CDATA section necessary within a script tag?

CDATA is necessary in any XML dialect, because text within an XML node is treated as a child element before being evaluated as JavaScript. This is also the reason why JSLint complains about the < character in regexes.

References

How to find which version of TensorFlow is installed in my system?

If you're using anaconda distribution of Python,

$ conda list | grep tensorflow
tensorflow    1.0.0       py35_0    conda-forge

To check it using Jupyter Notebook (IPython Notebook)

In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'

Replace Multiple String Elements in C#

Quicker - no. More effective - yes, if you will use the StringBuilder class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.

If you expect this method to be actively called on multiple Strings of significant length, it might be better to "migrate" its implementation onto the StringBuilder class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.

public static class StringExtention
{
    public static string clean(this string s)
    {
        StringBuilder sb = new StringBuilder (s);

        sb.Replace("&", "and");
        sb.Replace(",", "");
        sb.Replace("  ", " ");
        sb.Replace(" ", "-");
        sb.Replace("'", "");
        sb.Replace(".", "");
        sb.Replace("eacute;", "é");

        return sb.ToString().ToLower();
    }
}

UPDATE with CASE and IN - Oracle

There is another workaround you can use to update using a join. This example below assumes you want to de-normalize a table by including a lookup value (in this case storing a users name in the table). The update includes a join to find the name and the output is evaluated in a CASE statement that supports the name being found or not found. The key to making this work is ensuring all the columns coming out of the join have unique names. In the sample code, notice how b.user_name conflicts with the a.user_name column and must be aliased with the unique name "user_user_name".

UPDATE
(
    SELECT a.user_id, a.user_name, b.user_name as user_user_name
    FROM some_table a
    LEFT OUTER JOIN user_table b ON a.user_id = b.user_id
    WHERE a.user_id IS NOT NULL
)
SET user_name = CASE
    WHEN user_user_name IS NOT NULL THEN user_user_name
    ELSE 'UNKNOWN'
    END;   

Express.js: how to get remote client address

Particularly for node, the documentation for the http server component, under event connection says:

[Triggered] when a new TCP stream is established. [The] socket is an object of type net.Socket. Usually users will not want to access this event. In particular, the socket will not emit readable events because of how the protocol parser attaches to the socket. The socket can also be accessed at request.connection.

So, that means request.connection is a socket and according to the documentation there is indeed a socket.remoteAddress attribute which according to the documentation is:

The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.

Under express, the request object is also an instance of the Node http request object, so this approach should still work.

However, under Express.js the request already has two attributes: req.ip and req.ips

req.ip

Return the remote address, or when "trust proxy" is enabled - the upstream address.

req.ips

When "trust proxy" is true, parse the "X-Forwarded-For" ip address list and return an array, otherwise an empty array is returned. For example if the value were "client, proxy1, proxy2" you would receive the array ["client", "proxy1", "proxy2"] where "proxy2" is the furthest down-stream.

It may be worth mentioning that, according to my understanding, the Express req.ip is a better approach than req.connection.remoteAddress, since req.ip contains the actual client ip (provided that trusted proxy is enabled in express), whereas the other may contain the proxy's IP address (if there is one).

That is the reason why the currently accepted answer suggests:

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

The req.headers['x-forwarded-for'] will be the equivalent of express req.ip.

Get first word of string

One of the simplest ways to do this is like this

_x000D_
_x000D_
var totalWords = "my name is rahul.";_x000D_
var firstWord = totalWords.replace(/ .*/, '');_x000D_
alert(firstWord);_x000D_
console.log(firstWord);
_x000D_
_x000D_
_x000D_

how to measure running time of algorithms in python

For small algorithms you can use the module timeit from python documentation:

def test():
    "Stupid test function"
    L = []
    for i in range(100):
        L.append(i)

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

Less accurately but still valid you can use module time like this:

from time import time
t0 = time()
call_mifuntion_vers_1()
t1 = time()
call_mifunction_vers_2()
t2 = time()

print 'function vers1 takes %f' %(t1-t0)
print 'function vers2 takes %f' %(t2-t1)

Multiple github accounts on the same computer?

I use shell scripts to switch me to whatever account I want to be "active". Essentially you start from a fresh start, get one account configured properly and working, then move the these files to a name with the proper prefix. From then on you can use the command "github", or "gitxyz" to switch:

# my github script
cd ~/.ssh

if [ -f git_dhoerl -a -f git_dhoerl.pub -a -f config_dhoerl ]
then
    ; 
else 
    echo "Error: missing new files"
    exit 1
fi 

# Save a copy in /tmp, just in case
cp id_rsa /tmp
cp id_rsa.pub /tmp
cp config /tmp
echo "Saved old files in /tmp, just in case"

rm id_rsa
rm id_rsa.pub
rm config
echo "Removed current links/files"

ln git_dhoerl id_rsa
ln git_dhoerl.pub id_rsa.pub
ln config_dhoerl config

git config --global user.email "dhoerl@<company>.com"
git config --global github.user "dhoerl"        
git config --global github.token "whatever_it_is"

ssh-add -D

I've had great luck with this. I also created a run script in Xcode (for you Mac users) so it would not build my project unless I had the proper setting (since its using git):

Run Script placed after Dependencies (using /bin/ksh as the shell):

if [ "$(git config --global --get user.email)" != "dhoerl@<company>.com" ]
then
    exit 1
fi

EDIT: added tests for new files existence and copying old files to /tmp to address comment by @naomik below.

How to check if a list is empty in Python?

I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:

if len(my_list) == 0:
    print "my_list is empty"

How to execute 16-bit installer on 64-bit Win7?

It took me months of googling to find a solution for this issue. You don't need to install a virtual environment running a 32-bit version of Windows to run a program with a 16-bit installer on 64-bit Windows. If the program itself is 32-bit, and just the installer is 16-bit, here's your answer.

There are ways to modify a 16-bit installation program to make it 32-bit so it will install on 64-bit Windows 7. I found the solution on this site:

http://www.reactos.org/forum/viewtopic.php?f=22&t=10988

In my case, the installation program was InstallShield 5.X. The issue was that the setup.exe program used by InstallShield 5.X is 16-bit. First I extracted the installation program contents (changed the extension from .exe to .zip, opened it and extracted). I then replaced the original 16-bit setup.exe, located in the disk1 folder, with InstallShield's 32-bit version of setup.exe (download this file from the site referenced in the above link). Then I just ran the new 32-bit setup.exe in disk1 to start the installation and my program installed and runs perfectly on 64-bit Windows.

You can also repackage this modified installation, so it can be distributed as an installation program, using a free program like Inno Setup 5.

jQuery .val() vs .attr("value")

There is a big difference between an objects properties and an objects attributes

See this questions (and its answers) for some of the differences: .prop() vs .attr()

The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.

Comparing mongoose _id and strings

converting object id to string(using toString() method) will do the job.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

I had a similar problem when posting to the WebAPI endpoint. By turning the CustomErrors=Off, i was able to see the actual error which is one of the dlls was missing.

How do I create a right click context menu in Java Swing?

There's a section on Bringing Up a Popup Menu in the How to Use Menus article of The Java Tutorials which explains how to use the JPopupMenu class.

The example code in the tutorial shows how to add MouseListeners to the components which should display a pop-up menu, and displays the menu accordingly.

(The method you describe is fairly similar to the way the tutorial presents the way to show a pop-up menu on a component.)

Hard reset of a single file

You can use the following command:

git checkout filename

If you have a branch with the same file name you have to use this command:

git checkout -- filename

python NameError: name 'file' is not defined

To solve this error, it is enough to add from google.colab import files in your code!

How can I call a function using a function pointer?

Calling a function through a function pointer

float add(int, float), result;

int main()
{
    float (*fp)(int, float);
    float result;
    fp = add;
    result = add(5, 10.9);    // Normal calling
    printf("%f\n\n", result);

    result = (*fp)(5, 10.9);  // Calling via a function pointer
    printf("%f\n\n", result);

    result = (fp)(5, 10.9);   // Calling via function pointer. The
                              // indirection operator can be omitted

    printf("%f", result);
    getch();
}

float add(int a, float b)
{
    return a+b;
}

>

Output

15.90000
15.90000
15.90000

How to move (and overwrite) all files from one directory to another?

For moving and overwriting files, it doesn't look like there is the -R option (when in doubt check your options by typing [your_cmd] --help. Also, this answer depends on how you want to move your file. Move all files, files & directories, replace files at destination, etc.

When you type in mv --help it returns the description of all options.

For mv, the syntax is mv [option] [file_source] [file_destination]

To move simple files: mv image.jpg folder/image.jpg

To move as folder into destination mv folder home/folder

To move all files in source to destination mv folder/* home/folder/

Use -v if you want to see what is being done: mv -v

Use -i to prompt before overwriting: mv -i

Use -u to update files in destination. It will only move source files newer than the file in the destination, and when it doesn't exist yet: mv -u

Tie options together like mv -viu, etc.

How to copy text programmatically in my Android app?

public void onClick (View v) 
{
    switch (v.getId())
    {
        case R.id.ButtonCopy:
            copyToClipBoard();
            break;
        case R.id.ButtonPaste:
            pasteFromClipBoard();
            break;
        default:
            Log.d(TAG, "OnClick: Unknown View Received!");
            break;
    }
}

// Copy EditCopy text to the ClipBoard
private void copyToClipBoard() 
{
    ClipboardManager clipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipMan.setPrimaryClip(editCopy.getText());
}

you can try this..

What's the best way to limit text length of EditText in Android

Due to goto10's observation, I put together the following code to protected against loosing other filters with setting the max length:

/**
 * This sets the maximum length in characters of an EditText view. Since the
 * max length must be done with a filter, this method gets the current
 * filters. If there is already a length filter in the view, it will replace
 * it, otherwise, it will add the max length filter preserving the other
 * 
 * @param view
 * @param length
 */
public static void setMaxLength(EditText view, int length) {
    InputFilter curFilters[];
    InputFilter.LengthFilter lengthFilter;
    int idx;

    lengthFilter = new InputFilter.LengthFilter(length);

    curFilters = view.getFilters();
    if (curFilters != null) {
        for (idx = 0; idx < curFilters.length; idx++) {
            if (curFilters[idx] instanceof InputFilter.LengthFilter) {
                curFilters[idx] = lengthFilter;
                return;
            }
        }

        // since the length filter was not part of the list, but
        // there are filters, then add the length filter
        InputFilter newFilters[] = new InputFilter[curFilters.length + 1];
        System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length);
        newFilters[curFilters.length] = lengthFilter;
        view.setFilters(newFilters);
    } else {
        view.setFilters(new InputFilter[] { lengthFilter });
    }
}

Match the path of a URL, minus the filename extension

http:[\/]{2}.+?[.][^\/]+(.+)[.].+

let's see, what it done:

http:[\/]{2}.+?[.][^\/] - non-capture group for http://php.net

(.+)[.] - capture part until last dot occur: /manual/en/function.preg-match

[.].+ - matching extension of file like this: .php

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

Escaping double quotes in JavaScript onClick event handler

While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:

<script type="text/javascript">
function parse(a, b, c) {
    alert(c);
  }

</script>

<a href="#x" onclick="parse('#', false, 'xyc&quot;foo');return false;">Test</a>

The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..

How to show first commit by 'git log'?

git log $(git log --pretty=format:%H|tail -1)

Convert a float64 to an int in Go

If its simply from float64 to int, this should work

package main

import (
    "fmt"
)

func main() {
    nf := []float64{-1.9999, -2.0001, -2.0, 0, 1.9999, 2.0001, 2.0}

    //round
    fmt.Printf("Round : ")
    for _, f := range nf {
        fmt.Printf("%d ", round(f))
    }
    fmt.Printf("\n")

    //rounddown ie. math.floor
    fmt.Printf("RoundD: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundD(f))
    }
    fmt.Printf("\n")

    //roundup ie. math.ceil
    fmt.Printf("RoundU: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundU(f)) 
    }
    fmt.Printf("\n")

}

func roundU(val float64) int {
    if val > 0 { return int(val+1.0) }
    return int(val)
}

func roundD(val float64) int {
    if val < 0 { return int(val-1.0) }
    return int(val)
}

func round(val float64) int {
    if val < 0 { return int(val-0.5) }
    return int(val+0.5)
}

Outputs:

Round : -2 -2 -2 0 2 2 2 
RoundD: -2 -3 -3 0 1 2 2 
RoundU: -1 -2 -2 0 2 3 3 

Here's the code in the playground - https://play.golang.org/p/HmFfM6Grqh

linq where list contains any in list

You can use a Contains query for this:

var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

-- EDIT --

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

Check if a key is down?

Other people have asked this kind of question before (though I don't see any obvious dupes here right now).

I think the answer is that the keydown event (and its twin keyup) are all the info you get. Repeating is wired pretty firmly into the operating system, and an application program doesn't get much of an opportunity to query the BIOS for the actual state of the key.

What you can do, and perhaps have to if you need to get this working, is to programmatically de-bounce the key. Essentially, you can evaluate keydown and keyup yourself but ignore a keyupevent if it takes place too quickly after the last keydown... or essentially, you should delay your response to keyup long enough to be sure there's not another keydown event following with something like 0.25 seconds of the keyup.

This would involve using a timer activity, and recording the millisecond times for previous events. I can't say it's a very appealing solution, but...

What is the difference between const and readonly in C#?

const: Can't be changed anywhere.

readonly: This value can only be changed in the constructor. Can't be changed in normal functions.

Using python map and other functional tools

Here's the solution you're looking for:

>>> foos = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> bars = [1, 2, 3]
>>> [(x, bars) for x in foos]
[(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [
1, 2, 3])]

I'd recommend using a list comprehension (the [(x, bars) for x in foos] part) over using map as it avoids the overhead of a function call on every iteration (which can be very significant). If you're just going to use it in a for loop, you'll get better speeds by using a generator comprehension:

>>> y = ((x, bars) for x in foos)
>>> for z in y:
...     print z
...
(1.0, [1, 2, 3])
(2.0, [1, 2, 3])
(3.0, [1, 2, 3])
(4.0, [1, 2, 3])
(5.0, [1, 2, 3])

The difference is that the generator comprehension is lazily loaded.

UPDATE In response to this comment:

Of course you know, that you don't copy bars, all entries are the same bars list. So if you modify any one of them (including original bars), you modify all of them.

I suppose this is a valid point. There are two solutions to this that I can think of. The most efficient is probably something like this:

tbars = tuple(bars)
[(x, tbars) for x in foos]

Since tuples are immutable, this will prevent bars from being modified through the results of this list comprehension (or generator comprehension if you go that route). If you really need to modify each and every one of the results, you can do this:

from copy import copy
[(x, copy(bars)) for x in foos]

However, this can be a bit expensive both in terms of memory usage and in speed, so I'd recommend against it unless you really need to add to each one of them.

What is the minimum I have to do to create an RPM file?

If you are familiar with Maven there also rpm-maven-plugin which simplifies making RPMs: you have to write only pom.xml which will be then used to build RPM. RPM build environment is created implicitly by the plugin.

reactjs - how to set inline style of backgroundcolor?

If you want more than one style this is the correct full answer. This is div with class and style:

<div className="class-example" style={{width: '300px', height: '150px'}}></div>

How should I escape commas and speech marks in CSV files so they work in Excel?

We eventually found the answer to this.

Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...

Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."

... fixed the problem. Hope this helps someone!

How can I replace text with CSS?

The simplest way I found is by making the element font-size: 0px, then overwrite it with any font size when creating :after pseudo. Example below:

.pvw-title { 
    font-size:0px;
}

.pvw-title:after {
        content: "Hello";
        font-size:15px !important;
}

aspx page to redirect to a new page

In a special case within ASP.NET If you want to know if the page is redirected by a specified .aspx page and not another one, just put the information in a session name and take necessary action in the receiving Page_Load Event.

How to map atan2() to degrees 0-360

A formula to have the range of values from 0 to 360 degrees.

f(x,y)=180-90*(1+sign(x))* (1-sign(y^2))-45*(2+sign(x))*sign(y)

     -(180/pi())*sign(x*y)*atan((abs(x)-abs(y))/(abs(x)+abs(y)))

Is there a Newline constant defined in Java like Environment.Newline in C#?

As of Java 7:

System.lineSeparator()

Java API : System.lineSeparator

Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator. On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".

SQL Error: ORA-00936: missing expression

Your statement is calling SELECT and WHERE but does not specify which TABLE or record set you would like to SELECT FROM.

SELECT DISTINCT Description, Date as treatmentDate
FROM (TABLE_NAME or SUBQUERY)<br> --This is missing from your query.
WHERE doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I
AND P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');

Export tables to an excel spreadsheet in same directory

Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.

How to update core-js to core-js@3 dependency?

You update core-js with the following command:

npm install --save core-js@^3

If you read the React Docs you will find that the command is derived from when you need to upgrade React itself.

How to grant permission to users for a directory using command line in Windows?

Corrupt Permissions: Regaining access to a folder and its sub-objects

Although most of the answers posted in reply to the question have some merit, IMHO none of them give a complete solution. The following (might be) a perfect solution for Windows 7 if you are locked-out of a folder by corrupted permission settings:

icacls "c:\folder" /remove:d /grant:r Everyone:(OI)(CI)F /T  

For Windows 10 the user/SID must be specified after the /remove:d option:

icacls "c:\folder" /remove:d Everyone /grant:r Everyone:(OI)(CI)F /T  

.
Notes:

  1. The command is applied to the specified directory.

  2. Specifying the user "Everyone" sets the widest possible permission, as it includes every possible user.

  3. The option "/remove:d" deletes any explicit DENY settings that may exist, as those override explicit ALLOW settings: a necessary preliminary to creating a new ALLOW setting. This is only a precaution, as there is often no DENY setting present, but better safe than sorry.

  4. The option "/grant" creates a new ALLOW setting, an explicit permission that replaces (":r") any and all explicit ALLOW settings that may exist.

  5. The "F" parameter (i.e. the permission created) makes this a grant of FULL control.

  6. The "/T" parameter adds recursion, applying these changes to all current sub-objects in the specified directory (i.e. files and subfolders), as well as the folder itself.

  7. The "(OI)" and "(CI)" parameters also add recursion, applying these changes to sub-objects created subsequently.
    .

ADDENDUM (2019/02/10) -

The Windows 10 command line above was kindly suggested to me today, so here it is. I haven't got Windows 10 to test it, but please try it out if you have (and then will you please post a comment below).

The change only concerns removing the DENY setting as a first step. There might well not be any DENY setting present, so that option might make no difference. My understanding is, on Windows 7, that you don't need to specify a user after /remove:d but I might be wrong about that!

.

ADDENDUM (2019/11/21) -

User astark recommends replacing Everyone with the term *S-1-1-0 in order for the command to be language independent. I only have an English install of Windows, so I can't test this proposal, but it seems reasonable.

How to calculate UILabel width based on text length?

In iOS8 sizeWithFont has been deprecated, please refer to

CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];

You can add all the attributes you want in sizeWithAttributes. Other attributes you can set:

- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName

and so on. But probably you won't need the others

append multiple values for one key in a dictionary

Here is an alternative way of doing this using the not in operator:

# define an empty dict
years_dict = dict()

for line in list:
    # here define what key is, for example,
    key = line[0]
    # check if key is already present in dict
    if key not in years_dict:
        years_dict[key] = []
    # append some value 
    years_dict[key].append(some.value)

Multiple FROMs - what it means

The first answer is too complex, historic, and uninformative for my tastes.


It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,

  • Free you from having to manually remove what you don't want, by forcing you to whitelist what you do want,
  • Free resources that would otherwise be taken up because of Docker's implementation.

Let's start with the first. Very often with something like Debian you'll see.

RUN apt-get update \ 
  && apt-get dist-upgrade \
  && apt-get install <whatever> \
  && apt-get clean

We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,

RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;

It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree for an example of that).

By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean), and you would otherwise have lots of un-needed files in your final image.

See also

How to sort a list/tuple of lists/tuples by the element at a given index?

sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  # sorts in place

Shell script to set environment variables

Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.

Meanwhile you have to use double quotes not single quote to expand variables:

export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"

Semicolons at the end of a single command are also unnecessary.

So far:

#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

For su you can run it with:

su -c 'sh /path/to/script.sh'

Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using . or source from the interactive shell. It could have been a standalone scipt, or it could have been source'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.

How to check for an empty struct?

Just a quick addition, because I tackled the same issue today:

With Go 1.13 it is possible to use the new isZero() method:

if reflect.ValueOf(session).IsZero() {
     // do stuff...
}

I didn't test this regarding performance, but I guess that this should be faster, than comparing via reflect.DeepEqual().

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

How to normalize a NumPy array to within a certain range?

I tried following this, and got the error

TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'l') according to the casting rule ''same_kind''

The numpy array I was trying to normalize was an integer array. It seems they deprecated type casting in versions > 1.10, and you have to use numpy.true_divide() to resolve that.

arr = np.array(img)
arr = np.true_divide(arr,[255.0],out=None)

img was an PIL.Image object.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

My first post... UDF I managed quickly to compile. Usage: Select 3D range as normal and enclose is into quotation marks like below...

=CountIf3D("'StartSheet:EndSheet'!G16:G878";"Criteria")

Advisably sheets to be adjacent to avoid unanticipated results.

Public Function CountIf3D(SheetstoCount As String, CriteriaToUse As Variant)

     Dim sStarSheet As String, sEndSheet As String, sAddress As String
     Dim lColonPos As Long, lExclaPos As Long, cnt As Long

    lColonPos = InStr(SheetstoCount, ":") 'Finding ':' separating sheets
    lExclaPos = InStr(SheetstoCount, "!") 'Finding '!' separating address from the sheets

    sStarSheet = Mid(SheetstoCount, 2, lColonPos - 2) 'Getting first sheet's name
    sEndSheet = Mid(SheetstoCount, lColonPos + 1, lExclaPos - lColonPos - 2) 'Getting last sheet's name

    sAddress = Mid(SheetstoCount, lExclaPos + 1, Len(SheetstoCount) - lExclaPos) 'Getting address

        cnt = 0
   For i = Sheets(sStarSheet).Index To Sheets(sEndSheet).Index
        cnt = cnt + Application.CountIf(Sheets(i).Range(sAddress), CriteriaToUse)
   Next

   CountIf3D = cnt

End Function

How can I get the username of the logged-in user in Django?

You can use the request object to find the logged in user

def my_view(request):
    username = None
    if request.user.is_authenticated():
        username = request.user.username

According to https://docs.djangoproject.com/en/2.0/releases/1.10/

In version Django 2.0 the syntax has changed to

request.user.is_authenticated

How do I get extra data from intent on Android?

First, get the intent which has started your activity using the getIntent() method:

Intent intent = getIntent();

If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");

Full width image with fixed height

you can use pixels or percent.

<div id="container">
<img id="image" src="...">
</div>

css

#image
{
width:100%;
height:
}

Batch file include external file for variables

If the external configuration file is also valid batch file, you can just use:

call externalconfig.bat

inside your script. Try creating following a.bat:

@echo off
call b.bat
echo %MYVAR%

and b.bat:

set MYVAR=test

Running a.bat should generate output:

test

What's the difference between 'int?' and 'int' in C#?

Int cannot accept null but if developer are using int? then you store null in int like int i = null; // not accept int? i = null; // its working mostly use for pagination in MVC Pagelist

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

How to get logged-in user's name in Access vba?

Try this:

Function UserNameWindows() As String
     UserName = Environ("USERNAME")
End Function

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

TypeError: $(...).on is not a function

The problem may be if you are using older version of jQuery. Because older versions of jQuery have 'live' method instead of 'on'

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Event on a disabled input

suggestion here looks like a good candidate for this question as well

Performing click event on a disabled element? Javascript jQuery

jQuery('input#submit').click(function(e) {
    if ( something ) {        
        return false;
    } 
});

How to create an android app using HTML 5

you can use webview in android that will use chrome browser Or you can try Phonegap or sencha Touch

How to tell if node.js is installed or not

Please try this command node --version or node -v, either of which should return something like v4.4.5.

Reading e-mails from Outlook with Python through MAPI

I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content

How do I mock an open used in a with statement (using the Mock framework in Python)?

If you don't need any file further, you can decorate the test method:

@patch('builtins.open', mock_open(read_data="data"))
def test_testme():
    result = testeme()
    assert result == "data"

What does the term "Tuple" Mean in Relational Databases?

A tuple is used to define a slice of data from a cube; it is composed of an ordered collection of one member from one or more dimensions. A tuple is used to identify specific sections of multidimensional data from a cube; a tuple composed of one member from each dimension in a cube completely describes a cell value.

Open an html page in default browser with VBA?

You can even say:

FollowHyperlink "www.google.com"

If you get Automation Error then use http://:

ThisWorkbook.FollowHyperlink("http://www.google.com")

default select option as blank

just use "..option hidden selected.." as default option

Select the top N values by group

If there were a tie at the fourth position for mtcars$mpg then this should return all the ties:

top_mpg <- mtcars[ mtcars$mpg >= mtcars$mpg[order(mtcars$mpg, decreasing=TRUE)][4] , ]

> top_mpg
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2

Since there is a tie at the 3-4 position you can test it by changing 4 to a 3, and it still returns 4 items. This is logical indexing and you might need to add a clause that removes the NA's or wrap which() around the logical expression. It's not much more difficult to do this "by" cyl:

 Reduce(rbind,  by(mtcars, mtcars$cyl, 
        function(d) d[ d$mpg >= d$mpg[order(d$mpg, decreasing=TRUE)][4] , ]) )
#-------------
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128          32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic       30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla    33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Lotus Europa      30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Ferrari Dino      19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Merc 450SE        16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL        17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Pontiac Firebird  19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2

Incorporating my suggestion to @Ista:

Reduce(rbind,  by(mtcars, mtcars$cyl, function(d) d[ d$mpg <= sort( d$mpg )[3] , ]) )

Close iOS Keyboard by touching anywhere using Swift

Here's a succinct way of doing it:

let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
endEditingTapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(endEditingTapGesture)

Password masking console application

For this you should use the System.Security.SecureString

public SecureString GetPassword()
{
    var pwd = new SecureString();
    while (true)
    {
        ConsoleKeyInfo i = Console.ReadKey(true);
        if (i.Key == ConsoleKey.Enter)
        {
            break;
        }
        else if (i.Key == ConsoleKey.Backspace)
        {
            if (pwd.Length > 0)
            {
                pwd.RemoveAt(pwd.Length - 1);
                Console.Write("\b \b");
            }
        }
        else if (i.KeyChar != '\u0000' ) // KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc
        {
            pwd.AppendChar(i.KeyChar);
            Console.Write("*");
        }
    }
    return pwd;
}

img src SVG changing the styles with CSS

Simple..

You can use this code:

<svg class="logo">
  <use xlink:href="../../static/icons/logo.svg#Capa_1"></use>
</svg>

First specify the path of svg and then write it's ID, In this case "Capa_1". You can get the ID of svg by opening it in any editor.

In css:

.logo {
  fill: red;
}

Google Maps shows "For development purposes only"

Google Maps is no longer free. You have to associate a credit card so that you can get billed if your site has requests that exceed the $200 credit they give you monthly for free. That is why you get the watermarked maps.

For more information, see: https://cloud.google.com/maps-platform/pricing/

Update: A common problem with the new billing system is that you now have to activate each API separately. They all have different pricing (some are even free), so Google makes a point of having you enable them individually for your domain. I was never a heavy user of Google Maps, but I get the feeling that there are many more APIs now than there used to be.

So if you're still getting a restricted usage message after you've enabled billing, find out what API you need exactly for the features you want to offer, and check if it's enabled. The API settings are annoyingly hard to find.

  1. Go to this link: https://console.developers.google.com/apis/dashboard.
  2. Then you select your project in the dropdown.
  3. Go to library on the left pane.
  4. Browse the available APIs and enable the one you need.

Programmatically change the src of an img tag

You can use both jquery and javascript method: if you have two images for example:

<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">

1)Jquery Method->

$(".image2").attr("src","image1.jpg");

2)Javascript Method->

var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"

For this type of issue jquery is the simple one to use.

IEnumerable vs List - What to Use? How do they work?

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

enter image description here enter image description here

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

I found this question after seeing the 'more than one device' error, with 2 offline phones showing:

C:\Program Files (x86)\Android\android-sdk\android-tools>adb devices
List of devices attached
SH436WM01785    offline
SH436WM01785    offline
SH436WM01785    sideload

If you only have one device connected, run the following commands to get rid of the offline connections:

adb kill-server
adb devices

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

I think its a bug, please apply the workaround and then try again: http://support.microsoft.com/kb/281517.

Also, go into Advanced tab, and confirm if Target columns length is Varchar(max).

How to save a dictionary to a file?

I would suggest saving your data using the JSON format instead of pickle format as JSON's files are human-readable which makes your debugging easier since your data is small. JSON files are also used by other programs to read and write data. You can read more about it here

You'll need to install the JSON module, you can do so with pip:

pip install json


# To save the dictionary into a file:
json.dump( data, open( "myfile.json", 'w' ) )

This creates a json file with the name myfile.

# To read data from file:
data = json.load( open( "myfile.json" ) )

This reads and stores the myfile.json data in a data object.

Remove characters before character "."

public string RemoveCharactersBeforeDot(string s)
{
 string splitted=s.Split('.');
 return splitted[splitted.Length-1]
}

"multiple target patterns" Makefile error

I had it on the Makefile

MAPS+=reverse/db.901:550:2001.ip6.arpa 
lastserial:  ${MAPS}
    ./updateser ${MAPS}

It's because of the : in the file name. I solved this with

                      -------- notice
                     /    /
                    v    v
MAPS+=reverse/db.901\:550\:2001.ip6.arpa
lastserial:  ${MAPS}
    ./updateser ${MAPS}

How to run vi on docker container?

Inside container(in docker, not in VM), by default these are not installed. Even apt-get, wget will not work. My VM is running on Ubuntu 17.10. For me yum package manaager worked.

Yum is not part of debian or ubuntu. It is part of red-hat. But, it works in Ubuntu and it is installed by default like apt-get

Tu install vim, use this command

yum install -y vim-enhanced 

To uninstall vim :

yum uninstall -y vim-enhanced 

Similarly,

yum install -y wget 
yum install -y sudo 

-y is for assuming yes if prompted for any qustion asked after doing yum install packagename

jQuery - replace all instances of a character in a string

RegEx is the way to go in most cases.

In some cases, it may be faster to specify more elements or the specific element to perform the replace on:

$(document).ready(function () {
    $('.myclass').each(function () {
        $('img').each(function () {
            $(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
        })
    })
});

This does the replace once on each string, but it does it using a more specific selector.

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

Example:

File  f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());

will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

File sutest

#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.


I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.

A first stab at making it cross-platform could be...

#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}

sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.

How to add http:// if it doesn't exist in the URL

Scan the string for ://. If it does not have it, prepend http:// to the string... Everything else just use the string as is.

This will work unless you have a rubbish input string.

Remove Android App Title Bar

There are two options I'd like to present:

  1. Change the visibility of the SupportActionBar in JAVA code
  2. Choose another Style in your project's style.xml

1: Add getSupportActionBar().hide(); to your onCreate method.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);
}

2: Another option is to change the style of your Application. Check out the styles.xml in "app->res->values" and change

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

Where's the DateTime 'Z' format specifier?

Round tripping dates through strings has always been a pain...but the docs to indicate that the 'o' specifier is the one to use for round tripping which captures the UTC state. When parsed the result will usually have Kind == Utc if the original was UTC. I've found that the best thing to do is always normalize dates to either UTC or local prior to serializing then instruct the parser on which normalization you've chosen.

DateTime now = DateTime.Now;
DateTime utcNow = now.ToUniversalTime();

string nowStr = now.ToString( "o" );
string utcNowStr = utcNow.ToString( "o" );

now = DateTime.Parse( nowStr );
utcNow = DateTime.Parse( nowStr, null, DateTimeStyles.AdjustToUniversal );

Debug.Assert( now == utcNow );

When to favor ng-if vs. ng-show/ng-hide?

The answer is not simple:

It depends on the target machines (mobile vs desktop), it depends on the nature of your data, the browser, the OS, the hardware it runs on... you will need to benchmark if you really want to know.

It is mostly a memory vs computation problem ... as with most performance issues the difference can become significant with repeated elements (n) like lists, especially when nested (n x n, or worse) and also what kind of computations you run inside these elements:

  • ng-show: If those optional elements are often present (dense), like say 90% of the time, it may be faster to have them ready and only show/hide them, especially if their content is cheap (just plain text, nothing to compute or load). This consumes memory as it fills the DOM with hidden elements, but just show/hide something which already exists is likely to be a cheap operation for the browser.

  • ng-if: If on the contrary elements are likely not to be shown (sparse) just build them and destroy them in real time, especially if their content is expensive to get (computations/sorted/filtered, images, generated images). This is ideal for rare or 'on-demand' elements, it saves memory in terms of not filling the DOM but can cost a lot of computation (creating/destroying elements) and bandwidth (getting remote content). It also depends on how much you compute in the view (filtering/sorting) vs what you already have in the model (pre-sorted/pre-filtered data).

How Exactly Does @param Work - Java

@param won't affect the number. It's just for making javadocs.

More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

What is the native keyword in Java for?

  • native is a keyword in java, it indicates platform dependent.
  • native methods are acts as interface between Java(JNI) and other programming languages.

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

Python: list of lists

Lists are a mutable type - in order to create a copy (rather than just passing the same list around), you need to do so explicitly:

listoflists.append((list[:], list[0]))

However, list is already the name of a Python built-in - it'd be better not to use that name for your variable. Here's a version that doesn't use list as a variable name, and makes a copy:

listoflists = []
a_list = []
for i in range(0,10):
    a_list.append(i)
    if len(a_list)>3:
        a_list.remove(a_list[0])
        listoflists.append((list(a_list), a_list[0]))
print listoflists

Note that I demonstrated two different ways to make a copy of a list above: [:] and list().

The first, [:], is creating a slice (normally often used for getting just part of a list), which happens to contain the entire list, and thus is effectively a copy of the list.

The second, list(), is using the actual list type constructor to create a new list which has contents equal to the first list. (I didn't use it in the first example because you were overwriting that name in your code - which is a good example of why you don't want to do that!)

How to Customize a Progress Bar In Android

In case of complex ProgressBar like this,

enter image description here

use ClipDrawable.

NOTE : I've not used ProgressBar here in this example. I've achieved this using ClipDrawable by clipping image with Animation.

A Drawable that clips another Drawable based on this Drawable's current level value. You can control how much the child Drawable gets clipped in width and height based on the level, as well as a gravity to control where it is placed in its overall container. Most often used to implement things like progress bars, by increasing the drawable's level with setLevel().

NOTE : The drawable is clipped completely and not visible when the level is 0 and fully revealed when the level is 10,000.

I've used this two images to make this CustomProgressBar.

scall.png

scall.png

ballon_progress.png

ballon_progress.png

MainActivity.java

public class MainActivity extends ActionBarActivity {

private EditText etPercent;
private ClipDrawable mImageDrawable;

// a field in your class
private int mLevel = 0;
private int fromLevel = 0;
private int toLevel = 0;

public static final int MAX_LEVEL = 10000;
public static final int LEVEL_DIFF = 100;
public static final int DELAY = 30;

private Handler mUpHandler = new Handler();
private Runnable animateUpImage = new Runnable() {

    @Override
    public void run() {
        doTheUpAnimation(fromLevel, toLevel);
    }
};

private Handler mDownHandler = new Handler();
private Runnable animateDownImage = new Runnable() {

    @Override
    public void run() {
        doTheDownAnimation(fromLevel, toLevel);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etPercent = (EditText) findViewById(R.id.etPercent);

    ImageView img = (ImageView) findViewById(R.id.imageView1);
    mImageDrawable = (ClipDrawable) img.getDrawable();
    mImageDrawable.setLevel(0);
}

private void doTheUpAnimation(int fromLevel, int toLevel) {
    mLevel += LEVEL_DIFF;
    mImageDrawable.setLevel(mLevel);
    if (mLevel <= toLevel) {
        mUpHandler.postDelayed(animateUpImage, DELAY);
    } else {
        mUpHandler.removeCallbacks(animateUpImage);
        MainActivity.this.fromLevel = toLevel;
    }
}

private void doTheDownAnimation(int fromLevel, int toLevel) {
    mLevel -= LEVEL_DIFF;
    mImageDrawable.setLevel(mLevel);
    if (mLevel >= toLevel) {
        mDownHandler.postDelayed(animateDownImage, DELAY);
    } else {
        mDownHandler.removeCallbacks(animateDownImage);
        MainActivity.this.fromLevel = toLevel;
    }
}

public void onClickOk(View v) {
    int temp_level = ((Integer.parseInt(etPercent.getText().toString())) * MAX_LEVEL) / 100;

    if (toLevel == temp_level || temp_level > MAX_LEVEL) {
        return;
    }
    toLevel = (temp_level <= MAX_LEVEL) ? temp_level : toLevel;
    if (toLevel > fromLevel) {
        // cancel previous process first
        mDownHandler.removeCallbacks(animateDownImage);
        MainActivity.this.fromLevel = toLevel;

        mUpHandler.post(animateUpImage);
    } else {
        // cancel previous process first
        mUpHandler.removeCallbacks(animateUpImage);
        MainActivity.this.fromLevel = toLevel;

        mDownHandler.post(animateDownImage);
    }
}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/etPercent"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:inputType="number"
        android:maxLength="3" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ok"
        android:onClick="onClickOk" />

</LinearLayout>

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/scall" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/clip_source" />

</FrameLayout>

clip_source.xml

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
    android:clipOrientation="vertical"
    android:drawable="@drawable/ballon_progress"
    android:gravity="bottom" />

In case of complex HorizontalProgressBar just change cliporientation in clip_source.xml like this,

android:clipOrientation="horizontal"

You can download complete demo from here.

How do I load external fonts into an HTML document?

Microsoft have a proprietary CSS method of including embedded fonts (http://msdn.microsoft.com/en-us/library/ms533034(VS.85).aspx), but this probably shouldn't be recommended.

I've used sIFR before as this works great - it uses Javascript and Flash to dynamically replace normal text with some Flash containing the same text in the font you want (the font is embedded in a Flash file). This does not affect the markup around the text (it works by using a CSS class), you can still select the text, and if the user doesn't have Flash or has it disabled, it will degrade gracefully to the text in whatever font you specify in CSS (e.g. Arial).

How do you check "if not null" with Eloquent?

in laravel 5.4 this code Model::whereNotNull('column') was not working you need to add get() like this one Model::whereNotNull('column')->get(); this one works fine for me.

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

If I understand your issue this should work

&emsp—the em space; this should be a very wide space, typically as much as four real spaces. &ensp—the en space; this should be a somewhat wide space, roughly two regular spaces. &thinsp—this will be a narrow space, even more narrow than a regular space.

Sources: http://hea-www.harvard.edu/~fine/Tech/html-sentences.html

Curl to return http status code along with the response

The -i option is the one that you want:

curl -i http://localhost

-i, --include Include protocol headers in the output (H/F)

Alternatively you can use the verbose option:

curl -v http://localhost

-v, --verbose Make the operation more talkative

lvalue required as left operand of assignment error when using C++

When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.

You cannot use:

10 = 20;

since 10 does not evaluate to an lvalue.

You can use:

int i;
i = 20;

since i does evaluate to an lvalue.

You cannot use:

int i;
i + 1 = 20;

since i + 1 does not evaluate to an lvalue.

In your case, p + 1 does not evaluate to an lavalue. Hence, you cannot use

p + 1 = p;