Programs & Examples On #Nonlinear functions

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

Selected tab's color in Bottom Navigation View

1. Inside res create folder with name color (like drawable)

2. Right click on color folder. Select new-> color resource file-> create color.xml file (bnv_tab_item_foreground) (Figure 1: File Structure)

3. Copy and paste bnv_tab_item_foreground

<android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="0dp"
            android:layout_marginStart="0dp"
            app:itemBackground="@color/appcolor"//diffrent color
            app:itemIconTint="@color/bnv_tab_item_foreground" //inside folder 2 diff colors
            app:itemTextColor="@color/bnv_tab_item_foreground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation" />

bnv_tab_item_foreground:

 <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="true" android:color="@color/white" />
        <item android:color="@android:color/darker_gray"  />
    </selector>

Figure 1: File Structure:

Figure 1: File Structure

What is the meaning of the word logits in TensorFlow?

Summary

In context of deep learning the logits layer means the layer that feeds in to softmax (or other such normalization). The output of the softmax are the probabilities for the classification task and its input is logits layer. The logits layer typically produces values from -infinity to +infinity and the softmax layer transforms it to values from 0 to 1.

Historical Context

Where does this term comes from? In 1930s and 40s, several people were trying to adapt linear regression to the problem of predicting probabilities. However linear regression produces output from -infinity to +infinity while for probabilities our desired output is 0 to 1. One way to do this is by somehow mapping the probabilities 0 to 1 to -infinity to +infinity and then use linear regression as usual. One such mapping is cumulative normal distribution that was used by Chester Ittner Bliss in 1934 and he called this "probit" model, short for "probability unit". However this function is computationally expensive while lacking some of the desirable properties for multi-class classification. In 1944 Joseph Berkson used the function log(p/(1-p)) to do this mapping and called it logit, short for "logistic unit". The term logistic regression derived from this as well.

The Confusion

Unfortunately the term logits is abused in deep learning. From pure mathematical perspective logit is a function that performs above mapping. In deep learning people started calling the layer "logits layer" that feeds in to logit function. Then people started calling the output values of this layer "logit" creating the confusion with logit the function.

TensorFlow Code

Unfortunately TensorFlow code further adds in to confusion by names like tf.nn.softmax_cross_entropy_with_logits. What does logits mean here? It just means the input of the function is supposed to be the output of last neuron layer as described above. The _with_logits suffix is redundant, confusing and pointless. Functions should be named without regards to such very specific contexts because they are simply mathematical operations that can be performed on values derived from many other domains. In fact TensorFlow has another similar function sparse_softmax_cross_entropy where they fortunately forgot to add _with_logits suffix creating inconsistency and adding in to confusion. PyTorch on the other hand simply names its function without these kind of suffixes.

Reference

The Logit/Probit lecture slides is one of the best resource to understand logit. I have also updated Wikipedia article with some of above information.

What is the difference between "INNER JOIN" and "OUTER JOIN"?

In Simple Terms,

1.INNER JOIN OR EQUI JOIN : Returns the resultset that matches only the condition in both the tables.

2.OUTER JOIN : Returns the resultset of all the values from both the tables even if there is condition match or not.

3.LEFT JOIN : Returns the resultset of all the values from left table and only rows that match the condition in right table.

4.RIGHT JOIN : Returns the resultset of all the values from right table and only rows that match the condition in left table.

5.FULL JOIN : Full Join and Full outer Join are same.

Git: How to return from 'detached HEAD' state

You may have made some new commits in the detached HEAD state. I believe if you do as other answers advise:

git checkout master
# or
git checkout -

then you may lose your commits!! Instead, you may want to do this:

# you are currently in detached HEAD state
git checkout -b commits-from-detached-head

and then merge commits-from-detached-head into whatever branch you want, so you don't lose the commits.

Creating a Plot Window of a Particular Size

As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:

If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.

Calling multiple JavaScript functions on a button click

And of course you can never call the two functions at the same time. Not any one in the world except you are working on two processors simultaneously.

The best way is to call a JavaScript parent function and in that, specify all the sequence of function you want to call. For example,

function ShowDiv1() {
    document.getElementById("ReportDiv").style.display = 'block';
    return false;
}

function validateView()
{
    if (document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Category";
        document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").focus();
        return false;
    }
    if (document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Employee Name";
        document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").focus();
        return false;
    }
    ShowDiv1();
    return true;
}

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Use X-Requested-With: XMLHttpRequest with your request header. So the response header will not contain WWW-Authenticate:Basic.

beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', ("Basic "
                        .concat(btoa(key))));
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                },

Interfaces — What's the point?

I did a search for the word "composition" on this page and didn't see it once. This answer is very much in addition to the answers aforementioned.

One of the absolutely crucial reasons for using interfaces in an Object Oriented Project is that they allow you to favour composition over inheritance. By implementing interfaces you can decouple your implementations from the various algorithms you are applying to them.

This superb "Decorator Pattern" tutorial by Derek Banas (which - funnily enough - also uses pizza as an example) is a worthwhile illustration:

https://www.youtube.com/watch?v=j40kRwSm4VE

Deleting specific rows from DataTable

<asp:GridView ID="grd_item_list" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-bordered table-hover" OnRowCommand="grd_item_list_RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="No">
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 %>
            </ItemTemplate>
        </asp:TemplateField>            
        <asp:TemplateField HeaderText="Actions">
            <ItemTemplate>                    
                <asp:Button ID="remove_itemIndex" OnClientClick="if(confirm('Are You Sure to delete?')==true){ return true;} else{ return false;}" runat="server" class="btn btn-primary" Text="REMOVE" CommandName="REMOVE_ITEM" CommandArgument='<%# Container.DataItemIndex+1 %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

 **This is the row binding event**

protected void grd_item_list_RowCommand(object sender, GridViewCommandEventArgs e) {

    item_list_bind_structure();

    if (ViewState["item_list"] != null)
        dt = (DataTable)ViewState["item_list"];


    if (e.CommandName == "REMOVE_ITEM") {
        var RowNum = Convert.ToInt32(e.CommandArgument.ToString()) - 1;

        DataRow dr = dt.Rows[RowNum];
        dr.Delete();

    }

    grd_item_list.DataSource = dt;
    grd_item_list.DataBind();
}

Xml serialization - Hide null values

It exists a property called XmlElementAttribute.IsNullable

If the IsNullable property is set to true, the xsi:nil attribute is generated for class members that have been set to a null reference.

The following example shows a field with the XmlElementAttribute applied to it, and the IsNullable property set to false.

public class MyClass
{
   [XmlElement(IsNullable = false)]
   public string Group;
}

You can have a look to other XmlElementAttribute for changing names in serialization etc.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

Linux / Ubuntu: If installed phpmyadmin via apt: sudo apt-get install phpmyadmin php-mbstring

Can check /etc/phpmyadmin/config-db.php for changing the user credentials.

$dbuser='pma';
$dbpass='my_pass';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='3306';
$dbtype='mysql';

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Select columns in PySpark dataframe

The method select accepts a list of column names (string) or expressions (Column) as a parameter. To select columns you can use:

-- column names (strings):

df.select('col_1','col_2','col_3')

-- column objects:

import pyspark.sql.functions as F

df.select(F.col('col_1'), F.col('col_2'), F.col('col_3'))

# or

df.select(df.col_1, df.col_2, df.col_3)

# or

df.select(df['col_1'], df['col_2'], df['col_3'])

-- a list of column names or column objects:

df.select(*['col_1','col_2','col_3'])

#or

df.select(*[F.col('col_1'), F.col('col_2'), F.col('col_3')])

#or 

df.select(*[df.col_1, df.col_2, df.col_3])

The star operator * can be omitted as it's used to keep it consistent with other functions like drop that don't accept a list as a parameter.

addEventListener, "change" and option selection

You need a click listener which calls addActivityItem if less than 2 options exist:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)
    {
        addActivityItem();
    }
});

activities.addEventListener("change", function() {
    if(activities.value == "addNew")
    {
        addActivityItem();
    }
});

function addActivityItem() {
    // ... Code to add item here
}

A live demo is here on JSfiddle.

Can I embed a custom font in an iPhone application?

I have been trying out the various suggestions on this page on iOS 3.1.2 and these are my conclusions:

Simply using [UIFont fontWithName:size:] with the fonts in the Resources directory will not work, even if the FOND name is set using FontForge.

[UIFont fontWithName:size:] will work if the fonts are loaded first using GSFontAddFromFile. But GSFontAddFromFile is not part of iOS 3.1.2 so it has to be dynamically loaded as described by @rpetrich.

Non-Static method cannot be referenced from a static context with methods and variables

You should place Scanner input = new Scanner (System.in); into the main method rather than creating the input object outside.

Selenium Finding elements by class name in python

As per the HTML:

<html>
    <body>
    <p class="content">Link1.</p>
    </body>
<html>
<html>
    <body>
    <p class="content">Link2.</p>
    </body>
<html>

Two(2) <p> elements are having the same class content.

So to filter the elements having the same class i.e. content and create a list you can use either of the following Locator Strategies:

  • Using class_name:

    elements = driver.find_elements_by_class_name("content")
    
  • Using css_selector:

     elements = driver.find_elements_by_css_selector(".content")
    
  • Using xpath:

    elements = driver.find_elements_by_xpath("//*[@class='content']")
    

Ideally, to click on the element you need to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

  • Using CLASS_NAME:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "content")))
    
  • Using CSS_SELECTOR:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".content")))
    
  • Using XPATH:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='content']")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

References

You can find a couple of relevant discussions in:

CSS text-decoration underline color

You can't change the color of the line (you can't specify different foreground colors for the same element, and the text and its decoration form a single element). However there are some tricks:

a:link, a:visited {text-decoration: none; color: red; border-bottom: 1px solid #006699; }
a:hover, a:active {text-decoration: none; color: red; border-bottom: 1px solid #1177FF; }

Also you can make some cool effects this way:

a:link {text-decoration: none; color: red; border-bottom: 1px dashed #006699; }

Hope it helps.

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

Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant. In C++ it you can define it as const.

Var is a mutable variable, meaning that it can be changed. In C++ (2011 version update), it is the same as using auto, though swift allows for more flexibility in the usage. This is the more well-known variable type to beginners.

How do I access refs of a child component in the parent component

Here is an example that will focus on an input using refs (tested in React 16.8.6):

The Child component:

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return (<input type="text" ref={this.myRef} />);
  }
}

The Parent component with the Child component inside:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }
  componentDidMount() {
    this.childRef.current.myRef.current.focus();
  }
  render() {
    return <Child ref={this.childRef} />;
  }
}

ReactDOM.render(
    <Parent />,
    document.getElementById('container')
);

The Parent component with this.props.children:

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.childRef = React.createRef();
    }
    componentDidMount() {
        this.childRef.current.myRef.current.focus();
    }
    render() {
        const ChildComponentWithRef = React.forwardRef((props, ref) =>
            React.cloneElement(this.props.children, {
                ...props,
                ref
            })
        );
        return <ChildComponentWithRef ref={this.childRef} />
    }
}

ReactDOM.render(
    <Parent>
        <Child />
    </Parent>,
    document.getElementById('container')
);

Is there a simple, elegant way to define singletons?

Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the Instance method. Here's an example:

@Singleton
class Foo:
   def __init__(self):
       print 'Foo created'

f = Foo() # Error, this isn't how you get the instance of a singleton

f = Foo.instance() # Good. Being explicit is in line with the Python Zen
g = Foo.instance() # Returns already created instance

print f is g # True

And here's the code:

class Singleton:
    """
    A non-thread-safe helper class to ease implementing singletons.
    This should be used as a decorator -- not a metaclass -- to the
    class that should be a singleton.

    The decorated class can define one `__init__` function that
    takes only the `self` argument. Also, the decorated class cannot be
    inherited from. Other than that, there are no restrictions that apply
    to the decorated class.

    To get the singleton instance, use the `instance` method. Trying
    to use `__call__` will result in a `TypeError` being raised.

    """

    def __init__(self, decorated):
        self._decorated = decorated

    def instance(self):
        """
        Returns the singleton instance. Upon its first call, it creates a
        new instance of the decorated class and calls its `__init__` method.
        On all subsequent calls, the already created instance is returned.

        """
        try:
            return self._instance
        except AttributeError:
            self._instance = self._decorated()
            return self._instance

    def __call__(self):
        raise TypeError('Singletons must be accessed through `instance()`.')

    def __instancecheck__(self, inst):
        return isinstance(inst, self._decorated)

How do I export an Android Studio project?

Apparently, there's a lot of "dead wood" in the "build" directories of a project.

Under linux/unix, a simple way to get a clean, private backup is to use the "tar" command along with the "--exclude=String" option.

For example, to create an archive of all my apps while excluding the build directories, I have a script that creates the following 2 commands :

cd $HOME/android/Studio
tar cvf MyBackup-2017-07-13.tar Projects --exclude=build

Does C# support multiple inheritance?

Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should follow the class name in the signature.

interface A { }
interface B { }
class Base { }
class AnotherClass { }

Possible ways to inherit:

class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)

This is not legal:

class SomeClass : Base, AnotherClass { }

Convert JSONObject to Map

This is what worked for me:

    public static Map<String, Object> toMap(JSONObject jsonobj)  throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();
        Iterator<String> keys = jsonobj.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            Object value = jsonobj.get(key);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }   
            map.put(key, value);
        }   return map;
    }

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }
            else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }   return list;
}

Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java

Visual Studio debugging/loading very slow

As title says, VS debugging is slow. I can't find my problem, so post it here, may be it helps someone.

In my case slow debugging was on the website hosted in IIS.

  • VS 2019 (16.4.4)
  • VS 2017 (15.9.19)
  • Windows 10 (1909)
  • IIS (10.0.18362.1)
  • Edge (44.18362.449.0)

At first time after site loading it works fine, but after 1+ minute it become lagging. Requests are pending for 1-2 minutes (F12 network tab) before my breakpoints can handle them. It was in all my active browsers.

Solution: Do not use Edge with IIS while debugging.

To understand where the problem i spent about 4-5 hours. I used Edge + Chrome for my workflow. For now i use only Chrome (with separated user profiles).

Link that helped me: https://answers.microsoft.com/en-us/windows/forum/all/iis-running-very-slowly-after-windows-10-upgrade/dae433ba-4efe-45ab-aa66-824e6fa92b51 "J Marcos" answer.

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

For those looking to do this in dask. I could not find a similar option in dask but if I simply do this in same notebook for pandas it works for dask too.

import pandas as pd
import dask.dataframe as dd
pd.set_option('display.max_colwidth', -1) # This will set the no truncate for pandas as well as for dask. Not sure how it does for dask though. but it works

train_data = dd.read_csv('./data/train.csv')    
train_data.head(5)

How should I declare default values for instance variables in Python?

Using class members for default values of instance variables is not a good idea, and it's the first time I've seen this idea mentioned at all. It works in your example, but it may fail in a lot of cases. E.g., if the value is mutable, mutating it on an unmodified instance will alter the default:

>>> class c:
...     l = []
... 
>>> x = c()
>>> y = c()
>>> x.l
[]
>>> y.l
[]
>>> x.l.append(10)
>>> y.l
[10]
>>> c.l
[10]

How to map a composite key with JPA and Hibernate?

Let's take a simple example. Let's say two tables named test and customer are there described as:

create table test(
  test_id int(11) not null auto_increment,
  primary key(test_id));

create table customer(
  customer_id int(11) not null auto_increment,
  name varchar(50) not null,
  primary key(customer_id));

One more table is there which keeps the track of tests and customer:

create table tests_purchased(
  customer_id int(11) not null,
  test_id int(11) not null,
  created_date datetime not null,
  primary key(customer_id, test_id));

We can see that in the table tests_purchased the primary key is a composite key, so we will use the <composite-id ...>...</composite-id> tag in the hbm.xml mapping file. So the PurchasedTest.hbm.xml will look like:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="entities.PurchasedTest" table="tests_purchased">

    <composite-id name="purchasedTestId">
      <key-property name="testId" column="TEST_ID" />
      <key-property name="customerId" column="CUSTOMER_ID" />
    </composite-id>

    <property name="purchaseDate" type="timestamp">
      <column name="created_date" />
    </property>

  </class>
</hibernate-mapping>

But it doesn't end here. In Hibernate we use session.load (entityClass, id_type_object) to find and load the entity using primary key. In case of composite keys, the ID object should be a separate ID class (in above case a PurchasedTestId class) which just declares the primary key attributes like below:

import java.io.Serializable;

public class PurchasedTestId implements Serializable {
  private Long testId;
  private Long customerId;

  // an easy initializing constructor
  public PurchasedTestId(Long testId, Long customerId) {
    this.testId = testId;
    this.customerId = customerId;
  }

  public Long getTestId() {
    return testId;
  }

  public void setTestId(Long testId) {
    this.testId = testId;
  }

  public Long getCustomerId() {
    return customerId;
  }

  public void setCustomerId(Long customerId) {
    this.customerId = customerId;
  }

  @Override
  public boolean equals(Object arg0) {
    if(arg0 == null) return false;
    if(!(arg0 instanceof PurchasedTestId)) return false;
    PurchasedTestId arg1 = (PurchasedTestId) arg0;
    return (this.testId.longValue() == arg1.getTestId().longValue()) &&
           (this.customerId.longValue() == arg1.getCustomerId().longValue());
  }

  @Override
  public int hashCode() {
    int hsCode;
    hsCode = testId.hashCode();
    hsCode = 19 * hsCode+ customerId.hashCode();
    return hsCode;
  }
}

Important point is that we also implement the two functions hashCode() and equals() as Hibernate relies on them.

Understanding React-Redux and mapStateToProps()

Q: Is this ok?
A: yes

Q: Is this expected?
Yes, this is expected (if you are using react-redux).

Q: Is this an anti-pattern?
A: No, this is not an anti-pattern.

It's called "connecting" your component or "making it smart". It's by design.

It allows you to decouple your component from your state an additional time which increases the modularity of your code. It also allows you to simplify your component state as a subset of your application state which, in fact, helps you comply with the Redux pattern.

Think about it this way: a store is supposed to contain the entire state of your application.
For large applications, this could contain dozens of properties nested many layers deep.
You don't want to haul all that around on each call (expensive).

Without mapStateToProps or some analog thereof, you would be tempted to carve up your state another way to improve performance/simplify.

Directory Chooser in HTML page

Can't be done in pure HTML/JavaScript for security reasons.

Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.

You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.

Another thought would be opening an iframe showing the user's C: drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).

What do you need this for?

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

How can I get stock quotes using Google Finance API?

This is no longer an active API for google, you can try Xignite, although they charge: http://www.xignite.com

Angular: Cannot Get /

Deleting node modules folder worked for me.

  • Delete the node modules folder
  • Run npm install.
  • Re-run the application and it should work.

ADB error: cannot connect to daemon

If nothing works Restart your PC . Restarting my computer does the trick

How do I remove trailing whitespace using a regular expression?

The platform is not specified, but in C# (.NET) it would be:

Regular expression (presumes the multiline option - the example below uses it):

    [ \t]+(\r?$)

Replacement:

    $1

For an explanation of "\r?$", see Regular Expression Options, Multiline Mode (MSDN).

Code example

This will remove all trailing spaces and all trailing TABs in all lines:

string inputText = "     Hello, World!  \r\n" +
                   "  Some other line\r\n" +
                   "     The last line  ";
string cleanedUpText = Regex.Replace(inputText,
                                     @"[ \t]+(\r?$)", @"$1",
                                     RegexOptions.Multiline);

How to pass data from 2nd activity to 1st activity when pressed back? - android

Activity1 should start Activity2 with startActivityForResult().

Activity2 should use setResult() to send data back to Activity1.

In Activity2,

@Override
public void onBackPressed() {
    String data = mEditText.getText();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(resultcode, intent);
}

In Activity1,

onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String myStr=data.getStringExtra("MyData");
            mTextView.setText(myStr);
        }
    }
}

Readably print out a python dict() sorted by key

Another short oneliner:

mydict = {'c': 1, 'b': 2, 'a': 3}
print(*sorted(mydict.items()), sep='\n')

What is the @Html.DisplayFor syntax for?

I think the main benefit would be when you define your own Display Templates, or use Data annotations.

So for example if your title was a date, you could define

[DisplayFormat(DataFormatString = "{0:d}")]

and then on every page it would display the value in a consistent manner. Otherwise you may have to customise the display on multiple pages. So it does not help much for plain strings, but it does help for currencies, dates, emails, urls, etc.

For example instead of an email address being a plain string it could show up as a link:

<a href="mailto:@ViewData.Model">@ViewData.TemplateInfo.FormattedModelValue</a>

How to switch activity without animation in Android?

This is not an example use or an explanation of how to use FLAG_ACTIVITY_NO_ANIMATION, however it does answer how to disable the Activity switching animation, as asked in the question title:

Android, how to disable the 'wipe' effect when starting a new activity?

What is the recommended way to delete a large number of items from DynamoDB?

Thought about using the test to pass in the vars? Something like:

Test input would be something like:

{
  "TABLE_NAME": "MyDevTable",
  "PARTITION_KEY": "REGION",
  "SORT_KEY": "COUNTRY"
}

Adjusted your code to accept the inputs:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });

exports.handler = async (event) => {
    const TABLE_NAME = event.TABLE_NAME;
    const PARTITION_KEY = event.PARTITION_KEY;
    const SORT_KEY = event.SORT_KEY;
    let params = {
        TableName: TABLE_NAME,
    };
    console.log(`keys: ${PARTITION_KEY} ${SORT_KEY}`);

    let items = [];
    let data = await docClient.scan(params).promise();
    items = [...items, ...data.Items];
    
    while (typeof data.LastEvaluatedKey != 'undefined') {
        params.ExclusiveStartKey = data.LastEvaluatedKey;

        data = await docClient.scan(params).promise();
        items = [...items, ...data.Items];
    }

    let leftItems = items.length;
    let group = [];
    let groupNumber = 0;

    console.log('Total items to be deleted', leftItems);

    for (const i of items) {
        // console.log(`item: ${i[PARTITION_KEY] } ${i[SORT_KEY]}`);
        const deleteReq = {DeleteRequest: {Key: {},},};
        deleteReq.DeleteRequest.Key[PARTITION_KEY] = i[PARTITION_KEY];
        deleteReq.DeleteRequest.Key[SORT_KEY] = i[SORT_KEY];

        // console.log(`DeleteRequest: ${JSON.stringify(deleteReq)}`);
        group.push(deleteReq);
        leftItems--;

        if (group.length === 25 || leftItems < 1) {
            groupNumber++;

            console.log(`Batch ${groupNumber} to be deleted.`);

            const params = {
                RequestItems: {
                    [TABLE_NAME]: group,
                },
            };

            await docClient.batchWrite(params).promise();

            console.log(
                `Batch ${groupNumber} processed. Left items: ${leftItems}`
            );

            // reset
            group = [];
        }
    }

    const response = {
        statusCode: 200,
        //  Uncomment below to enable CORS requests
        headers: {
            "Access-Control-Allow-Origin": "*"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

How to check if a specific key is present in a hash or not?

You can always use Hash#key? to check if the key is present in a hash or not.

If not it will return you false

hash =  { one: 1, two:2 }

hash.key?(:one)
#=> true

hash.key?(:four)
#=> false

Copy from one workbook and paste into another

This should do it, let me know if you have trouble with it:

Sub foo()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy

'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial

'Close x:
x.Close

End Sub

Alternatively, you could just:

Sub foo2()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1") 

'Close x:
x.Close

End Sub

To extend this to the entire sheet:

With x.Sheets("name of copying sheet").UsedRange
    'Now, paste to y worksheet:
    y.Sheets("sheet name").Range("A1").Resize( _
        .Rows.Count, .Columns.Count) = .Value
End With

And yet another way, store the value as a variable and write the variable to the destination:

Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value

'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals 

'Close x:
x.Close

End Sub

The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:

Copy/PasteSpecial vs Range.Value = Range.Value

That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.

How do I perform the SQL Join equivalent in MongoDB?

You have to do it the way you described. MongoDB is a non-relational database and doesn't support joins.

Delimiters in MySQL

Delimiters other than the default ; are typically used when defining functions, stored procedures, and triggers wherein you must define multiple statements. You define a different delimiter like $$ which is used to define the end of the entire procedure, but inside it, individual statements are each terminated by ;. That way, when the code is run in the mysql client, the client can tell where the entire procedure ends and execute it as a unit rather than executing the individual statements inside.

Note that the DELIMITER keyword is a function of the command line mysql client (and some other clients) only and not a regular MySQL language feature. It won't work if you tried to pass it through a programming language API to MySQL. Some other clients like PHPMyAdmin have other methods to specify a non-default delimiter.

Example:

DELIMITER $$
/* This is a complete statement, not part of the procedure, so use the custom delimiter $$ */
DROP PROCEDURE my_procedure$$

/* Now start the procedure code */
CREATE PROCEDURE my_procedure ()
BEGIN    
  /* Inside the procedure, individual statements terminate with ; */
  CREATE TABLE tablea (
     col1 INT,
     col2 INT
  );

  INSERT INTO tablea
    SELECT * FROM table1;

  CREATE TABLE tableb (
     col1 INT,
     col2 INT
  );
  INSERT INTO tableb
    SELECT * FROM table2;
  
/* whole procedure ends with the custom delimiter */
END$$

/* Finally, reset the delimiter to the default ; */
DELIMITER ;

Attempting to use DELIMITER with a client that doesn't support it will cause it to be sent to the server, which will report a syntax error. For example, using PHP and MySQLi:

$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$result = $mysqli->query('DELIMITER $$');
echo $mysqli->error;

Errors with:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER $$' at line 1

Generate random numbers uniformly over an entire range

The solution given by man 3 rand for a number between 1 and 10 inclusive is:

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

In your case, it would be:

j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));

Of course, this is not perfect randomness or uniformity as some other messages are pointing out, but this is enough for most cases.

Using ADB to capture the screen

Sorry to tell you screencap just a simple command, only accept few arguments, but none of them can save time for you, here is the -h help output.

$ adb shell screencap -h
usage: screencap [-hp] [-d display-id] [FILENAME]
-h: this message
-p: save the file as a png.
-d: specify the display id to capture, default 0.
If FILENAME ends with .png it will be saved as a png.
If FILENAME is not given, the results will be printed to stdout.

Besides the command screencap, there is another command screenshot, I don't know why screenshot was removed from Android 5.0, but it's avaiable below Android 4.4, you can check the source from here. I didn't make my comparison which is faster between these two commands, but you can give your try in your real environment and make the final decision.

How to insert a file in MySQL database?

You need to use BLOB, there's TINY, MEDIUM, LONG, and just BLOB, as with other types, choose one according to your size needs.

TINYBLOB 255
BLOB 65535
MEDIUMBLOB 16777215
LONGBLOB 4294967295
(in bytes)

The insert statement would be fairly normal. You need to read the file using fread and then addslashes to it.

MySQL limit from descending order

yes, you can swap these 2 queries

select * from table limit 5, 5

select * from table limit 0, 5

Delete file from internal storage

File file = new File(getFilePath(imageUri.getValue())); 
boolean b = file.delete();

is not working in my case.

boolean b = file.delete();                 // returns false
boolean b = file.getAbsolutePath.delete(); // returns false 

always returns false.

The issue has been resolved by using the code below:

ContentResolver contentResolver = getContentResolver();
contentResolver.delete(uriDelete, null, null);

Split / Explode a column of dictionaries into separate columns with pandas

I know the question is quite old, but I got here searching for answers. There is actually a better (and faster) way now of doing this using json_normalize:

import pandas as pd

df2 = pd.json_normalize(df['Pollutant Levels'])

This avoids costly apply functions...

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

How can I merge two MySQL tables?

It depends on the semantic of the primary key. If it's just autoincrement, then use something like:

insert into table1 (all columns except pk)
select all_columns_except_pk 
from table2;

If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.

How to set DialogFragment's width and height?

The only thing that worked in my case was the solution pointed here: http://adilatwork.blogspot.mx/2012/11/android-dialogfragment-dialog-sizing.html

Snippet from Adil blog post:

@Override
public void onStart()
{
  super.onStart();

  // safety check
  if (getDialog() == null)
    return;

  int dialogWidth = ... // specify a value here
  int dialogHeight = ... // specify a value here

  getDialog().getWindow().setLayout(dialogWidth, dialogHeight);

  // ... other stuff you want to do in your onStart() method
}

Java: Multiple class declarations in one file

No. You can't. But it is very possible in Scala:

class Foo {val bar = "a"}
class Bar {val foo = "b"}

How to set a value to a file input in HTML?

Define in html:

<input type="hidden" name="image" id="image"/>

In JS:

ajax.jsonRpc("/consulta/dni", 'call', {'document_number': document_number})
    .then(function (data) {
        if (data.error){
            ...;
        }
        else {
            $('#image').val(data.image);
        }
    })

After:

<input type="hidden" name="image" id="image" value="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8U..."/>
<button type="submit">Submit</button>

Does the join order matter in SQL?

If you try joining C on a field from B before joining B, i.e.:

SELECT A.x, 
       A.y, 
       A.z 
FROM A 
   INNER JOIN C
       on B.x = C.x
   INNER JOIN B
       on A.x = B.x

your query will fail, so in this case the order matters.

Expression must have class type

a is a pointer. You need to use->, not .

Difference between "\n" and Environment.NewLine

Environment.NewLine will return the newline character for the corresponding platform in which your code is running

you will find this very useful when you deploy your code in linux on the Mono framework

What is TypeScript and why would I use it in place of JavaScript?

TypeScript's relation to JavaScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript - typescriptlang.org.

JavaScript is a programming language that is developed by EMCA's Technical Committee 39, which is a group of people composed of many different stakeholders. TC39 is a committee hosted by ECMA: an internal standards organization. JavaScript has many different implementations by many different vendors (e.g. Google, Microsoft, Oracle, etc.). The goal of JavaScript is to be the lingua franca of the web.

TypeScript is a superset of the JavaScript language that has a single open-source compiler and is developed mainly by a single vendor: Microsoft. The goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient.

Essentially TypeScript achieves its goals in three ways:

  1. Support for modern JavaScript features - The JavaScript language (not the runtime) is standardized through the ECMAScript standards. Not all browsers and JavaScript runtimes support all features of all ECMAScript standards (see this overview). TypeScript allows for the use of many of the latest ECMAScript features and translates them to older ECMAScript targets of your choosing (see the list of compile targets under the --target compiler option). This means that you can safely use new features, like modules, lambda functions, classes, the spread operator and destructuring, while remaining backwards compatible with older browsers and JavaScript runtimes.

  2. Advanced type system - The type support is not part of the ECMAScript standard and will likely never be due to the interpreted nature instead of compiled nature of JavaScript. The type system of TypeScript is incredibly rich and includes: interfaces, enums, hybrid types, generics, union/intersection types, access modifiers and much more. The official website of TypeScript gives an overview of these features. Typescript's type system is on-par with most other typed languages and in some cases arguably more powerful.

  3. Developer tooling support - TypeScript's compiler can run as a background process to support both incremental compilation and IDE integration such that you can more easily navigate, identify problems, inspect possibilities and refactor your codebase.

TypeScript's relation to other JavaScript targeting languages

TypeScript has a unique philosophy compared to other languages that compile to JavaScript. JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. You can almost rename your .js files to .ts files and start using TypeScript (see "JavaScript interoperability" below). TypeScript files are compiled to readable JavaScript, so that migration back is possible and understanding the compiled TypeScript is not hard at all. TypeScript builds on the successes of JavaScript while improving on its weaknesses.

On the one hand, you have future proof tools that take modern ECMAScript standards and compile it down to older JavaScript versions with Babel being the most popular one. On the other hand, you have languages that may totally differ from JavaScript which target JavaScript, like CoffeeScript, Clojure, Dart, Elm, Haxe, Scala.js, and a whole host more (see this list). These languages, though they might be better than where JavaScript's future might ever lead, run a greater risk of not finding enough adoption for their futures to be guaranteed. You might also have more trouble finding experienced developers for some of these languages, though the ones you will find can often be more enthusiastic. Interop with JavaScript can also be a bit more involved, since they are farther removed from what JavaScript actually is.

TypeScript sits in between these two extremes, thus balancing the risk. TypeScript is not a risky choice by any standard. It takes very little effort to get used to if you are familiar with JavaScript, since it is not a completely different language, has excellent JavaScript interoperability support and it has seen a lot of adoption recently.

Optionally static typing and type inference

JavaScript is dynamically typed. This means JavaScript does not know what type a variable is until it is actually instantiated at run-time. This also means that it may be too late. TypeScript adds type support to JavaScript and catches type errors during compilation to JavaScript. Bugs that are caused by false assumptions of some variable being of a certain type can be completely eradicated if you play your cards right (how strict you type your code or if you type your code at all is up to you).

TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. For example: var x = "hello" in TypeScript is the same as var x : string = "hello". The type is simply inferred from its use. Even it you don't explicitly type the types, they are still there to save you from doing something which otherwise would result in a run-time error.

TypeScript is optionally typed by default. For example function divideByTwo(x) { return x / 2 } is a valid function in TypeScript which can be called with any kind of parameter, even though calling it with a string will obviously result in a runtime error. Just like you are used to in JavaScript. This works, because when no type was explicitly assigned and the type could not be inferred, like in the divideByTwo example, TypeScript will implicitly assign the type any. This means the divideByTwo function's type signature automatically becomes function divideByTwo(x : any) : any. There is a compiler flag to disallow this behavior: --noImplicitAny. Enabling this flag gives you a greater degree of safety, but also means you will have to do more typing.

Types have a cost associated with them. First of all, there is a learning curve, and second of all, of course, it will cost you a bit more time to set up a codebase using proper strict typing too. In my experience, these costs are totally worth it on any serious codebase you are sharing with others. A Large Scale Study of Programming Languages and Code Quality in Github suggests that "statically typed languages, in general, are less defect prone than the dynamic types, and that strong typing is better than weak typing in the same regard".

It is interesting to note that this very same paper finds that TypeScript is less error-prone than JavaScript:

For those with positive coefficients we can expect that the language is associated with, ceteris paribus, a greater number of defect fixes. These languages include C, C++, JavaScript, Objective-C, Php, and Python. The languages Clojure, Haskell, Ruby, Scala, and TypeScript, all have negative coefficients implying that these languages are less likely than the average to result in defect fixing commits.

Enhanced IDE support

The development experience with TypeScript is a great improvement over JavaScript. The IDE is informed in real-time by the TypeScript compiler on its rich type information. This gives a couple of major advantages. For example, with TypeScript, you can safely do refactorings like renames across your entire codebase. Through code completion, you can get inline help on whatever functions a library might offer. No more need to remember them or look them up in online references. Compilation errors are reported directly in the IDE with a red squiggly line while you are busy coding. All in all, this allows for a significant gain in productivity compared to working with JavaScript. One can spend more time coding and less time debugging.

There is a wide range of IDEs that have excellent support for TypeScript, like Visual Studio Code, WebStorm, Atom and Sublime.

Strict null checks

Runtime errors of the form cannot read property 'x' of undefined or undefined is not a function are very commonly caused by bugs in JavaScript code. Out of the box TypeScript already reduces the probability of these kinds of errors occurring, since one cannot use a variable that is not known to the TypeScript compiler (with the exception of properties of any typed variables). It is still possible though to mistakenly utilize a variable that is set to undefined. However, with the 2.0 version of TypeScript you can eliminate these kinds of errors all together through the usage of non-nullable types. This works as follows:

With strict null checks enabled (--strictNullChecks compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. For example, let x : number = undefined will result in a compile error. This fits perfectly with type theory since undefined is not a number. One can define x to be a sum type of number and undefined to correct this: let x : number | undefined = undefined.

Once a type is known to be nullable, meaning it is of a type that can also be of the value null or undefined, the TypeScript compiler can determine through control flow based type analysis whether or not your code can safely use a variable or not. In other words when you check a variable is undefined through for example an if statement the TypeScript compiler will infer that the type in that branch of your code's control flow is not anymore nullable and therefore can safely be used. Here is a simple example:

let x: number | undefined;
if (x !== undefined) x += 1; // this line will compile, because x is checked.
x += 1; // this line will fail compilation, because x might be undefined.

During the build, 2016 conference co-designer of TypeScript Anders Hejlsberg gave a detailed explanation and demonstration of this feature: video (from 44:30 to 56:30).

Compilation

To use TypeScript you need a build process to compile to JavaScript code. The build process generally takes only a couple of seconds depending of course on the size of your project. The TypeScript compiler supports incremental compilation (--watch compiler flag) so that all subsequent changes can be compiled at greater speed.

The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. Source map information can be used by debugging utilities like the Chrome DevTools and other IDE's to relate the lines in the JavaScript to the ones that generated them in the TypeScript. This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code. Source map information works pretty well, it was around long before TypeScript, but debugging TypeScript is generally not as great as when using JavaScript directly. Take the this keyword for example. Due to the changed semantics of the this keyword around closures since ES2015, this may actually exists during runtime as a variable called _this (see this answer). This may confuse you during debugging but generally is not a problem if you know about it or inspect the JavaScript code. It should be noted that Babel suffers the exact same kind of issue.

There are a few other tricks the TypeScript compiler can do, like generating intercepting code based on decorators, generating module loading code for different module systems and parsing JSX. However, you will likely require a build tool besides the Typescript compiler. For example, if you want to compress your code you will have to add other tools to your build process to do so.

There are TypeScript compilation plugins available for Webpack, Gulp, Grunt and pretty much any other JavaScript build tool out there. The TypeScript documentation has a section on integrating with build tools covering them all. A linter is also available in case you would like even more build time checking. There are also a great number of seed projects out there that will get you started with TypeScript in combination with a bunch of other technologies like Angular 2, React, Ember, SystemJS, Webpack, Gulp, etc.

JavaScript interoperability

Since TypeScript is so closely related to JavaScript it has great interoperability capabilities, but some extra work is required to work with JavaScript libraries in TypeScript. TypeScript definitions are needed so that the TypeScript compiler understands that function calls like _.groupBy or angular.copy or $.fadeOut are not in fact illegal statements. The definitions for these functions are placed in .d.ts files.

The simplest form a definition can take is to allow an identifier to be used in any way. For example, when using Lodash, a single line definition file declare var _ : any will allow you to call any function you want on _, but then, of course, you are also still able to make mistakes: _.foobar() would be a legal TypeScript call, but is, of course, an illegal call at run-time. If you want proper type support and code completion your definition file needs to to be more exact (see lodash definitions for an example).

Npm modules that come pre-packaged with their own type definitions are automatically understood by the TypeScript compiler (see documentation). For pretty much any other semi-popular JavaScript library that does not include its own definitions somebody out there has already made type definitions available through another npm module. These modules are prefixed with "@types/" and come from a Github repository called DefinitelyTyped.

There is one caveat: the type definitions must match the version of the library you are using at run-time. If they do not, TypeScript might disallow you from calling a function or dereferencing a variable that exists or allow you to call a function or dereference a variable that does not exist, simply because the types do not match the run-time at compile-time. So make sure you load the right version of the type definitions for the right version of the library you are using.

To be honest, there is a slight hassle to this and it may be one of the reasons you do not choose TypeScript, but instead go for something like Babel that does not suffer from having to get type definitions at all. On the other hand, if you know what you are doing you can easily overcome any kind of issues caused by incorrect or missing definition files.

Converting from JavaScript to TypeScript

Any .js file can be renamed to a .ts file and ran through the TypeScript compiler to get syntactically the same JavaScript code as an output (if it was syntactically correct in the first place). Even when the TypeScript compiler gets compilation errors it will still produce a .js file. It can even accept .js files as input with the --allowJs flag. This allows you to start with TypeScript right away. Unfortunately, compilation errors are likely to occur in the beginning. One does need to remember that these are not show-stopping errors like you may be used to with other compilers.

The compilation errors one gets in the beginning when converting a JavaScript project to a TypeScript project are unavoidable by TypeScript's nature. TypeScript checks all code for validity and thus it needs to know about all functions and variables that are used. Thus type definitions need to be in place for all of them otherwise compilation errors are bound to occur. As mentioned in the chapter above, for pretty much any JavaScript framework there are .d.ts files that can easily be acquired with the installation of DefinitelyTyped packages. It might, however, be that you've used some obscure library for which no TypeScript definitions are available or that you've polyfilled some JavaScript primitives. In that case, you must supply type definitions for these bits for the compilation errors to disappear. Just create a .d.ts file and include it in the tsconfig.json's files array, so that it is always considered by the TypeScript compiler. In it declare those bits that TypeScript does not know about as type any. Once you've eliminated all errors you can gradually introduce typing to those parts according to your needs.

Some work on (re)configuring your build pipeline will also be needed to get TypeScript into the build pipeline. As mentioned in the chapter on compilation there are plenty of good resources out there and I encourage you to look for seed projects that use the combination of tools you want to be working with.

The biggest hurdle is the learning curve. I encourage you to play around with a small project at first. Look how it works, how it builds, which files it uses, how it is configured, how it functions in your IDE, how it is structured, which tools it uses, etc. Converting a large JavaScript codebase to TypeScript is doable when you know what you are doing. Read this blog for example on converting 600k lines to typescript in 72 hours). Just make sure you have a good grasp of the language before you make the jump.

Adoption

TypeScript is open-source (Apache 2 licensed, see GitHub) and backed by Microsoft. Anders Hejlsberg, the lead architect of C# is spearheading the project. It's a very active project; the TypeScript team has been releasing a lot of new features in the last few years and a lot of great ones are still planned to come (see the roadmap).

Some facts about adoption and popularity:

  • In the 2017 StackOverflow developer survey TypeScript was the most popular JavaScript transpiler (9th place overall) and won third place in the most loved programming language category.
  • In the 2018 state of js survey TypeScript was declared as one of the two big winners in the JavaScript flavors category (with ES6 being the other).
  • In the 2019 StackOverlow deverloper survey TypeScript rose to the 9th place of most popular languages amongst professional developers, overtaking both C and C++. It again took third place amongst most the most loved languages.

Key Presses in Python

You could also use PyAutoGui to send a virtual key presses.

Here's the documentation: https://pyautogui.readthedocs.org/en/latest/

import pyautogui


pyautogui.press('Any key combination')

You can also send keys like the shift key or enter key with:

import pyautogui

pyautogui.press('shift')

Pyautogui can also send straight text like so:

import pyautogui

pyautogui.typewrite('any text you want to type')

As for pressing the "A" key 1000 times, it would look something like this:

import pyautogui

for i in range(999):
    pyautogui.press("a")

alt-tab or other tasks that require more than one key to be pressed at the same time:

import pyautogui

# Holds down the alt key
pyautogui.keyDown("alt")

# Presses the tab key once
pyautogui.press("tab")

# Lets go of the alt key
pyautogui.keyUp("alt")

How to configure a HTTP proxy for svn

You can find the instructions here. Basically you just add

[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128
http-proxy-compression = no

to your ~/.subversion/servers file.

SQL permissions for roles

Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:

GRANT ALL ON table1 TO doctor 

Users in that role will have no permissions whatsoever to other tables (not even read).

List Directories and get the name of the Directory

import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in dirs:
        print os.path.join(root, name)

Walk is a good built-in for what you are doing

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

How can I get the ID of an element using jQuery?

Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use:

$('.classname').id();

$('#elementId').id();

addEventListener not working in IE8

You can use the below addEvent() function to add events for most things but note that for XMLHttpRequest if (el.attachEvent) will fail in IE8, because it doesn't support XMLHttpRequest.attachEvent() so you have to use XMLHttpRequest.onload = function() {} instead.

function addEvent(el, e, f) {
    if (el.attachEvent) {
        return el.attachEvent('on'+e, f);
    }
    else {
        return el.addEventListener(e, f, false);
    }
}

var ajax = new XMLHttpRequest();
ajax.onload = function(e) {
}

Why use prefixes on member variables in C++ classes

Many of those conventions are from a time without sophisticated editors. I would recommend using a proper IDE that allows you to color every kind of variable. Color is by far easier to spot than any prefix.

If you need to get even more detail on a variable any modern IDE should be able to show it to you by moving the caret or cursor over it. And if you use a variable in a wrong way (for instance a pointer with the . operator) you will get an error, anyway.

How do I make a Windows batch script completely silent?

Copies a directory named html & all its contents to a destination directory in silent mode. If the destination directory is not present it will still create it.

@echo off
TITLE Copy Folder with Contents

set SOURCE=C:\labs
set DESTINATION=C:\Users\MyUser\Desktop\html

xcopy %SOURCE%\html\* %DESTINATION%\* /s /e /i /Y >NUL

  1. /S Copies directories and subdirectories except empty ones.

  2. /E Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.

  3. /I If destination does not exist and copying more than one file, assumes that destination must be a directory.

  4. /Y Suppresses prompting to confirm you want to overwrite an existing destination file.

Android fade in and fade out with ImageView

I used used fadeIn animation to replace new image for old one

ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();

How to identify all stored procedures referring a particular table

This useful query also works if you are using Azure SQL / Synapse Anlaytics

SELECT DISTINCT o.name AS Object_Name,o.type_desc
FROM sys.sql_modules m
INNER JOIN sys.objects o
ON m.object_id=o.object_id
WHERE m.definition Like '%Table_Name%'

How to launch PowerShell (not a script) from the command line

Set the default console colors and fonts:

http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)

Set-StrictMode -Version Latest

Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'

New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

How to set page content to the middle of screen?

Solution for the code you posted:

.center{
    position:absolute;
    width:780px;
    height:650px;
    left:50%;
    top:50%;
    margin-left:-390px;
    margin-top:-325px;
}

<table class="center" width="780" border="0" align="center" cellspacing="2" bordercolor="#000000" bgcolor="#FFCC66">
      <tr>
        <td>
        <table width="100%" border="0">
      <tr>
        <td>
        <table width="100%" border="0">
        <tr>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
            <td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>        
        </tr>
        </table>
        </td>
      </tr>
      <tr>
        <td>
        <table width="100%" border="0">
        <tr>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
            <td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>        
        </tr>
        </table>
        </td>
      </tr>
</table>

--

How this works?

Example: http://jsfiddle.net/953Yj/

<div class="center">
    Lorem ipsum
</div>

.center{
    position:absolute;
    height: X px;
    width: Y px;
    left:50%;
    top:50%;
    margin-top:- X/2 px;
    margin-left:- Y/2 px;
}
  • X would your your height.
  • Y would be your width.

To position the div vertically and horizontally, divide X and Y by 2.

How can I parse a CSV string with JavaScript, which contains comma in data?

Regular expressions to the rescue! These few lines of code handle properly quoted fields with embedded commas, quotes, and newlines based on the RFC 4180 standard.

function parseCsv(data, fieldSep, newLine) {
    fieldSep = fieldSep || ',';
    newLine = newLine || '\n';
    var nSep = '\x1D';
    var qSep = '\x1E';
    var cSep = '\x1F';
    var nSepRe = new RegExp(nSep, 'g');
    var qSepRe = new RegExp(qSep, 'g');
    var cSepRe = new RegExp(cSep, 'g');
    var fieldRe = new RegExp('(?<=(^|[' + fieldSep + '\\n]))"(|[\\s\\S]+?(?<![^"]"))"(?=($|[' + fieldSep + '\\n]))', 'g');
    var grid = [];
    data.replace(/\r/g, '').replace(/\n+$/, '').replace(fieldRe, function(match, p1, p2) {
        return p2.replace(/\n/g, nSep).replace(/""/g, qSep).replace(/,/g, cSep);
    }).split(/\n/).forEach(function(line) {
        var row = line.split(fieldSep).map(function(cell) {
            return cell.replace(nSepRe, newLine).replace(qSepRe, '"').replace(cSepRe, ',');
        });
        grid.push(row);
    });
    return grid;
}

const csv = 'A1,B1,C1\n"A ""2""","B, 2","C\n2"';
const separator = ',';      // field separator, default: ','
const newline = ' <br /> '; // newline representation in case a field contains newlines, default: '\n' 
var grid = parseCsv(csv, separator, newline);
// expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C <br /> 2' ] ]

Unless stated elsewhere, you don't need a finite state machine. The regular expression handles RFC 4180 properly thanks to positive lookbehind, negative lookbehind, and positive lookahead.

Clone/download code at https://github.com/peterthoeny/parse-csv-js

Can you recommend a free light-weight MySQL GUI for Linux?

I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.

There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.

app-release-unsigned.apk is not signed

My solution was to change the name of my signing config from the default "config" to "debug". To verify, I changed it to some other random name and got the error again, and then changed it back to "debug" and the error was gone. So while it seems artificial and I tend to not believe this is the whole story, give this solution a try.

How to sort a Collection<T>?

Collections by themselves do not have a predefined order, therefore you must convert them to a java.util.List. Then you can use one form of java.util.Collections.sort

Collection< T > collection = ...;

List< T > list = new ArrayList< T >( collection );

Collections.sort( list );
 // or
Collections.sort( list, new Comparator< T >( ){...} );

// list now is sorted

3-dimensional array in numpy

As much as people like to say "order doesn't matter its just convention" this breaks down when entering cross domain interfaces, IE transfer from C ordering to Fortran ordering or some other ordering scheme. There, precisely how your data is layed out and how shape is represented in numpy is very important.

By default, numpy uses C ordering, which means contiguous elements in memory are the elements stored in rows. You can also do FORTRAN ordering ("F"), this instead orders elements based on columns, indexing contiguous elements.

Numpy's shape further has its own order in which it displays the shape. In numpy, shape is largest stride first, ie, in a 3d vector, it would be the least contiguous dimension, Z, or pages, 3rd dim etc... So when executing:

np.zeros((2,3,4)).shape

you will get

(2,3,4)

which is actually (frames, rows, columns). doing np.zeros((2,2,3,4)).shape instead would mean (metaframs, frames, rows, columns). This makes more sense when you think of creating multidimensional arrays in C like langauges. For C++, creating a non contiguously defined 4D array results in an array [ of arrays [ of arrays [ of elements ]]]. This forces you to de reference the first array that holds all the other arrays (4th dimension) then the same all the way down (3rd, 2nd, 1st) resulting in syntax like:

double element = array4d[w][z][y][x];

In fortran, this indexed ordering is reversed (x is instead first array4d[x][y][z][w]), most contiguous to least contiguous and in matlab, it gets all weird.

Matlab tried to preserve both mathematical default ordering (row, column) but also use column major internally for libraries, and not follow C convention of dimensional ordering. In matlab, you order this way:

double element = array4d[y][x][z][w];

which deifies all convention and creates weird situations where you are sometimes indexing as if row ordered and sometimes column ordered (such as with matrix creation).

In reality, Matlab is the unintuitive one, not Numpy.

What is a callback in java

A callback is commonly used in asynchronous programming, so you could create a method which handles the response from a web service. When you call the web service, you could pass the method to it so that when the web service responds, it call's the method you told it ... it "calls back".

In Java this can commonly be done through implementing an interface and passing an object (or an anonymous inner class) that implements it. You find this often with transactions and threading - such as the Futures API.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html

Printing leading 0's in C

There are 2 ways to output your number with leading zeroes:

Using the 0 flag and the width specifier:

int zipcode = 123;
printf("%05d\n", zipcode);  // outputs 00123

Using the precision specifier:

int zipcode = 123;
printf("%.5d\n", zipcode);  // outputs 00123

The difference between these is the handling of negative numbers:

printf("%05d\n", -123);  // outputs -0123 (pad to 5 characters)
printf("%.5d\n", -123);  // outputs -00123 (pad to 5 digits)

Zip codes are unlikely to be negative, so it should not matter.

Note however that zip codes may actually contain letters and dashes, so they should be stored as strings. Including the leading zeroes in the string is straightforward so it solves your problem in a much simpler way.

Note that in both examples above, the 5 width or precision values can be specified as an int argument:

int width = 5;
printf("%0*d\n", width, 123);  // outputs 00123
printf("%.*d\n", width, 123);  // outputs 00123

There is one more trick to know: a precision of 0 causes no output for the value 0:

printf("|%0d|%0d|\n", 0, 1);  // outputs |0|1|
printf("|%.0d|%.0d|\n", 0, 1);  // outputs ||1|

HTML colspan in CSS

if you use div and span it will occupy more code size when the datagrid-table row are more in volume. This below code is checked in all browsers

HTML:

<div id="gridheading">
<h4>Sl.No</h4><h4 class="big">Name</h4><h4>Location</h4><h4>column</h4><h4>column</h4><h4>column</h4><h4>Amount(Rs)</h4><h4>View</h4><h4>Edit</h4><h4>Delete</h4> 
</div>
<div class="data"> 
<h4>01</h4><h4 class="big">test</h4><h4>TVM</h4><h4>A</h4><h4>I</h4><h4>4575</h4><h4>4575</h4></div>
<div class="data"> 
<h4>01</h4><h4 class="big">test</h4><h4>TVM</h4><h4>A</h4><h4>I</h4><h4>4575</h4><h4>4575</h4></div>

CSS:

#gridheading {
    background: #ccc;
    border-bottom: 1px dotted #BBBBBB;
    font-size: 12px;
    line-height: 30px;
    text-transform: capitalize;
}
.data {
    border-bottom: 1px dotted #BBBBBB;
    display: block;
    font-weight: normal;
    line-height: 20px;
    text-align: left;
    word-wrap: break-word;
}
 h4 {
    border-right: thin dotted #000000;
    display: table-cell;
    margin-right: 100px;
    text-align: center;
    width: 100px;
    word-wrap: break-word;
}
.data .big {
    margin-right: 150px;
    width: 200px;
}

onSaveInstanceState () and onRestoreInstanceState ()

The main thing is that if you don't store in onSaveInstanceState() then onRestoreInstanceState() will not be called. This is the main difference between restoreInstanceState() and onCreate(). Make sure you really store something. Most likely this is your problem.

case statement in where clause - SQL Server

simply do the select:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

SQL RANK() versus ROW_NUMBER()

ROW_NUMBER : Returns a unique number for each row starting with 1. For rows that have duplicate values,numbers are arbitarily assigned.

Rank : Assigns a unique number for each row starting with 1,except for rows that have duplicate values,in which case the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.

How do I change the select box arrow

CSS

select.inpSelect {
  //Remove original arrows
  -webkit-appearance: none; 
  //Use png at assets/selectArrow.png for the arrow on the right
  //Set the background color to a BadAss Green color 
  background: url(assets/selectArrow.png) no-repeat right #BADA55;
}

How to print to console using swift playground?

move you mouse over the "Hello, playground" on the right side bar, you will see an eye icon and a small circle icon next it. Just click on the circle one to show the detail page and console output!

Handle Button click inside a row in RecyclerView

this is how I handle multiple onClick events inside a recyclerView:

Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference in the ViewHolder to eliminate a potential memory leak.

Define interface :

public interface ClickListener {

    void onPositionClicked(int position);
    
    void onLongClicked(int position);
}

Then the Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
    private final ClickListener listener;
    private final List<MyItems> itemsList;

    public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
        this.listener = listener;
        this.itemsList = itemsList;
    }

    @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);
    }

    @Override public void onBindViewHolder(MyViewHolder holder, int position) {
        // bind layout and data etc..
    }

    @Override public int getItemCount() {
        return itemsList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private ImageView iconImageView;
        private TextView iconTextView;
        private WeakReference<ClickListener> listenerRef;

        public MyViewHolder(final View itemView, ClickListener listener) {
            super(itemView);

            listenerRef = new WeakReference<>(listener);
            iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
            iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

            itemView.setOnClickListener(this);
            iconTextView.setOnClickListener(this);
            iconImageView.setOnLongClickListener(this);
        }

        // onClick Listener for view
        @Override
        public void onClick(View v) {

            if (v.getId() == iconTextView.getId()) {
                Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
            
            listenerRef.get().onPositionClicked(getAdapterPosition());
        }


        //onLongClickListener for view
        @Override
        public boolean onLongClick(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Hello Dialog")
                    .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            builder.create().show();
            listenerRef.get().onLongClicked(getAdapterPosition());
            return true;
        }
    }
}

Then in your activity/fragment - whatever you can implement : Clicklistener - or anonymous class if you wish like so :

MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
            @Override public void onPositionClicked(int position) {
                // callback performed on click
            }

            @Override public void onLongClicked(int position) {
                // callback performed on click
            }
        });

To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()

Hope this approach helps!

How to create bitmap from byte array?

Guys thank you for your help. I think all of this answers works. However i think my byte array contains raw bytes. That's why all of those solutions didnt work for my code.

However i found a solution. Maybe this solution helps other coders who have problem like mine.

static byte[] PadLines(byte[] bytes, int rows, int columns) {
   int currentStride = columns; // 3
   int newStride = columns;  // 4
   byte[] newBytes = new byte[newStride * rows];
   for (int i = 0; i < rows; i++)
       Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
   return newBytes;
 }

 int columns = imageWidth;
 int rows = imageHeight;
 int stride = columns;
 byte[] newbytes = PadLines(imageData, rows, columns);

 Bitmap im = new Bitmap(columns, rows, stride, 
          PixelFormat.Format8bppIndexed, 
          Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));

 im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");

This solutions works for 8bit 256 bpp (Format8bppIndexed). If your image has another format you should change PixelFormat .

And there is a problem with colors right now. As soon as i solved this one i will edit my answer for other users.

*PS = I am not sure about stride value but for 8bit it should be equal to columns.

And also this function Works for me.. This function copies 8 bit greyscale image into a 32bit layout.

public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
        {

            byte[] data = new byte[width * height * 4];

            int o = 0;

            for (int i = 0; i < width * height; i++)
            {
                byte value = imageData[i];


                data[o++] = value;
                data[o++] = value;
                data[o++] = value;
                data[o++] = 0; 
            }

            unsafe
            {
                fixed (byte* ptr = data)
                {

                    using (Bitmap image = new Bitmap(width, height, width * 4,
                                PixelFormat.Format32bppRgb, new IntPtr(ptr)))
                    {

                        image.Save(Path.ChangeExtension(fileName, ".jpg"));
                    }
                }
            }
        }

How do I divide in the Linux console?

you can also use perl -e

perl -e 'print 67/8'

How to set the JDK Netbeans runs on?

Thanks to KasunBG's tip, I found the solution in the "suggested" link, update the following file (replace 7.x with your Netbeans version) :

C:\Program Files\NetBeans 7.x\etc\netbeans.conf

Change the following line to point it where your java installation is :

netbeans_jdkhome="C:\Program Files\Java\jdk1.7xxxxx"

You may need Administrator privileges to edit netbeans.conf

Convert LocalDate to LocalDateTime or java.sql.Timestamp

function call asStartOfDay() on java.time.LocalDate object returns a java.time.LocalDateTime object

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

I'll just try to answer the question but my examples very simple because I'm new at mvc. Hope this help somebody.

    [HttpPost]  ///This function is in my controller class
    public ActionResult Delete(string txtDelete)
    {
        int _id = Convert.ToInt32(txtDelete); // put your code           
    }

This code is in my controller's cshtml

  >   @using (Html.BeginForm("Delete", "LibraryManagement"))
 {
<button>Delete</button>
@Html.Label("Enter an ID number");
@Html.TextBox("txtDelete")  }  

Just make sure the textbox name and your controller's function input are the same name and type(string).This way, your function get the textbox input.

Is there a simple way to remove unused dependencies from a maven pom.xml?

You can use dependency:analyze -DignoreNonCompile

This will print a list of used undeclared and unused declared dependencies (while ignoring runtime/provided/test/system scopes for unused dependency analysis.)

** Be careful while using this, some libraries used at runtime are considered as unused **

For more details refer this link

How to get main div container to align to centre?

You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.

UIButton Image + Text IOS

Use this code:

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(0, 10, 200, 52)];
[sampleButton setTitle:@"Button Title" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];
[sampleButton setBackgroundImage:[[UIImage imageNamed:@"redButton.png"] 
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[sampleButton addTarget:self action:@selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton]

Function passed as template argument

Yes, it is valid.

As for making it work with functors as well, the usual solution is something like this instead:

template <typename F>
void doOperation(F f)
{
  int temp=0;
  f(temp);
  std::cout << "Result is " << temp << std::endl;
}

which can now be called as either:

doOperation(add2);
doOperation(add3());

See it live

The problem with this is that if it makes it tricky for the compiler to inline the call to add2, since all the compiler knows is that a function pointer type void (*)(int &) is being passed to doOperation. (But add3, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3 is passed to the function, which means that the function to call is add3::operator(), and not just some unknown function pointer.)

Show space, tab, CRLF characters in editor of Visual Studio

My problem was hitting CTRL+F and space

This marked all spaces brown. Spent 10 minutes to "turn it off" :P

Java - How to access an ArrayList of another class?

You can do this by providing in class numbers:

  • A method that returns the ArrayList object itself.
  • A method that returns a non-modifiable wrapper of the ArrayList. This prevents modification to the list without the knowledge of the class numbers.
  • Methods that provide the set of operations you want to support from class numbers. This allows class numbers to control the set of operations supported.

By the way, there is a strong convention that Java class names are uppercased.

Case 1 (simple getter):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return list; }
      ...
}

Case 2 (non-modifiable wrapper):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return Collections.unmodifiableList( list ); }
      ...
}

Case 3 (specific methods):

public class Numbers {
      private List<Integer> list;
      public void addToList( int i ) { list.add(i); }
      public int getValueAtIndex( int index ) { return list.get( index ); }
      ...
}

How to check if anonymous object has a method?

I know this is an old question, but I am surprised that all answers ensure that the method exists and it is a function, when the OP does only want to check for existence. To know it is a function (as many have stated) you may use:

typeof myObj.prop2 === 'function'

But you may also use as a condition:

typeof myObj.prop2

Or even:

myObj.prop2

This is so because a function evaluates to true and undefined evaluates to false. So if you know that if the member exists it may only be a function, you can use:

if(myObj.prop2) {
  <we have prop2>
}

Or in an expression:

myObj.prop2 ? <exists computation> : <no prop2 computation>

Including another class in SCSS

Combine Mixin with Extend

I just stumbled upon a combination of Mixin and Extend:

reused blocks:

.block1 { box-shadow: 0 5px 10px #000; }

.block2 { box-shadow: 5px 0 10px #000; }

.block3 { box-shadow: 0 0 1px #000; }

dynamic mixin:

@mixin customExtend($class){ @extend .#{$class}; }

use mixin:

like: @include customExtend(block1);

h1 {color: fff; @include customExtend(block2);}

Sass will compile only the mixins content to the extended blocks, which makes it able to combine blocks without generating duplicate code. The Extend logic only puts the classname of the Mixin import location in the block1, ..., ... {box-shadow: 0 5px 10px #000;}

jQuery/JavaScript: accessing contents of an iframe

This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar.navbar-default\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}

How to calculate the IP range when the IP address and the netmask is given?

Input: 192.168.0.1/25

The mask is this part: /25

To find the network address do the following:

  • Subtract the mask from the ip length (32 - mask) = 32 - 25 = 7 and take those bits from the right

  • In the given ip address I.e: 192.168.0.1 in binary is: 11111111 11111111 00000000 00000001 Now, taking 7 bits from right '0' 1111111 11111111 00000000 00000000 Which in decimal is: 192.168.0.0 (this is the network address)

To find first valid/usable ip address add +1 to network address I.e: 192.168.0.1

To find the last/broadcast address the procedure is same as that of finding network address but here you have to make (32-mask) bits from right to '1'

I.e: 11111111 11111111 00000000 01111111 Which in decimal is 192.168.0.127

To find the last valid/usable ip address subtract 1 from the broadcast address I.e: 192.168.0.126

sql server Get the FULL month name from a date

If you are using SQL Server 2012 or later, you can use:

SELECT FORMAT(MyDate, 'MMMM dd yyyy')

You can view the documentation for more information on the format.

stale element reference: element is not attached to the page document

In my case, I had a page where it was an input type='date' whose reference I had got on page load, but When I tried to interact with it, it showed this exception and that was quite meaningful as Javascript had manipulated my control hence it was detached from the document and I had to re-get its reference after the javascript had performed its job with the control. So, this is how my code looked before the exception:

if (elemDate != null)
{ 
    elemDate.Clear(); 
    elemDate.SendKeys(model.Age);
}

Code after the exception was raised:

int tries = 0;
do
{
    try
    {
        tries++;
        if (elemDate != null)
        {
            // these lines were causing the exception so I had break after these are successfully executed because if they are executed that means the control was found and attached to the document and we have taken the reference of it again.
            elemDate.Clear();
            elemDate.SendKeys(model.Age);
            break;
        }
    }
    catch (StaleElementReferenceException)
    {
        System.Threading.Thread.Sleep(10); // put minor fake delay so Javascript on page does its actions with controls
        elemDate = driver.FindElement(By.Id(dateId));
    }
} while (tries < 3); // Try it three times.

So, Now you can perform further actions with your code or you can quit the driver if it was unsuccessful in getting the control to work.

if(tries > 2)
{
   // element was not found, find out what is causing the control detachment.
   // driver.Quit();
   return;
}

// Hurray!! Control was attached and actions were performed.
// Do something with it...

Something that I have learnt so far is, catching exceptions to know about successful code execution is not a good idea, But, I had to do it and I found this work-around to be working well in this case.

PS: After writing all this, I just noticed the tags that this thread was for java. This code sample is just for demonstration purpose, It might help people who have issue in C# language. Or it can be easily translated to java as it doesn't have much C# specific code.

How to use target in location.href

<a href="url" target="_blank"> <input type="button" value="fake button" /> </a>

How to add a bot to a Telegram Group?

Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.

Old answer:

  1. Create a new group from the menu. Don't add any bots yet
  2. Find the bot (for instance you can go to Contacts and search for it)
  3. Tap to open
  4. Tap the bot name on the top bar. Your page becomes like this: Telegram bot settings
  5. Now, tap the triple ... and you will get the Add to Group button: Adding the bot
  6. Now select your group and add the bot - and confirm the addition

What is the correct way to restore a deleted file from SVN?

The problem with doing an svn merge as suggested by Sean Bright is that is reintroduces other changes made in the same revision as the deletion. An svn copy is a more targeted operation that will only affect the deleted files.

Using Tortoise SVN you can resurrect a file that has been deleted from your working copy directory and from later SVN revisions, via a svn copy as follows:

  • Browse to the working copy folder that previously contained the file.
  • Right click on the folder in Explorer, go to TortoiseSVN -> Show log.
  • Right click on the revision number just prior to the revision that deleted the file and select "Browse repository".
  • Right click on the deleted file and select "Copy to working copy..." and save.

The deleted file will now be in the working copy folder. To re-add it back to SVN, right click on the restored file and select SVN Commit.

NB: This method will preserve the previous history of the restored file, however to see the prior history in the TortoiseSVN log you need to make sure "Stop on copy/rename" is unchecked in the Log messages dialog.

Disable same origin policy in Chrome

You can use this chrome plugin called "Allow-Control-Allow-Origin: *" ... It make it a dead simple and work very well. check it here: *

Chrome extenstion

The result of a query cannot be enumerated more than once

Try replacing this

var query = context.Search(id, searchText);

with

var query = context.Search(id, searchText).tolist();

and everything will work well.

Android WSDL/SOAP service client

I have just completed a android App about wsdl,i have some tips to append:

1.the most important resource is www.wsdl2code.com

2.you can take you username and password with header, which encoded with Base64,such as :

        String USERNAME = "yourUsername";
    String PASSWORD = "yourPassWord";
    StringBuffer auth = new StringBuffer(USERNAME);
    auth.append(':').append(PASSWORD);
    byte[] raw = auth.toString().getBytes();
    auth.setLength(0);
    auth.append("Basic ");
    org.kobjects.base64.Base64.encode(raw, 0, raw.length, auth);
    List<HeaderProperty> headers = new ArrayList<HeaderProperty>();
    headers.add(new HeaderProperty("Authorization", auth.toString())); // "Basic V1M6"));

    Vectordianzhan response = bydWs.getDianzhans(headers);

3.somethimes,you are not sure either ANDROID code or webserver is wrong, then debug is important.in the sample , catching "XmlPullParserException" ,log "requestDump" and "responseDump"in the exception.additionally, you should catch the IP package with adb.

    try {
    Logg.i(TAG, "2  ");
    Object response = androidHttpTransport.call(SOAP_ACTION, envelope, headers); 
    Logg.i(TAG, "requestDump: " + androidHttpTransport.requestDump);
    Logg.i(TAG, "responseDump: "+ androidHttpTransport.responseDump);
    Logg.i(TAG, "3");
} catch (IOException e) {
    Logg.i(TAG, "IOException");
} 
catch (XmlPullParserException e) {
     Logg.i(TAG, "requestDump: " + androidHttpTransport.requestDump);
     Logg.i(TAG, "responseDump: "+ androidHttpTransport.responseDump);
     Logg.i(TAG, "XmlPullParserException");
     e.printStackTrace();
}

How can I convert ticks to a date format?

    private void button1_Click(object sender, EventArgs e)
    {
        long myTicks = 633896886277130000;
        DateTime dtime = new DateTime(myTicks);
        MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
    }

Gives

September 27, 2009

Is that what you need?

I don't see how that format is necessarily easy to work with in SQL queries, though.

How to return more than one value from a function in Python?

You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly

How to show/hide if variable is null

To clarify, the above example does work, my code in the example did not work for unrelated reasons.

If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

The following will cause the div to show:

$scope.myvar = "Hello World";

or

$scope.myvar = true;

The following will hide the div:

$scope.myvar = null;

or

$scope.myvar = false;

Doing HTTP requests FROM Laravel to an external API

As of Laravel v7.X, the framework now comes with a minimal API wrapped around the Guzzle HTTP client. It provides an easy way to make get, post, put, patch, and delete requests using the HTTP Client:

use Illuminate\Support\Facades\Http;

$response = Http::get('http://test.com');
$response = Http::post('http://test.com');
$response = Http::put('http://test.com');
$response = Http::patch('http://test.com');
$response = Http::delete('http://test.com');

You can manage responses using the set of methods provided by the Illuminate\Http\Client\Response instance returned.

$response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

Please note that you will, of course, need to install Guzzle like so:

composer require guzzlehttp/guzzle

There are a lot more helpful features built-in and you can find out more about these set of the feature here: https://laravel.com/docs/7.x/http-client

This is definitely now the easiest way to make external API calls within Laravel.

How to update a value, given a key in a hashmap?

Use Java8 built in fuction 'computeIfPresent'

Example:

public class ExampleToUpdateMapValue {

    public static void main(String[] args) {
        Map<String,String> bookAuthors = new TreeMap<>();
        bookAuthors.put("Genesis","Moses");
        bookAuthors.put("Joshua","Joshua");
        bookAuthors.put("Judges","Samuel");

        System.out.println("---------------------Before----------------------");
        bookAuthors.entrySet().stream().forEach(System.out::println);
        // To update the existing value using Java 8
        bookAuthors.computeIfPresent("Judges", (k,v) -> v = "Samuel/Nathan/Gad");

        System.out.println("---------------------After----------------------");
        bookAuthors.entrySet().stream().forEach(System.out::println);
    }
}

Creating an iframe with given HTML dynamically

I know this is an old question but I thought I would provide an example using the srcdoc attribute as this is now widely supported and this is question is viewed often.

Using the srcdoc attribute, you can provide inline HTML to embed. It overrides the src attribute if supported. The browser will fall back to the src attribute if unsupported.

I would also recommend using the sandbox attribute to apply extra restrictions to the content in the frame. This is especially important if the HTML is not your own.

_x000D_
_x000D_
const iframe = document.createElement('iframe');_x000D_
const html = '<body>Foo</body>';_x000D_
iframe.srcdoc = html;_x000D_
iframe.sandbox = '';_x000D_
document.body.appendChild(iframe);
_x000D_
_x000D_
_x000D_

If you need to support older browsers, you can check for srcdoc support and fallback to one of the other methods from other answers.

_x000D_
_x000D_
function setIframeHTML(iframe, html) {_x000D_
  if (typeof iframe.srcdoc !== 'undefined') {_x000D_
    iframe.srcdoc = html;_x000D_
  } else {_x000D_
    iframe.sandbox = 'allow-same-origin';_x000D_
    iframe.contentWindow.document.open();_x000D_
    iframe.contentWindow.document.write(html);_x000D_
    iframe.contentWindow.document.close();_x000D_
  }_x000D_
}_x000D_
_x000D_
var iframe = document.createElement('iframe');_x000D_
iframe.sandbox = '';_x000D_
var html = '<body>Foo</body>';_x000D_
_x000D_
document.body.appendChild(iframe);_x000D_
setIframeHTML(iframe, html);
_x000D_
_x000D_
_x000D_

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

What does DIM stand for in Visual Basic and BASIC?

Variable declaration. Initially, it was short for "dimension", which is not a term that is used in programming (outside of this specific keyword) to any significant degree.

http://in.answers.yahoo.com/question/index?qid=20090310095555AANmiAZ

How to initialize HashSet values by construction?

This is an elegant solution:

public static final <T> Set<T> makeSet(@SuppressWarnings("unchecked") T... o) {
        return new HashSet<T>() {
            private static final long serialVersionUID = -3634958843858172518L;
            {
                for (T x : o)
                   add(x);
            }
        };
}

Invalid http_host header

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart

How to detect the physical connected state of a network cable/connector?

You can use ethtool:

$ sudo ethtool eth0
Settings for eth0:
    Supported ports: [ TP ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Full
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Full
    Advertised auto-negotiation: Yes
    Speed: 1000Mb/s
    Duplex: Full
    Port: Twisted Pair
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
    Supports Wake-on: umbg
    Wake-on: g
    Current message level: 0x00000007 (7)
    Link detected: yes

To only get the Link status you can use grep:

$ sudo ethtool eth0 | grep Link
    Link detected: yes

Enum ToString with user friendly strings

I do this with extension methods:

public enum ErrorLevel
{
  None,
  Low,
  High,
  SoylentGreen
}

public static class ErrorLevelExtensions
{
  public static string ToFriendlyString(this ErrorLevel me)
  {
    switch(me)
    {
      case ErrorLevel.None:
        return "Everything is OK";
      case ErrorLevel.Low:
        return "SNAFU, if you know what I mean.";
      case ErrorLevel.High:
        return "Reaching TARFU levels";
      case ErrorLevel.SoylentGreen:
        return "ITS PEOPLE!!!!";
      default:
        return "Get your damn dirty hands off me you FILTHY APE!";
    }
  }
}

Error: Argument is not a function, got undefined

?med's second point was my pitfall but just for the record, maybe it's helping someone somewhere:

I had the same problem and just before I went nuts I discovered that I had forgotten to include my controller script.

As my app is based on ASP.Net MVC I decided to keep myself sane by inserting the following snippet in my App_Start/BundleConfig.cs

bundles.Add(new ScriptBundle("~/app").Include(
                "~/app/app.js",
                "~/app/controllers/*.js",
                "~/app/services/*.js" ));

and in Layout.cshtml

<head>
...
   @Scripts.Render("~/app")
...
</head>

Now I won't have to think about including the files manually ever again. In hindsight I really should have done this when setting up the project...

Querying DynamoDB by date

Updated Answer:

DynamoDB allows for specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.

For the use case in this question, you would want to use a global secondary index on the "CreatedAt" field.

For more on DynamoDB secondary indexes see the secondary index documentation

Original Answer:

DynamoDB does not allow indexed lookups on the range key only. The hash key is required such that the service knows which partition to look in to find the data.

You can of course perform a scan operation to filter by the date value, however this would require a full table scan, so it is not ideal.

If you need to perform an indexed lookup of records by time across multiple primary keys, DynamoDB might not be the ideal service for you to use, or you might need to utilize a separate table (either in DynamoDB or a relational store) to store item metadata that you can perform an indexed lookup against.

How to dockerize maven project? and how many ways to accomplish it?

Working example.

This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.

Question originally posted 4 years ago.

1. Generate an application

Use the spring initializer to generate a demo app

https://start.spring.io/

enter image description here

Extract the zip archive locally

2. Create a Dockerfile

#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package

#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]

Note

  • This example uses a multi-stage build. The first stage is used to build the code. The second stage only contains the built jar and a JRE to run it (note how jar is copied between stages).

3. Build the image

docker build -t demo .

4. Run the image

$ docker run --rm -it demo:latest

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-02-22 17:18:57.835  INFO 1 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837  INFO 1 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294  INFO 1 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 0.711 seconds (JVM running for 1.035)

Misc

Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.

Update (2019-02-07)

This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.

Option 1: Multi-stage build

This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.

The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.

FROM maven:3.5-jdk-8 AS build  
COPY src /usr/src/app/src  
COPY pom.xml /usr/src/app  
RUN mvn -f /usr/src/app/pom.xml clean package

FROM gcr.io/distroless/java  
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar  
EXPOSE 8080  
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]  

Note:

  • I'm using Google's distroless base image, which strives to provide just enough run-time for a java app.

Option 2: Jib

I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)

https://github.com/GoogleContainerTools/jib

The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.


Original answer (Included for completeness, but written ages ago)

Try using the new official images, there's one for Maven

https://registry.hub.docker.com/_/maven/

The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.

Example 1 - Maven running within a container

The following command runs your Maven build inside a container:

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       maven:3.2-jdk-7 \
       mvn clean install

Notes:

  • The neat thing about this approach is that all software is installed and running within the container. Only need docker on the host machine.
  • See Dockerfile for this version

Example 2 - Use Nexus to cache files

Run the Nexus container

docker run -d -p 8081:8081 --name nexus sonatype/nexus

Create a "settings.xml" file:

<settings>
  <mirrors>
    <mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://nexus:8081/content/groups/public/</url>
    </mirror>
  </mirrors>
</settings>

Now run Maven linking to the nexus container, so that dependencies will be cached

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       --link nexus:nexus \
       maven:3.2-jdk-7 \
       mvn -s settings.xml clean install

Notes:

  • An advantage of running Nexus in the background is that other 3rd party repositories can be managed via the admin URL transparently to the Maven builds running in local containers.

How to install PyQt4 on Windows using pip?

QT no longer supports PyQt4, but you can install PyQt5 with pip:

pip install PyQt5

Center text output from Graphics.DrawString()

Here's some code. This assumes you are doing this on a form, or a UserControl.

Graphics g = this.CreateGraphics();
SizeF size = g.MeasureString("string to measure");

int nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));
int nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));

From your post, it sounds like the ClientRectangle part (as in, you're not using it) is what's giving you difficulty.

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

It may sound banal, but for me Build > Clean Project fixed this error without any other changes.

Passing arguments to "make run"

Another trick I use is the -n flag, which tells make to do a dry run. For example,

$ make install -n 
# Outputs the string: helm install stable/airflow --name airflow -f values.yaml
$ eval $(make install -n) --dry-run --debug
# Runs: helm install stable/airflow --name airflow -f values.yaml --dry-run --debug

Python: Assign Value if None Exists

IfLoop's answer (and MatToufoutu's comment) work great for standalone variables, but I wanted to provide an answer for anyone trying to do something similar for individual entries in lists, tuples, or dictionaries.

Dictionaries

existing_dict = {"spam": 1, "eggs": 2}
existing_dict["foo"] = existing_dict["foo"] if "foo" in existing_dict else 3

Returns {"spam": 1, "eggs": 2, "foo": 3}

Lists

existing_list = ["spam","eggs"]
existing_list = existing_list if len(existing_list)==3 else 
                existing_list + ["foo"]

Returns ["spam", "eggs", "foo"]

Tuples

existing_tuple = ("spam","eggs")
existing_tuple = existing_tuple if len(existing_tuple)==3 else 
                 existing_tuple + ("foo",)

Returns ("spam", "eggs", "foo")

(Don't forget the comma in ("foo",) to define a "single" tuple.)

The lists and tuples solution will be more complicated if you want to do more than just check for length and append to the end. Nonetheless, this gives a flavor of what you can do.

A process crashed in windows .. Crash dump location

a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).

If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP

Creating random colour in Java?

Use the random library:

import java.util.Random;

Then create a random generator:

Random rand = new Random();

As colours are separated into red green and blue, you can create a new random colour by creating random primary colours:

// Java 'Color' class takes 3 floats, from 0 to 1.
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();

Then to finally create the colour, pass the primary colours into the constructor:

Color randomColor = new Color(r, g, b);

You can also create different random effects using this method, such as creating random colours with more emphasis on certain colours ... pass in less green and blue to produce a "pinker" random colour.

// Will produce a random colour with more red in it (usually "pink-ish")
float r = rand.nextFloat();
float g = rand.nextFloat() / 2f;
float b = rand.nextFloat() / 2f;

Or to ensure that only "light" colours are generated, you can generate colours that are always > 0.5 of each colour element:

// Will produce only bright / light colours:
float r = rand.nextFloat() / 2f + 0.5;
float g = rand.nextFloat() / 2f + 0.5;
float b = rand.nextFloat() / 2f + 0.5;

There are various other colour functions that can be used with the Color class, such as making the colour brighter:

randomColor.brighter();

An overview of the Color class can be read here: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html

WCF, Service attribute value in the ServiceHost directive could not be found

I got this error when trying to add the Service reference for the first Silverlight enabled WCF in the same solution. I just build the .Web project and it started working..

How do I rename a column in a SQLite database table?

Quoting the sqlite documentation:

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a colum, remove a column, or add or remove constraints from a table.

What you can do of course is, create a new table with the new layout, SELECT * FROM old_table, and fill the new table with the values you'll receive.

jquery toggle slide from left to right and back

There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.

HTML Code:

<div class="text">Lorem ipsum.</div>

JQuery Code:

  $(document).ready(function(){
    var DivWidth = $(".text").width();
    $(".left").click(function(){
      $(".text").animate({
        width: 0
      });
    });
    $(".right").click(function(){
      $(".text").animate({
        width: DivWidth
      });
    });
  });

You can see an example here: How to slide toggle a DIV from Left to Right?

How do I compare 2 rows from the same table (SQL Server)?

You can join a table to itself as many times as you require, it is called a self join.

An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.

SELECT a.SelfJoinTableID
FROM   dbo.SelfJoinTable a
       INNER JOIN dbo.SelfJoinTable b
         ON a.SelfJoinTableID = b.SelfJoinTableID
       INNER JOIN dbo.SelfJoinTable c
         ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE  a.Status = 'Status to filter a'
       AND b.Status = 'Status to filter b'
       AND c.Status = 'Status to filter c' 

JQuery - how to select dropdown item based on value

_x000D_
_x000D_
$('#dropdownid').val('selectedvalue');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id='dropdownid'>_x000D_
    <option value=''>- Please choose -</option>_x000D_
    <option value='1'>1</option>_x000D_
    <option value='2'>2</option>_x000D_
    <option value='selectedvalue'>There we go!</option>_x000D_
    <option value='3'>3</option>_x000D_
    <option value='4'>4</option>_x000D_
    <option value='5'>5</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

HTTP Error 503. The service is unavailable. App pool stops on accessing website

I was experiencing this error and in my case the cause was that some time ago I modified the user password, and the 503 error didn't appears till I restarted the application pool.

So I fixed it setting the new password on Applications Pools / Advanced Settings / Identity / [...] / Set... / Password / Confirm Password

Convert char array to a int number in C

Why not just use atoi? For example:

char myarray[4] = {'-','1','2','3'};

int i = atoi(myarray);

printf("%d\n", i);

Gives me, as expected:

-123

Update: why not - the character array is not null terminated. Doh!

Is it bad to have my virtualenv directory inside my git repository?

Storing the virtualenv directory inside git will, as you noted, allow you to deploy the whole app by just doing a git clone (plus installing and configuring Apache/mod_wsgi). One potentially significant issue with this approach is that on Linux the full path gets hard-coded in the venv's activate, django-admin.py, easy_install, and pip scripts. This means your virtualenv won't entirely work if you want to use a different path, perhaps to run multiple virtual hosts on the same server. I think the website may actually work with the paths wrong in those files, but you would have problems the next time you tried to run pip.

The solution, already given, is to store enough information in git so that during the deploy you can create the virtualenv and do the necessary pip installs. Typically people run pip freeze to get the list then store it in a file named requirements.txt. It can be loaded with pip install -r requirements.txt. RyanBrady already showed how you can string the deploy statements in a single line:

# before 15.1.0
virtualenv --no-site-packages --distribute .env &&\
    source .env/bin/activate &&\
    pip install -r requirements.txt

# after deprecation of some arguments in 15.1.0
virtualenv .env && source .env/bin/activate && pip install -r requirements.txt

Personally, I just put these in a shell script that I run after doing the git clone or git pull.

Storing the virtualenv directory also makes it a bit trickier to handle pip upgrades, as you'll have to manually add/remove and commit the files resulting from the upgrade. With a requirements.txt file, you just change the appropriate lines in requirements.txt and re-run pip install -r requirements.txt. As already noted, this also reduces "commit spam".

What is the default boolean value in C#?

The default value for bool is false. See this table for a great reference on default values. The only reason it would not be false when you check it is if you initialize/set it to true.

Converting Numpy Array to OpenCV Array

This is what worked for me...

import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)

error: command 'gcc' failed with exit status 1 on CentOS

How i solved

# yum update
# yum install -y https://centos7.iuscommunity.org/ius-release.rpm
# yum install -y python36u python36u-libs python36u-devel python36u-pip
# pip3.6 install pipenv

I hope it will help Someone to resolve "gcc" issue.

Is it possible to play music during calls so that the partner can hear it ? Android

Note: You can play back the audio data only to the standard output device.
Currently, that is the mobile device speaker or a Bluetooth headset. You 
cannot play sound files in the conversation audio during a call.

See official link 

http://developer.android.com/guide/topics/media/mediaplayer.html

How do you beta test an iphone app?

Diawi Alternatives

Since diawi.com have added some limitations for free accounds.

Next best available and easy to use alternative is

Microsoft

https://appcenter.ms

Google

https://firebase.google.com/docs/app-distribution/ios/distribute-console

Others

https://hockeyapp.net/

http://buildtry.com

Happy build sharing!

What is the fastest factorial function in JavaScript?

Here is one using newer javascript functions fill, map, reduce and constructor (and fat arrow syntax):

Math.factorial = n => n === 0 ? 1 : Array(n).fill(null).map((e,i)=>i+1).reduce((p,c)=>p*c)

Edit: updated to handle n === 0

How to reset the use/password of jenkins on windows?

This is for windows environment:

I got the Initial Admin password under C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword

I was able to login with user "admin" and above password. Then under Jenkins> people I edited the password of the user and clicked on apply to reflect the changes.

Fatal error: Call to undefined function socket_create()

I got this error when my .env file was not set up properly. Make sure you have a .env file with valid database login credentials.

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

Counting duplicates in Excel

If you are not looking for Excel formula, Its easy from the Menu

Data Menu --> Remove Duplicates would alert, if there are no duplicates

Also, if you see the count and reduced after removing duplicates...

How do I automatically update a timestamp in PostgreSQL

To populate the column during insert, use a DEFAULT value:

CREATE TABLE users (
  id serial not null,
  firstname varchar(100),
  middlename varchar(100),
  lastname varchar(100),
  email varchar(200),
  timestamp timestamp default current_timestamp
)

Note that the value for that column can explicitly be overwritten by supplying a value in the INSERT statement. If you want to prevent that you do need a trigger.

You also need a trigger if you need to update that column whenever the row is updated (as mentioned by E.J. Brennan)

Note that using reserved words for column names is usually not a good idea. You should find a different name than timestamp

Get a random item from a JavaScript array

var random = items[Math.floor(Math.random()*items.length)]

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

How to push to History in React Router v4?

Here's my hack (this is my root-level file, with a little redux mixed in there - though I'm not using react-router-redux):

const store = configureStore()
const customHistory = createBrowserHistory({
  basename: config.urlBasename || ''
})

ReactDOM.render(
  <Provider store={store}>
    <Router history={customHistory}>
      <Route component={({history}) => {
        window.appHistory = history
        return (
          <App />
        )
      }}/>
    </Router>
  </Provider>,
  document.getElementById('root')
)

I can then use window.appHistory.push() anywhere I want (for example, in my redux store functions/thunks/sagas, etc) I had hoped I could just use window.customHistory.push() but for some reason react-router never seemed to update even though the url changed. But this way I have the EXACT instance react-router uses. I don't love putting stuff in the global scope, and this is one of the few things I'd do that with. But it's better than any other alternative I've seen IMO.

when do you need .ascx files and how would you use them?

ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:

Implement Validation for WPF TextBoxes

When it comes to Muhammad Mehdi's answer, it is better to do:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
     Regex regex = new Regex ( "[^0-9]+" );
     if(regex.IsMatch(e.Text))
     {
         MessageBox.Show("Error");
     }
}

Because when comparing with the TextCompositionEventArgs it gets also the last character, while with the textbox.Text it does not. With textbox, the error will show after next inserted character.

Case insensitive string compare in LINQ-to-SQL

I tried this using Lambda expression, and it worked.

List<MyList>.Any (x => (String.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)) && (x.Type == qbType) );

Passing data to a jQuery UI Dialog

After SEVERAL HOURS of try/catch I finally came with this working example, its working on AJAX POST with new rows appends to the TABLE on the fly (that was my real problem):

Tha magic came with link this:

<a href="#" onclick="removecompany(this);return false;" id="remove_13">remove</a>
<a href="#" onclick="removecompany(this);return false;" id="remove_14">remove</a>
<a href="#" onclick="removecompany(this);return false;" id="remove_15">remove</a>

This is the final working with AJAX POST and Jquery Dialog:

  <script type= "text/javascript">/*<![CDATA[*/
    var $k = jQuery.noConflict();  //this is for NO-CONFLICT with scriptaculous
     function removecompany(link){
        companyid = link.id.replace('remove_', '');
    $k("#removedialog").dialog({
                bgiframe: true,
                resizable: false,
                height:140,
                autoOpen:false,
                modal: true,
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.5
                },
                buttons: {
                    'Are you sure ?': function() {
                        $k(this).dialog('close');
                        alert(companyid);
                        $k.ajax({
                              type: "post",
                              url: "../ra/removecompany.php",
                              dataType: "json",
                              data: {
                                    'companyid' : companyid
                                    },
                              success: function(data) {
                                    //alert(data);
                                    if(data.success)
                                    {
                                        //alert('success'); 
                                        $k('#companynew'+companyid).remove();
                                    }
                          }
                        }); // End ajax method
                    },
                    Cancel: function() {
                        $k(this).dialog('close');
                    }
                }
            });
            $k("#removedialog").dialog('open'); 
            //return false;
     }
    /*]]>*/</script>
    <div id="removedialog" title="Remove a Company?">
        <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
        This company will be permanently deleted and cannot be recovered. Are you sure?</p>
    </div>

How to check type of files without extensions in python?

In the case of images, you can use the imghdr module.

>>> import imghdr
>>> imghdr.what('8e5d7e9d873e2a9db0e31f9dfc11cf47')  # You can pass a file name or a file object as first param. See doc for optional 2nd param.
'png'

Python 2 imghdr doc
Python 3 imghdr doc

How to increment a pointer address and pointer's value?

With regards to "How to increment a pointer address and pointer's value?" I think that ++(*p++); is actually well defined and does what you're asking for, e.g.:

#include <stdio.h>

int main() {
  int a = 100;
  int *p = &a;
  printf("%p\n",(void*)p);
  ++(*p++);
  printf("%p\n",(void*)p);
  printf("%d\n",a);
  return 0;
}

It's not modifying the same thing twice before a sequence point. I don't think it's good style though for most uses - it's a little too cryptic for my liking.

Activate a virtualenv with a Python script

For python2/3, Using below code snippet we can activate virtual env.

activate_this = "/home/<--path-->/<--virtual env name -->/bin/activate_this.py" #for ubuntu
activate_this = "D:\<-- path -->\<--virtual env name -->\Scripts\\activate_this.py" #for windows
with open(activate_this) as f:
    code = compile(f.read(), activate_this, 'exec')
    exec(code, dict(__file__=activate_this))

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

Returning http status code from Web Api controller

If you need to return an IHttpActionResult and want to return the error code plus a message, use:

return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotModified, "Error message here"));

Can we call the function written in one JavaScript in another JS file?

For those who want to do this in Node.js (running scripts on the server-side) another option is to use require and module.exports. Here is a short example on how to create a module and export it for use elsewhere:

file1.js

const print = (string) => {
    console.log(string);
};

exports.print = print;

file2.js

const file1 = require('./file1');

function printOne() {
    file1.print("one");
};

How to find a parent with a known class in jQuery?

<div id="412412412" class="input-group date">
     <div class="input-group-prepend">
          <button class="btn btn-danger" type="button">Button Click</button>
          <input type="text" class="form-control" value="">
      </div>
</div>

In my situation, i use this code:

$(this).parent().closest('.date').attr('id')

Hope this help someone.

How do I remove a single file from the staging area (undo git add)?

If I understand the question correctly, you simply want to "undo" the git add that was done for that file.

If you need to remove a single file from the staging area, use

git reset HEAD -- <file>

If you need to remove a whole directory (folder) from the staging area, use

git reset HEAD -- <directoryName>

Your modifications will be kept. When you run git status the file will once again show up as modified but not yet staged.

See the git reset man page for details.

Double precision floating values in Python?

Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..

import random
from decimal import Decimal

GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

Convert UTC datetime string to local datetime

import datetime

def utc_str_to_local_str(utc_str: str, utc_format: str, local_format: str):
    """
    :param utc_str: UTC time string
    :param utc_format: format of UTC time string
    :param local_format: format of local time string
    :return: local time string
    """
    temp1 = datetime.datetime.strptime(utc_str, utc_format)
    temp2 = temp1.replace(tzinfo=datetime.timezone.utc)
    local_time = temp2.astimezone()
    return local_time.strftime(local_format)

utc = '2018-10-17T00:00:00.111Z'
utc_fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
local_fmt = '%Y-%m-%dT%H:%M:%S+08:00'
local_string = utc_str_to_local_str(utc, utc_fmt, local_fmt)
print(local_string)   # 2018-10-17T08:00:00+08:00

for example, my timezone is '+08:00'. input utc = 2018-10-17T00:00:00.111Z, then I will get output = 2018-10-17T08:00:00+08:00

How to deploy correctly when using Composer's develop / production switch?

On production servers I rename vendor to vendor-<datetime>, and during deployment will have two vendor dirs.

A HTTP cookie causes my system to choose the new vendor autoload.php, and after testing I do a fully atomic/instant switch between them to disable the old vendor dir for all future requests, then I delete the previous dir a few days later.

This avoids any problem caused by filesystem caches I'm using in apache/php, and also allows any active PHP code to continue using the previous vendor dir.


Despite other answers recommending against it, I personally run composer install on the server, since this is faster than rsync from my staging area (a VM on my laptop).

I use --no-dev --no-scripts --optimize-autoloader. You should read the docs for each one to check if this is appropriate on your environment.

updating table rows in postgres using subquery

Postgres allows:

UPDATE dummy
SET customer=subquery.customer,
    address=subquery.address,
    partn=subquery.partn
FROM (SELECT address_id, customer, address, partn
      FROM  /* big hairy SQL */ ...) AS subquery
WHERE dummy.address_id=subquery.address_id;

This syntax is not standard SQL, but it is much more convenient for this type of query than standard SQL. I believe Oracle (at least) accepts something similar.

Creating a batch file, for simple javac and java command execution

you want these four lines of code in your Run.bat:

@echo off          //this makes it so you have an empty cmd window on startup
javac Main.java    //this compiles the .java into a .class
java Main          // this runs the .class file
pause              //this prevents the window from instantly closing after program end

Rails: Why "sudo" command is not recognized?

sudo is a command for Linux so it cant be used in windows so you will get that error

Nginx -- static file serving confusion with root & alias

as say as @treecoder

In case of the root directive, full path is appended to the root including the location part, whereas in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

A picture is worth a thousand words

for root:

enter image description here

for alias:

enter image description here

When is the @JsonProperty property used and what is it used for?

As you know, this is all about serialize and desalinize an object. Suppose there is an object:

public class Parameter {
  public String _name;
  public String _value; 
}

The serialization of this object is:

{
  "_name": "...",
  "_value": "..."
}

The name of variable is directly used to serialize data. If you are about to remove system api from system implementation, in some cases, you have to rename variable in serialization/deserialization. @JsonProperty is a meta data to tell serializer how to serial object. It is used to:

  • variable name
  • access (READ, WRITE)
  • default value
  • required/optional

from example:

public class Parameter {
  @JsonProperty(
        value="Name",
        required=true,
        defaultValue="No name",
        access= Access.READ_WRITE)
  public String _name;
  @JsonProperty(
        value="Value",
        required=true,
        defaultValue="Empty",
        access= Access.READ_WRITE)
  public String _value; 
}

CSS @font-face not working with Firefox, but working with Chrome and IE

If you are trying to import external fonts you face one of the most common problem with your Firefox and other browser. Some time your font working well in google Chrome or one of the other browser but not in every browser.

There have lots of reason for this type of error one of the biggest reason behind this problem is previous per-defined font. You need to add !important keyword after end of your each line of CSS code as below:

Example:

@font-face
{
    font-family:"Hacen Saudi Arabia" !important;
    src:url("../font/Hacen_Saudi_Arabia.eot?") format("eot") !important;
    src:url("../font/Hacen_Saudi_Arabia.woff") format("woff") !important;
    src: url("../font/Hacen_Saudi_Arabia.ttf") format("truetype") !important;
    src:url("../font/Hacen_Saudi_Arabia.svg#HacenSaudiArabia") format("svg") !important;
}
.sample
{
    font-family:"Hacen Saudi Arabia" !important;
}

Description: Enter above code in your CSS file or code here. In above example replace "Hacen Saudi Arabia" with your font-family and replace url as per your font directory.

If you enter !important in your css code browser automatically focus on this section and override previously used property. For More details visit: https://answerdone.blogspot.com/2017/06/font-face-not-working-solution.html

Store output of sed into a variable

In general,

variable=$(command)

or

variable=`command`

The latter one is the old syntax, prefer $(command).

Note: variable = .... means execute the command variable with the first argument =, the second ....

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

The problem is that I missed out 'db' folder for the dbpath in the command:

C:\mongodb\bin> mongod --directoryperdb --dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongodb.log --logappend -rest --install

Available text color classes in Bootstrap

There are few more classess in Bootstrap 4 (added in recent versions) not mentioned in other answers.

.text-black-50 and .text-white-50 are 50% transparent.

_x000D_
_x000D_
.text-body {_x000D_
  color: #212529 !important;_x000D_
}_x000D_
_x000D_
.text-black-50 {_x000D_
  color: rgba(0, 0, 0, 0.5) !important;_x000D_
}_x000D_
_x000D_
.text-white-50 {_x000D_
  color: rgba(255, 255, 255, 0.5) !important;_x000D_
}_x000D_
_x000D_
/*DEMO*/_x000D_
p{padding:.5rem}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
_x000D_
<p class="text-body">.text-body</p>_x000D_
<p class="text-black-50">.text-black-50</p>_x000D_
<p class="text-white-50 bg-dark">.text-white-50</p>
_x000D_
_x000D_
_x000D_

How can I schedule a job to run a SQL query daily?

Using T-SQL: My job is executing stored procedure. You can easy change @command to run your sql.

EXEC msdb.dbo.sp_add_job  
   @job_name = N'MakeDailyJob',   
   @enabled = 1,   
   @description = N'Procedure execution every day' ; 

 EXEC msdb.dbo.sp_add_jobstep  
    @job_name = N'MakeDailyJob',   
    @step_name = N'Run Procedure',   
    @subsystem = N'TSQL',   
    @command = 'exec BackupFromConfig';

 EXEC msdb.dbo.sp_add_schedule  
    @schedule_name = N'Everyday schedule',   
    @freq_type = 4,  -- daily start
    @freq_interval = 1,
    @active_start_time = '230000' ;   -- start time 23:00:00

 EXEC msdb.dbo.sp_attach_schedule  
   @job_name = N'MakeDailyJob',  
   @schedule_name = N'Everyday schedule' ;

 EXEC msdb.dbo.sp_add_jobserver  
   @job_name = N'MakeDailyJob',  
   @server_name = @@servername ;

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

INSERT INTO [Business]
           ([IsDeleted]
           ,[FirstName]
           ,[LastName]
           ,[LastUpdated]
           ,[LastUpdatedBy])
     VALUES
           (0, 'Joe', 'Thomas', 
           GETDATE(),  <LastUpdatedBy, nvarchar(50),>)

Flexbox and Internet Explorer 11 (display:flex in <html>?)

Here is an example of using flex that also works in Internet Explorer 11 and Chrome.

HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >_x000D_
<title>Flex Test</title>_x000D_
<style>_x000D_
html, body {_x000D_
    margin: 0px;_x000D_
    padding: 0px;_x000D_
    height: 100vh;_x000D_
}_x000D_
.main {_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -ms-flex-direction: row;_x000D_
    flex-direction: row;_x000D_
    align-items: stretch;_x000D_
    min-height: 100vh;_x000D_
}_x000D_
_x000D_
.main::after {_x000D_
  content: '';_x000D_
  height: 100vh;_x000D_
  width: 0;_x000D_
  overflow: hidden;_x000D_
  visibility: hidden;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.left {_x000D_
    width: 200px;_x000D_
    background: #F0F0F0;_x000D_
    flex-shrink: 0;_x000D_
}_x000D_
_x000D_
.right {_x000D_
    flex-grow: 1;_x000D_
    background: yellow;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="main">_x000D_
    <div class="left">_x000D_
        <div style="height: 300px;">_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="right">_x000D_
        <div style="height: 1000px;">_x000D_
            test test test_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Swift Alamofire: How to get the HTTP response status code

I needed to know how to get the actual error code number.

I inherited a project from someone else and I had to get the error codes from a .catch clause that they had previously setup for Alamofire:

} .catch { (error) in

    guard let error = error as? AFError else { return }
    guard let statusCode = error.responseCode else { return }

    print("Alamofire statusCode num is: ", statusCode)
}

Or if you need to get it from the response value follow @mbryzinski's answer

Alamofire ... { (response) in

    guard let error = response.result.error as? AFError else { return }
    guard let statusCode = error.responseCode else { return }

    print("Alamofire statusCode num is: ", statusCode)
})

dropdownlist set selected value in MVC3 Razor

just in case someone comes with this question, this is how I do it, please forget about the repository object, I'm using the Repository Pattern, you can use your object context to retrieve the entities. And also don't pay attention to my entity names, my entity type Action has nothing to do with an MVC Action.

Controller:

ViewBag.ActionStatusId = new SelectList(repository.GetAll<ActionStatus>(), "ActionStatusId", "Name", myAction.ActionStatusId);

Pay attention that the last variable of the SelectList constructor is the selected value (object selectedValue)

Then this is my view to render it:

<div class="editor-label">
   @Html.LabelFor(model => model.ActionStatusId, "ActionStatus")
</div>
<div class="editor-field">
   @Html.DropDownList("ActionStatusId")
   @Html.ValidationMessageFor(model => model.ActionStatusId)
</div> 

I think it is pretty simple, I hope this helps! :)

How to assign a heredoc value to a variable in Bash?

You can avoid a useless use of cat and handle mismatched quotes better with this:

$ read -r -d '' VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF

If you don't quote the variable when you echo it, newlines are lost. Quoting it preserves them:

$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

If you want to use indentation for readability in the source code, use a dash after the less-thans. The indentation must be done using only tabs (no spaces).

$ read -r -d '' VAR <<-'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
    EOF
$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

If, instead, you want to preserve the tabs in the contents of the resulting variable, you need to remove tab from IFS. The terminal marker for the here doc (EOF) must not be indented.

$ IFS='' read -r -d '' VAR <<'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
EOF
$ echo "$VAR"
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''

Tabs can be inserted at the command line by pressing Ctrl-V Tab. If you are using an editor, depending on which one, that may also work or you may have to turn off the feature that automatically converts tabs to spaces.

In vb.net, how to get the column names from a datatable

Do you have access to your database, if so just open it up and look up the column and use an SQL call to retrieve the needed.

A short example on a form to retrieve data from a database table:

Form contain only a GataGridView named DataGrid

Database name: DB.mdf

Table name: DBtable

Column names in table: Name as varchar(50), Age as int, Gender as bit.

Private Sub DatabaseTest_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Public ConString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\{username}\documents\visual studio 2010\Projects\Userapplication prototype v1.0\Userapplication prototype v1.0\Database\DB.mdf;" & "Integrated Security=True;User Instance=True"
    Dim conn As New SqlClient.SqlConnection
    Dim cmd As New SqlClient.SqlCommand
    Dim da As New SqlClient.SqlDataAdapter
    Dim dt As New DataTable
    Dim sSQL As String = String.Empty
    Try
        conn = New SqlClient.SqlConnection(ConString)
        conn.Open() 'connects to the database
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        sSQL = "SELECT * FROM DBtable" 'Sql to be executed
        cmd.CommandText = sSQL 'makes the string a command
        da.SelectCommand = cmd 'puts the command into the sqlDataAdapter
        da.Fill(dt) 'populates the dataTable by performing the command above
        Me.DataGrid.DataSource = dt 'Updates the grid using the populated dataTable

        'the following is only if any errors happen:
        If dt.Rows.Count = 0 Then
            MsgBox("No record found!")
        End If
    Catch ex As Exception
        MsgBox(ErrorToString)
    Finally
        conn.Close() 'closes the connection again so it can be accessed by other users or programs
    End Try
End Sub

This will fetch all the rows and columns from your database table for review.
If you want to only fetch the names just change the sql call with: "SELECT Name FROM DBtable" this way the DataGridView will only show the column names.

I'm only a rookie but i would strongly advise to get rid of theses auto generate wizards. Using SQL you have full access to your database and what happens.
Also one last thing, if your database doesn't use SQLClient just change it to OleDB.

Example: "Dim conn As New SqlClient.SqlConnection" becomes: Dim conn As New OleDb.OleDbConnection

How do I add 24 hours to a unix timestamp in php?

You could use the DateTime class as well:

$timestamp = mktime(15, 30, 00, 3, 28, 2015);

$d = new DateTime();
$d->setTimestamp($timestamp);

Add a Period of 1 Day:

$d->add(new DateInterval('P1D'));
echo $d->format('c');

See DateInterval for more details.

How do I get the current absolute URL in Ruby on Rails?

If by relative, you mean just without the domain, then look into request.domain.

App crashing when trying to use RecyclerView on android 5.0

My problem was in my XML lyout I have an android:animateLayoutChanges set to true and I've called notifyDataSetChanged() on the RecyclerView's adapter in the Java code.

So, I've just removed android:animateLayoutChanges from my layout and that resloved my problem.