Programs & Examples On #Duplication

How to disable a button when an input is empty?

Using constants allows to combine multiple fields for verification:

_x000D_
_x000D_
class LoginFrm extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = {_x000D_
      email: '',_x000D_
      password: '',_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  handleEmailChange = (evt) => {_x000D_
    this.setState({ email: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handlePasswordChange = (evt) => {_x000D_
    this.setState({ password: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handleSubmit = () => {_x000D_
    const { email, password } = this.state;_x000D_
    alert(`Welcome ${email} password: ${password}`);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const { email, password } = this.state;_x000D_
    const enabled =_x000D_
          email.length > 0 &&_x000D_
          password.length > 0;_x000D_
    return (_x000D_
      <form onSubmit={this.handleSubmit}>_x000D_
        <input_x000D_
          type="text"_x000D_
          placeholder="Email"_x000D_
          value={this.state.email}_x000D_
          onChange={this.handleEmailChange}_x000D_
        />_x000D_
        _x000D_
        <input_x000D_
          type="password"_x000D_
          placeholder="Password"_x000D_
          value={this.state.password}_x000D_
          onChange={this.handlePasswordChange}_x000D_
        />_x000D_
        <button disabled={!enabled}>Login</button>_x000D_
      </form>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<LoginFrm />, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<body>_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

enum to string in modern C++11 / C++14 / C++17 and future C++20

You could use a reflection library, like Ponder:

enum class MyEnum
{
    Zero = 0,
    One  = 1,
    Two  = 2
};

ponder::Enum::declare<MyEnum>()
    .value("Zero", MyEnum::Zero)
    .value("One",  MyEnum::One)
    .value("Two",  MyEnum::Two);

ponder::EnumObject zero(MyEnum::Zero);

zero.name(); // -> "Zero"

Check if an element has event listener on it. No jQuery

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

SQL INSERT INTO from multiple tables

I would suggest instead of creating a new table, you just use a view that combines the two tables, this way if any of the data in table 1 or table 2 changes, you don't need to update the third table:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
    FROM    Table1 t1
            INNER JOIN Table2 t2
                ON t1.ID = t2.ID;

If you could have records in one table, and not in the other, then you would need to use a full join:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, ID = ISNULL(t1.ID, t2.ID), t2.Number
    FROM    Table1 t1
            FULL JOIN Table2 t2
                ON t1.ID = t2.ID;

If you know all records will be in table 1 and only some in table 2, then you should use a LEFT JOIN:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
    FROM    Table1 t1
            LEFT JOIN Table2 t2
                ON t1.ID = t2.ID;

If you know all records will be in table 2 and only some in table 2 then you could use a RIGHT JOIN

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
    FROM    Table1 t1
            RIGHT JOIN Table2 t2
                ON t1.ID = t2.ID;

Or just reverse the order of the tables and use a LEFT JOIN (I find this more logical than a right join but it is personal preference):

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
    FROM    Table2 t2
            LEFT JOIN Table1 t1
                ON t1.ID = t2.ID;

Error 1022 - Can't write; duplicate key in table

From the two linksResolved Successfully and Naming Convention, I easily solved this same problem which I faced. i.e., for the foreign key name, give as fk_colName_TableName. This naming convention is non-ambiguous and also makes every ForeignKey in your DB Model unique and you will never get this error.

Error 1022: Can't write; duplicate key in table

Only Add Unique Item To List

If your requirements are to have no duplicates, you should be using a HashSet.

HashSet.Add will return false when the item already exists (if that even matters to you).

You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice (GetHashCode & Equals).

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

I had the same on my project.

I tried " super.setIntegerProperty("loadUrlTimeoutValue", 70000); " but to no avail.

I ensured all files were linked properly [ CSS, JS files etc ], validated the HTML using w3c validator [ http://validator.w3.org/#validate_by_upload ] , and cleaned the project [ Project -> Clean ]

It now loads and executes without the same error.

Hope this helps

Setting an environment variable before a command in Bash is not working for the second command in a pipe

Use a shell script:

#!/bin/bash
# myscript
FOO=bar
somecommand someargs | somecommand2

> ./myscript

Duplicate AssemblyVersion Attribute

My error was that I was also referencing another file in my project, which was also containing a value for the attribute "AssemblyVersion". I removed that attribute from one of the file and it is now working properly.

The key is to make sure that this value is not declared more than once in any file in your project.

Find duplicate records in a table using SQL Server

Try this instead

SELECT MAX(shoppername), COUNT(*) AS cnt
FROM dbo.sales
GROUP BY CHECKSUM(*)
HAVING COUNT(*) > 1

Read about the CHECKSUM function first, as there can be duplicates.

In Javascript, how do I check if an array has duplicate values?

Another approach (also for object/array elements within the array1) could be2:

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also...

1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values

Where to get "UTF-8" string literal in Java?

In case this page comes up in someones web search, as of Java 1.7 you can now use java.nio.charset.StandardCharsets to get access to constant definitions of standard charsets.

How to use the IEqualityComparer

If you want a generic solution without boxing:

public class KeyBasedEqualityComparer<T, TKey> : IEqualityComparer<T>
{
    private readonly Func<T, TKey> _keyGetter;

    public KeyBasedEqualityComparer(Func<T, TKey> keyGetter)
    {
        _keyGetter = keyGetter;
    }

    public bool Equals(T x, T y)
    {
        return EqualityComparer<TKey>.Default.Equals(_keyGetter(x), _keyGetter(y));
    }

    public int GetHashCode(T obj)
    {
        TKey key = _keyGetter(obj);

        return key == null ? 0 : key.GetHashCode();
    }
}

public static class KeyBasedEqualityComparer<T>
{
    public static KeyBasedEqualityComparer<T, TKey> Create<TKey>(Func<T, TKey> keyGetter)
    {
        return new KeyBasedEqualityComparer<T, TKey>(keyGetter);
    }
}

usage:

KeyBasedEqualityComparer<Class_reglement>.Create(x => x.Numf)

Converting Integer to Long

If you don't know the exact class of your number (Integer, Long, Double, whatever), you can cast to Number and get your long value from it:

Object num = new Integer(6);
Long longValue = ((Number) num).longValue();

How to include js file in another js file?

It is not possible directly. You may as well write some preprocessor which can handle that.

If I understand it correctly then below are the things that can be helpful to achieve that:

  • Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)

  • If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.

  • Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.

JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".

Hope it helps.

How to get index of an item in java.util.Set

After creating Set just convert it to List and get by index from List:

Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");

List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";

How to parse dates in multiple formats using SimpleDateFormat

I'm solved this problem more simple way using regex

fun parseTime(time: String?): Long {
    val longRegex = "\\d{4}+-\\d{2}+-\\d{2}+\\w\\d{2}:\\d{2}:\\d{2}.\\d{3}[Z]\$"
    val shortRegex = "\\d{4}+-\\d{2}+-\\d{2}+\\w\\d{2}:\\d{2}:\\d{2}Z\$"

    val longDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssXXX")
    val shortDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")

    return when {
        Pattern.matches(longRegex, time) -> longDateFormat.parse(time).time
        Pattern.matches(shortRegex, time) -> shortDateFormat.parse(time).time
        else -> throw InvalidParamsException(INVALID_TIME_MESSAGE, null)
    }
}

How to correctly implement custom iterators and const_iterators?

Boost has something to help: the Boost.Iterator library.

More precisely this page: boost::iterator_adaptor.

What's very interesting is the Tutorial Example which shows a complete implementation, from scratch, for a custom type.

template <class Value>
class node_iter
  : public boost::iterator_adaptor<
        node_iter<Value>                // Derived
      , Value*                          // Base
      , boost::use_default              // Value
      , boost::forward_traversal_tag    // CategoryOrTraversal
    >
{
 private:
    struct enabler {};  // a private type avoids misuse

 public:
    node_iter()
      : node_iter::iterator_adaptor_(0) {}

    explicit node_iter(Value* p)
      : node_iter::iterator_adaptor_(p) {}

    // iterator convertible to const_iterator, not vice-versa
    template <class OtherValue>
    node_iter(
        node_iter<OtherValue> const& other
      , typename boost::enable_if<
            boost::is_convertible<OtherValue*,Value*>
          , enabler
        >::type = enabler()
    )
      : node_iter::iterator_adaptor_(other.base()) {}

 private:
    friend class boost::iterator_core_access;
    void increment() { this->base_reference() = this->base()->next(); }
};

The main point, as has been cited already, is to use a single template implementation and typedef it.

How to extract elements from a list using indices in Python?

Bounds checked:

 [a[index] for index in (1,2,5,20) if 0 <= index < len(a)]
 # [11, 12, 15] 

Can I create view with parameter in MySQL?

I previously came up with a different workaround that doesn't use stored procedures, but instead uses a parameter table and some connection_id() magic.

EDIT (Copied up from comments)

create a table that contains a column called connection_id (make it a bigint). Place columns in that table for parameters for the view. Put a primary key on the connection_id. replace into the parameter table and use CONNECTION_ID() to populate the connection_id value. In the view use a cross join to the parameter table and put WHERE param_table.connection_id = CONNECTION_ID(). This will cross join with only one row from the parameter table which is what you want. You can then use the other columns in the where clause for example where orders.order_id = param_table.order_id.

How to Join to first row

You could do:

SELECT 
  Orders.OrderNumber, 
  LineItems.Quantity, 
  LineItems.Description
FROM 
  Orders INNER JOIN LineItems 
  ON Orders.OrderID = LineItems.OrderID
WHERE
  LineItems.LineItemID = (
    SELECT MIN(LineItemID) 
    FROM   LineItems
    WHERE  OrderID = Orders.OrderID
  )

This requires an index (or primary key) on LineItems.LineItemID and an index on LineItems.OrderID or it will be slow.

How can I check whether a option already exist in select by JQuery

if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
  alert("option doesn't exist!");
}

What's wrong with foreign keys?

I know only Oracle databases, no other ones, and I can tell that Foreign Keys are essential for maintaining data integrity. Prior to inserting data, a data structure needs to be made, and be made correctlty. When that is done - and thus all primary AND foreign keys are created - the work is done !

Meaning : orphaned rows ? No. Never seen that in my life. Unless a bad programmer forgot the foreign key, or if he implemented that on another level. Both are - in context of Oracle - huge mistakes, which will lead to data duplication, orphan data, and thus : data corruption. I can't imagine a database without FK enforced. It looks like chaos to me. It's a bit like the Unix permission system : imagine that everybody is root. Think of the chaos.

Foreign Keys are essential, just like Primary Keys. It's like saying : what if we removing Primary Keys ? Well, total chaos is going to happen. That's what. You may not move the primary or foreign key responsibility to the programming level, it must be at the data level.

Drawbacks ? Yes, absolutely ! Because on insert, a lot more checks are going to be happening. But, if data integrity is more important than performance, it's a no-brainer. The problem with performance on Oracle is more related to indexes, which come with PK and FK's.

Ignore case in Python strings

In response to your clarification...

You could use ctypes to execute the c function "strcasecmp". Ctypes is included in Python 2.5. It provides the ability to call out to dll and shared libraries such as libc. Here is a quick example (Python on Linux; see link for Win32 help):

from ctypes import *
libc = CDLL("libc.so.6")  // see link above for Win32 help
libc.strcasecmp("THIS", "this") // returns 0
libc.strcasecmp("THIS", "THAT") // returns 8

may also want to reference strcasecmp documentation

Not really sure this is any faster or slower (have not tested), but it's a way to use a C function to do case insensitive string comparisons.

~~~~~~~~~~~~~~

ActiveState Code - Recipe 194371: Case Insensitive Strings is a recipe for creating a case insensitive string class. It might be a bit over kill for something quick, but could provide you with a common way of handling case insensitive strings if you plan on using them often.

Most pythonic way to delete a file which may not exist

This is another solution:

if os.path.isfile(os.path.join(path, filename)):
    os.remove(os.path.join(path, filename))

Read response body in JAX-RS client from a post request

I also had the same issue, trying to run a unit test calling code that uses readEntity. Can't use getEntity in production code because that just returns a ByteInputStream and not the content of the body and there is no way I am adding production code that is hit only in unit tests.

My solution was to create a response and then use a Mockito spy to mock out the readEntity method:

Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);

Note that you can't use the when(mockResponse.readEntity(String.class) option because that throws the same IllegalStateException.

Hope this helps!

Find PHP version on windows command line

Just create a php file and write the code

<?php
echo phpversion();
?>

and open the file in any browser. It will show the php version installed in your system.

How can I get the last 7 characters of a PHP string?

for last 7 characters

$newstring = substr($dynamicstring, -7);

$newstring : 5409els

for first 7 characters

$newstring = substr($dynamicstring, 0, 7);

$newstring : 2490slk

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

How to create a custom string representation for a class object?

Implement __str__() or __repr__() in the class's metaclass.

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object):
  __metaclass__ = MC

print C

Use __str__ if you mean a readable stringification, use __repr__ for unambiguous representations.

Relative frequencies / proportions with dplyr

This answer is based upon Matifou's answer.

First I modified it to ensure that I don't get the freq column returned as a scientific notation column by using the scipen option.

Then I multiple the answer by 100 to get a percent rather than decimal to make the freq column easier to read as a percentage.

getOption("scipen") 
options("scipen"=10) 
mtcars %>%
count(am, gear) %>% 
mutate(freq = (n / sum(n)) * 100)

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

Add an index (numeric ID) column to large data frame

You can add a sequence of numbers very easily with

data$ID <- seq.int(nrow(data))

If you are already using library(tidyverse), you can use

data <- tibble::rowid_to_column(data, "ID")

Parsing CSV / tab-delimited txt file with Python

Start by turning the text into a list of lists. That will take care of the parsing part:

lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))

The rest can be done with indexed lookups:

d = dict()
key = lol[6][0]      # cell A7
value = lol[6][3]    # cell D7
d[key] = value       # add the entry to the dictionary
 ...

Easiest way to compare arrays in C#

I was looking to determine if two sets had equivalent contents, in any order. That meant that, for each element in set A there were equal numbers of elements with that value in both sets. I wanted to account for duplicates (so {1,2,2,3} and {1,2,3,3} should not be considered "the same").

This is what I came up with (note that IsNullOrEmpty is another static extension method that returns true if the enumerable is null or has 0 elements):

    public static bool HasSameContentsAs<T>(this IEnumerable<T> source, IEnumerable<T> target) 
        where T : IComparable
    {
        //If our source is null or empty, then it's just a matter of whether or not the target is too
        if (source.IsNullOrEmpty())
            return target.IsNullOrEmpty();

        //Otherwise, if the target is null/emtpy, they can't be equal
        if (target.IsNullOrEmpty())
            return false;

        //Neither is null or empty, so we'll compare contents.  To account for multiples of 
        //a given value (ex. 1,2,2,3 and 1,1,2,3 are not equal) we'll group the first set
        foreach (var group in source.GroupBy(s => s))
        {
            //If there are a different number of elements in the target set, they don't match
            if (target.Count(t => t.Equals(group.Key)) != group.Count())
                return false;
        }

        //If we got this far, they have the same contents
        return true;
    }

How get total sum from input box values using Javascript?

Try:

Qty1 : <input onblur="findTotal()" type="text" name="qty" id="qty1"/><br>
Qty2 : <input onblur="findTotal()" type="text" name="qty" id="qty2"/><br>
Qty3 : <input onblur="findTotal()" type="text" name="qty" id="qty3"/><br>
Qty4 : <input onblur="findTotal()" type="text" name="qty" id="qty4"/><br>
Qty5 : <input onblur="findTotal()" type="text" name="qty" id="qty5"/><br>
Qty6 : <input onblur="findTotal()" type="text" name="qty" id="qty6"/><br>
Qty7 : <input onblur="findTotal()" type="text" name="qty" id="qty7"/><br>
Qty8 : <input onblur="findTotal()" type="text" name="qty" id="qty8"/><br>
<br><br>
Total : <input type="text" name="total" id="total"/>


    <script type="text/javascript">
function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('total').value = tot;
}

    </script>

How to create a DataFrame of random integers with Pandas?

numpy.random.randint accepts a third argument (size) , in which you can specify the size of the output array. You can use this to create your DataFrame -

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Here - np.random.randint(0,100,size=(100, 4)) - creates an output array of size (100,4) with random integer elements between [0,100) .


Demo -

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

which produces:

     A   B   C   D
0   45  88  44  92
1   62  34   2  86
2   85  65  11  31
3   74  43  42  56
4   90  38  34  93
5    0  94  45  10
6   58  23  23  60
..  ..  ..  ..  ..

What HTTP traffic monitor would you recommend for Windows?

I use Wireshark in most cases, but I have found Fiddler to be less of a hassle when dealing with encrypted data.

Check if String / Record exists in DataTable

You can loop over each row of the DataTable and check the value.

I'm a big fan of using a foreach loop when using IEnumerables. Makes it very simple and clean to look at or process each row

DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
    if (dr["item_manuf_id"].ToString() == "some value")
    {
        // do your deed
    }
}

Alternatively you can use a PrimaryKey for your DataTable. This helps in various ways, but you often need to define one before you can use it.

An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx

DataTable workTable = new DataTable("Customers");

// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;

workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));

// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };

Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.

Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx

DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
    // do your deed
}

Finally, you can use the Select() method to find data within a DataTable also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.

String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);

foreach (DataRow dr in drFound)
{
    // do you deed. Each record here was already found to match your criteria
}

Regex in JavaScript for validating decimal numbers

Since you asked for decimal numbers validation, for completeness' sake, I'd use a regex that doesn't allow strings like 06.05.

^((0(\.\d{1,2})?)|([1-9]\d*(\.\d{1,2})?))$

Slightly more complicated, but returns false in that case.

Creating an empty file in C#

Using just File.Create will leave the file open, which probably isn't what you want.

You could use:

using (File.Create(filename)) ;

That looks slightly odd, mind you. You could use braces instead:

using (File.Create(filename)) {}

Or just call Dispose directly:

File.Create(filename).Dispose();

Either way, if you're going to use this in more than one place you should probably consider wrapping it in a helper method, e.g.

public static void CreateEmptyFile(string filename)
{
    File.Create(filename).Dispose();
}

Note that calling Dispose directly instead of using a using statement doesn't really make much difference here as far as I can tell - the only way it could make a difference is if the thread were aborted between the call to File.Create and the call to Dispose. If that race condition exists, I suspect it would also exist in the using version, if the thread were aborted at the very end of the File.Create method, just before the value was returned...

Angular.js programmatically setting a form field to dirty

Small additional note to @rmag's answer. If you have empty but required fields that you want to make dirty use this:

$scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue !== undefined 
    ? $scope.myForm.username.$viewValue : '');

How to dispatch a Redux action with a timeout?

This may be a bit off-topic but I want to share it here because I simply wanted to remove Alerts from state after a given timeout i.e. auto hiding alerts/notifications.

I ended up using setTimeout() within the <Alert /> component, so that it can then call and dispatch a REMOVE action on given id.

export function Alert(props: Props) {
  useEffect(() => {
    const timeoutID = setTimeout(() => {
      dispatchAction({
        type: REMOVE,
        payload: {
          id: id,
        },
      });
    }, timeout ?? 2000);
    return () => clearTimeout(timeoutID);
  }, []);
  return <AlertComponent {...props} />;
}

HTML form submit to PHP script

Try this:

<form method="post" action="check.php">
    <select name="website_string">
        <option value="" selected="selected"></option>
        <option VALUE="abc"> ABC</option>
        <option VALUE="def"> def</option>
        <option VALUE="hij"> hij</option>
    </select>
    <input TYPE="submit" name="submit" />
</form>

Both your select control and your submit button had the same name attribute, so the last one used was the submit button when you clicked it. All other syntax errors aside.

check.php

<?php
    echo $_POST['website_string'];
?>

Obligatory disclaimer about using raw $_POST data. Sanitize anything you'll actually be using in application logic.

Dropdown select with images

PLAIN JAVASCRIPT:

DEMO: http://codepen.io/tazotodua/pen/orhdp

_x000D_
_x000D_
var shownnn = "yes";_x000D_
var dropd = document.getElementById("image-dropdown");_x000D_
_x000D_
function showww() {_x000D_
  dropd.style.height = "auto";_x000D_
  dropd.style.overflow = "y-scroll";_x000D_
}_x000D_
_x000D_
function hideee() {_x000D_
    dropd.style.height = "30px";_x000D_
    dropd.style.overflow = "hidden";_x000D_
  }_x000D_
  //dropd.addEventListener('mouseover', showOrHide, false);_x000D_
  //dropd.addEventListener('click',showOrHide , false);_x000D_
_x000D_
_x000D_
function myfuunc(imgParent) {_x000D_
  hideee();_x000D_
  var mainDIVV = document.getElementById("image-dropdown");_x000D_
  imgParent.parentNode.removeChild(imgParent);_x000D_
  mainDIVV.insertBefore(imgParent, mainDIVV.childNodes[0]);_x000D_
}
_x000D_
#image-dropdown {_x000D_
  display: inline-block;_x000D_
  border: 1px solid;_x000D_
}_x000D_
#image-dropdown {_x000D_
  height: 30px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
/*#image-dropdown:hover {} */_x000D_
_x000D_
#image-dropdown .img_holder {_x000D_
  cursor: pointer;_x000D_
}_x000D_
#image-dropdown img.flagimgs {_x000D_
  height: 30px;_x000D_
}_x000D_
#image-dropdown span.iTEXT {_x000D_
  position: relative;_x000D_
  top: -8px;_x000D_
}
_x000D_
<!-- not tested in mobiles -->_x000D_
_x000D_
_x000D_
<div id="image-dropdown" onmouseleave="hideee();">_x000D_
  <div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
    <img class="flagimgs first" src="http://www.google.com/tv/images/socialyoutube.png" /> <span class="iTEXT">First</span>_x000D_
  </div>_x000D_
  <div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
    <img class="flagimgs second" src="http://www.google.com/cloudprint/learn/images/icons/fiabee.png" /> <span class="iTEXT">Second</span>_x000D_
  </div>_x000D_
  <div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
    <img class="flagimgs second" src="http://www.google.com/tv/images/lplay.png" /> <span class="iTEXT">Third</span>_x000D_
  </div>_x000D_
  <div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
    <img class="flagimgs second" src="http://www.google.com/cloudprint/learn/images/icons/cloudprintlite.png" /> <span class="iTEXT">Fourth</span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Auto highlight text in a textbox control

If your intention is to get the text in the textbox highlighted on a mouse click you can make it simple by adding:

this.textBox1.Click += new System.EventHandler(textBox1_Click);

in:

partial class Form1
{
    private void InitializeComponent()
    {

    }
}

where textBox1 is the name of the relevant textbox located in Form1

And then create the method definition:

void textBox1_Click(object sender, System.EventArgs e)
{
    textBox1.SelectAll();
}

in:

public partial class Form1 : Form
{

}

Can I have multiple background images using CSS?

You could have a div for the top with one background and another for the main page, and seperate the page content between them or put the content in a floating div on another z-level. The way you are doing it may work but I doubt it will work across every browser you encounter.

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Following is the solution which worked for me. The files which I updated are as follows:

  1. config.xml (Full Path: /config.xml)
  2. network_security_config.xml (Full Path: /resources/android/xml/network_security_config.xml)

Changes in the corresponding files are as follows:

1. config.xml

I have added <application android:usesCleartextTraffic="true" /> tag within <edit-config> tag in the config.xml file

<platform name="android">
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:usesCleartextTraffic="true" />
        <application android:networkSecurityConfig="@xml/network_security_config" />
    </edit-config>
    ...
<platform name="android">

2. network_security_config.xml

In this file I have added 2 <domain> tag within <domain-config> tag, the main domain and a sub domain as per my project requirement

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">mywebsite.in</domain>
        <domain includeSubdomains="true">api.mywebsite.in</domain>
    </domain-config>
</network-security-config>

Thanks @Ashutosh for the providing the help.

Hope it helps.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I solved it with window.length. But with this solution you can take current error (X-Frame or 404).

iframe.onload = event => {
   const isLoaded = event.target.contentWindow.window.length // 0 or 1
}

MSDN

Fast and simple String encrypt/decrypt in JAVA

Simplest way is to add this JAVA library using Gradle:

compile 'se.simbio.encryption:library:2.0.0'

You can use it as simple as this:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

Delete first character of a string in Javascript

The easiest way to strip all leading 0s is:

var s = "00test";
s = s.replace(/^0+/, "");

If just stripping a single leading 0 character, as the question implies, you could use

s = s.replace(/^0/, "");

What is the difference between JAX-RS and JAX-WS?

Can JAX-RS do Asynchronous Request like JAX-WS?

1) I don't know if the JAX-RS API includes a specific mechanism for asynchronous requests, but this answer could still change based on the client implementation you use.

Can JAX-RS access a web service that is not running on the Java platform, and vice versa?

2) I can't think of any reason it wouldn't be able to.

What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?

3) REST based architectures typically will use a lightweight data format, like JSON, to send data back and forth. This is in contrast to JAX-WS which uses XML. I don't see XML by itself so significantly heavier than JSON (which some people may argue), but with JAX-WS it's how much XML is used that ends up making REST with JSON the lighter option.

What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?

4) As stated in 3, REST architectures often use JSON to send and receive data. JAX-WS uses XML. It's not that JSON is so significantly smaller than XML by itself. It's mostly that JAX-WS specification includes lots overhead in how it communicates.

On the point about WSDL and API definitions, REST will more frequently use the URI structure and HTTP commands to define the API rather than message types, as is done in the JAX-WS. This means that you don't need to publish a WSDL document so that other users of your service can know how to talk to your service. With REST you will still need to provide some documentation to other users about how the REST service is organized and what data and HTTP commands need to be sent.

Curl to return http status code along with the response

In my experience we usually use curl this way

curl -f http://localhost:1234/foo || exit 1

curl: (22) The requested URL returned error: 400 Bad Request

This way we can pipe the curl when it fails, and it also shows the status code.

Bootstrap 3 navbar active li not changing background-color

in my case just removing background-image from nav-bar item solved the problem

.navbar-default .navbar-nav > .active > a:focus {
    .
    .
    .


    background-image: none;
}

In C/C++ what's the simplest way to reverse the order of bits in a byte?

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

#define BIT0 (0x01)
#define BIT1 (0x02)
#define BIT2 (0x04)
#define BIT3 (0x08)
#define BIT4 (0x10)
#define BIT5 (0x20)
#define BIT6 (0x40)
#define BIT7 (0x80)

#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c\n"

#define BITETOBINARY(byte) \
(byte & BIT7 ? '1' : '0'), \
(byte & BIT6 ? '1' : '0'), \
(byte & BIT5 ? '1' : '0'), \
(byte & BIT4 ? '1' : '0'), \
(byte & BIT3 ? '1' : '0'), \
(byte & BIT2 ? '1' : '0'), \
(byte & BIT1 ? '1' : '0'), \
(byte & BIT0 ? '1' : '0') \

#define BITETOBINARYREVERSE(byte) \
(byte & BIT0 ? '1' : '0'), \
(byte & BIT1 ? '1' : '0'), \
(byte & BIT2 ? '1' : '0'), \
(byte & BIT3 ? '1' : '0'), \
(byte & BIT4 ? '1' : '0'), \
(byte & BIT5 ? '1' : '0'), \
(byte & BIT6 ? '1' : '0'), \
(byte & BIT7 ? '1' : '0') \



int main()
{

    int i,j,c;

    i |= BIT2|BIT7;

    printf("0x%02X\n",i);    

    printf(BYTE_TO_BINARY_PATTERN,BITETOBINARY(i));

    printf("Reverse");

    printf(BYTE_TO_BINARY_PATTERN,BITETOBINARYREVERSE(i));

   return 0;
}

How does DateTime.Now.Ticks exactly work?

Not really an answer to your question as asked, but thought I'd chip in about your general objective.

There already is a method to generate random file names in .NET.

See System.Path.GetTempFileName and GetRandomFileName.

Alternatively, it is a common practice to use a GUID to name random files.

How to bind inverse boolean properties in WPF?

Following @Paul's answer, I wrote the following in the ViewModel:

public bool ShowAtView { get; set; }
public bool InvShowAtView { get { return !ShowAtView; } }

I hope having a snippet here will help someone, probably newbie as I am.
And if there's a mistake, please let me know!

BTW, I also agree with @heltonbiker comment - it's definitely the correct approach only if you don't have to use it more than 3 times...

How do I set a program to launch at startup

If an application is designed to start when Windows starts (as opposed to when a user logs in), your only option is to involve a Windows Service. Either write the application as a service, or write a simple service that exists only to launch the application.

Writing services can be tricky, and can impose restrictions that may be unacceptable for your particular case. One common design pattern is a front-end/back-end pair, with a service that does the work and an application front-end that communicates with the service to display information to the user.

On the other hand, if you just want your application to start on user login, you can use methods 1 or 2 that Joel Coehoorn listed.

How can I write a byte array to a file in Java?

Apache Commons IO Utils has a FileUtils.writeByteArrayToFile() method. Note that if you're doing any file/IO work then the Apache Commons IO library will do a lot of work for you.

How to Scroll Down - JQuery

Try This:

window.scrollBy(0,180); // horizontal and vertical scroll increments

Delete all records in a table of MYSQL in phpMyAdmin

An interesting fact.

I was sure TRUNCATE will always perform better, but in my case, for a db with approx 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows. Setting the auto increment adds about a second in total, but it's still a lot better.

So I would suggest try both, see which works faster for your case.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows:

Run the following command from the ssh terminal and follow the instruction:

 sudo apt-get install libsm6 libxrender1 libfontconfig1

Once its installed Open the Jupyter notebook and run following command:

!pip install opencv-contrib-python

Note: I tried to run this command: "sudo python3 -m pip install opencv-contrib-python"but it was showing an error. But above command worked for me.

Now refresh the notebook page and check whether it's installed or not by running import cv2 in the notebook.

How to add property to object in PHP >= 5.3 strict mode without generating error

I always use this way:

$foo = (object)null; //create an empty object
$foo->bar = "12345";

echo $foo->bar; //12345

How to update Identity Column in SQL Server?

You can create a new table using the following code.

SELECT IDENTITY (int, 1, 1) AS id, column1, column2
INTO dbo.NewTable
FROM dbo.OldTable

Then delete the old db, and rename the new db to the old db's name. Note: that column1 and column2 represent all the columns in your old table that you want to keep in your new table.

What does '?' do in C++?

It's the conditional operator.

a ? b : c

It's a shortcut for IF/THEN/ELSE.

means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

Making Maven run all tests, even when some fail

A quick answer:

mvn -fn test

Works with nested project builds.

How to increase maximum execution time in php

use below statement if safe_mode is off

set_time_limit(0);

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

Range of values in C Int and Long 32 - 64 bits

In C and C++ you have these least requirements (i.e actual implementations can have larger magnitudes)

signed char: -2^07+1 to +2^07-1
short:       -2^15+1 to +2^15-1
int:         -2^15+1 to +2^15-1
long:        -2^31+1 to +2^31-1
long long:   -2^63+1 to +2^63-1

Now, on particular implementations, you have a variety of bit ranges. The wikipedia article describes this nicely.

Reference to a non-shared member requires an object reference occurs when calling public sub

Go to the Declaration of the desired object and mark it Shared.

Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX

In Python, how do I loop through the dictionary and change the value if it equals something?

Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration:

mydict = dict((k, v if v else '') for k, v in mydict.items())

Programmatically read from STDIN or input file in Perl

Here is how I made a script that could take either command line inputs or have a text file redirected.

if ($#ARGV < 1) {
    @ARGV = ();
    @ARGV = <>;
    chomp(@ARGV);
}


This will reassign the contents of the file to @ARGV, from there you just process @ARGV as if someone was including command line options.

WARNING

If no file is redirected, the program will sit their idle because it is waiting for input from STDIN.

I have not figured out a way to detect if a file is being redirected in yet to eliminate the STDIN issue.

Good NumericUpDown equivalent in WPF?

add a textbox and scrollbar

in VB

Private Sub Textbox1_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Textbox1.ValueChanged
     If e.OldValue > e.NewValue Then
         Textbox1.Text = (Textbox1.Text + 1)
     Else
         Textbox1.Text = (Textbox1.Text - 1)
     End If
End Sub

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

webpack: Module not found: Error: Can't resolve (with relative path)

Just ran into this... I have a common library shared among multiple transpiled products. I was using symlinks with brunch to handle sharing things between the projects. When moving to webpack, this stopped working.

What did get things working was using webpack configuration to turn off symlink resolving.

i.e. adding this in webpack.config.js:

module.exports = {
  //...
  resolve: {
    symlinks: false
  }
};

as documented here:

https://webpack.js.org/configuration/resolve/#resolvesymlinks

ASP.NET Setting width of DataBound column in GridView

I did a small demo for you. Demonstrating how to display long text.

In this example there is a column Name which may contain very long text. The boundField will display all content in a table cell and therefore the cell will expand as needed (because of the content)

The TemplateField will also be rendered as a cell BUT it contains a div which limits the width of any contet to eg 40px. So this column will have some kind of max-width!

    <asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" Width="100px">
        <Columns>
            <asp:BoundField HeaderText="ID" DataField="ID" />
            <asp:BoundField HeaderText="Name (long)" DataField="Name">
                <ItemStyle Width="40px"></ItemStyle>
            </asp:BoundField>
            <asp:TemplateField HeaderText="Name (short)">
                <ItemTemplate>
                    <div style="width: 40px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
                        <%# Eval("Name") %>
                    </div>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

enter image description here

Here is my demo codeBehind

 public partial class gridViewLongText : System.Web.UI.Page
 {
     protected void Page_Load(object sender, EventArgs e)
     {
         #region init and bind data
         List<Person> list = new List<Person>();
         list.Add(new Person(1, "Sam"));
         list.Add(new Person(2, "Max"));
         list.Add(new Person(3, "Dave"));
         list.Add(new Person(4, "TabularasaVeryLongName"));
         gvPersons.DataSource = list;
         gvPersons.DataBind();
         #endregion
     }
 }

 public class Person
 {
     public int ID { get; set; }
     public string Name { get; set; }

     public Person(int _ID, string _Name)
     {
         ID = _ID;
         Name = _Name;
     }
 }

How to fix "unable to open stdio.h in Turbo C" error?

Just Re install the turbo C++ from your Computer and install again in the Directory C:\TC\ Folder.

Again The Problem exists ,then change the directory from FILE>>CHANGE DIRECTORY to C:\TC\BIN\

How to maintain aspect ratio using HTML IMG tag

Try this:

<img src="Runtime Path to photo" border="1" height="64" width="64" object-fit="cover">

Adding object-fit="cover" will force the image to take up the space without losing the aspect ratio.

Google Maps v3 - limit viewable area and zoom level

Here's my variant to solve the problem of viewable area's limitation.

        google.maps.event.addListener(this.map, 'idle', function() {
            var minLat = strictBounds.getSouthWest().lat();
            var minLon = strictBounds.getSouthWest().lng();
            var maxLat = strictBounds.getNorthEast().lat();
            var maxLon = strictBounds.getNorthEast().lng();
            var cBounds  = self.map.getBounds();
            var cMinLat = cBounds.getSouthWest().lat();
            var cMinLon = cBounds.getSouthWest().lng();
            var cMaxLat = cBounds.getNorthEast().lat();
            var cMaxLon = cBounds.getNorthEast().lng();
            var centerLat = self.map.getCenter().lat();
            var centerLon = self.map.getCenter().lng();

            if((cMaxLat - cMinLat > maxLat - minLat) || (cMaxLon - cMinLon > maxLon - minLon))
            {   //We can't position the canvas to strict borders with a current zoom level
                self.map.setZoomLevel(self.map.getZoomLevel()+1);
                return;
            }
            if(cMinLat < minLat)
                var newCenterLat = minLat + ((cMaxLat-cMinLat) / 2);
            else if(cMaxLat > maxLat)
                var newCenterLat = maxLat - ((cMaxLat-cMinLat) / 2);
            else
                var newCenterLat = centerLat;
            if(cMinLon < minLon)
                var newCenterLon = minLon + ((cMaxLon-cMinLon) / 2);
            else if(cMaxLon > maxLon)
                var newCenterLon = maxLon - ((cMaxLon-cMinLon) / 2);
            else
                var newCenterLon = centerLon;

            if(newCenterLat != centerLat || newCenterLon != centerLon)
                self.map.setCenter(new google.maps.LatLng(newCenterLat, newCenterLon));
        });

strictBounds is an object of new google.maps.LatLngBounds() type. self.gmap stores a Google Map object (new google.maps.Map()).

It really works but don't only forget to take into account the haemorrhoids with crossing 0th meridians and parallels if your bounds cover them.

Install Windows Service created in Visual Studio

Looking at:

No public installers with the RunInstallerAttribute.Yes attribute could be found in the C:\Users\myusername\Documents\Visual Studio 2010\Projects\TestService\TestSe rvice\obj\x86\Debug\TestService.exe assembly.

It looks like you may not have an installer class in your code. This is a class that inherits from Installer that will tell installutil how to install your executable as a service.

P.s. I have my own little self-installing/debuggable Windows Service template here which you can copy code from or use: Debuggable, Self-Installing Windows Service

Right query to get the current number of connections in a PostgreSQL DB

They definitely may give different results. The better one is

select count(*) from pg_stat_activity;

It's because it includes connections to WAL sender processes which are treated as regular connections and count towards max_connections.

See max_wal_senders

Produce a random number in a range using C#

Try below code.

Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51

How to make div background color transparent in CSS

It might be a little late to the discussion but inevitably someone will stumble onto this post like I did. I found the answer I was looking for and thought I'd post my own take on it. The following JSfiddle includes how to layer .PNG's with transparency. Jerska's mention of the transparency attribute for the div's CSS was the solution: http://jsfiddle.net/jyef3fqr/

HTML:

   <button id="toggle-box">toggle</button>
   <div id="box" style="display:none;" ><img src="x"></div>
   <button id="toggle-box2">toggle</button>
   <div id="box2" style="display:none;"><img src="xx"></div>
   <button id="toggle-box3">toggle</button>
   <div id="box3" style="display:none;" ><img src="xxx"></div>

CSS:

#box {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:1;
}
#box2 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
      }
      #box3 {
background-color: #ffffff;
height:400px;
width: 1200px;
position: absolute;
top:30px;
z-index:2;
background-color : transparent;
      }
 body {background-color:#c0c0c0; }

JS:

$('#toggle-box').click().toggle(function() {
$('#box').animate({ width: 'show' });
}, function() {
$('#box').animate({ width: 'hide' });
});

$('#toggle-box2').click().toggle(function() {
$('#box2').animate({ width: 'show' });
}, function() {
$('#box2').animate({ width: 'hide' });
});
$('#toggle-box3').click().toggle(function() {
$('#box3').animate({ width: 'show' });
 }, function() {
$('#box3').animate({ width: 'hide' });
});

And my original inspiration:http://jsfiddle.net/5g1zwLe3/ I also used paint.net for creating the transparent PNG's, or rather the PNG's with transparent BG's.

Which .NET Dependency Injection frameworks are worth looking into?

The great thing about C# is that it is following a path beaten by years of Java developers before it. So, my advice, generally speaking when looking for tools of this nature, is to look for the solid Java answer and see if there exists a .NET adaptation yet.

So when it comes to DI (and there are so many options out there, this really is a matter of taste) is Spring.NET. Additionally, it's always wise to research the people behind projects. I have no issue suggesting SourceGear products for source control (outside of using them) because I have respect for Eric Sink. I have seen Mark Pollack speak and what can I say, the guy just gets it.

In the end, there are a lot of DI frameworks and your best bet is to do some sample projects with a few of them and make an educated choice.

Good luck!

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

When you export you use the compatibility system set to MYSQL40. Worked for me.

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

In my particular case, I had a similar error on a legacy website used in my organization. To solve the issue, I had to list the website a a "Trusted site".

To do so:

  • Click the Tools button, and then Internet options.
  • Go on the Security tab.
  • Click on Trusted sites and then on the sites button.
  • Enter the url of the website and click on Add.

I'm leaving this here in the remote case it will help someone.

Write to CSV file and export it?

How to write to a file (easy search in Google) ... 1st Search Result

As far as creation of the file each time a user accesses the page ... each access will act on it's own behalf. You business case will dictate the behavior.

Case 1 - same file but does not change (this type of case can have multiple ways of being defined)

  • You would have logic that created the file when needed and only access the file if generation is not needed.

Case 2 - each user needs to generate their own file

  • You would decide how you identify each user, create a file for each user and access the file they are supposed to see ... this can easily merge with Case 1. Then you delete the file after serving the content or not if it requires persistence.

Case 3 - same file but generation required for each access

  • Use Case 2, this will cause a generation each time but clean up once accessed.

jquery to validate phone number

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

Supports :

  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899

Is it possible to get only the first character of a String?

Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.

              String mob=edit_mobile.getText().toString();
                    if (mob.length() >= 10) {
                        if (mob.contains("+91")) {
                            mob= mob.substring(3, 13);
                        }
                        if (mob.substring(0, 1).contains("0")) {
                            mob= mob.substring(1, 11);
                        }
                        if (mob.contains("+")) {
                            mob= mob.replace("+", "");
                        }
                        mob= mob.substring(0, 10);
                        Log.i("mob", mob);

                    }

Get array of object's keys

Summary

For getting all of the keys of an Object you can use Object.keys(). Object.keys() takes an object as an argument and returns an array of all the keys.

Example:

_x000D_
_x000D_
const object = {_x000D_
  a: 'string1',_x000D_
  b: 42,_x000D_
  c: 34_x000D_
};_x000D_
_x000D_
const keys = Object.keys(object)_x000D_
_x000D_
console.log(keys);_x000D_
_x000D_
console.log(keys.length) // we can easily access the total amount of properties the object has
_x000D_
_x000D_
_x000D_

In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.

Getting the values with: Object.values()

The complementary function of Object.keys() is Object.values(). This function takes an object as an argument and returns an array of values. For example:

_x000D_
_x000D_
const object = {_x000D_
  a: 'random',_x000D_
  b: 22,_x000D_
  c: true_x000D_
};_x000D_
_x000D_
_x000D_
console.log(Object.values(object));
_x000D_
_x000D_
_x000D_

Executing Javascript from Python

Using PyV8, I can do this. However, I have to replace document.write with return because there's no DOM and therefore no document.

import PyV8
ctx = PyV8.JSContext()
ctx.enter()

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
"""

print ctx.eval(js.replace("document.write", "return "))

Or you could create a mock document object

class MockDocument(object):

    def __init__(self):
        self.value = ''

    def write(self, *args):
        self.value += ''.join(str(i) for i in args)


class Global(PyV8.JSClass):
    def __init__(self):
        self.document = MockDocument()

scope = Global()
ctx = PyV8.JSContext(scope)
ctx.enter()
ctx.eval(js)
print scope.document.value

What is Java String interning?

String interning is an optimization technique by the compiler. If you have two identical string literals in one compilation unit then the code generated ensures that there is only one string object created for all the instance of that literal(characters enclosed in double quotes) within the assembly.

I am from C# background, so i can explain by giving a example from that:

object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;

output of the following comparisons:

Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true    
Console.WriteLine(obj == str2); // false !?

Note1:Objects are compared by reference.

Note2:typeof(int).Name is evaluated by reflection method so it does not gets evaluated at compile time. Here these comparisons are made at compile time.

Analysis of the Results: 1) true because they both contain same literal and so the code generated will have only one object referencing "Int32". See Note 1.

2) true because the content of both the value is checked which is same.

3) FALSE because str2 and obj does not have the same literal. See Note 2.

Getting the absolute path of the executable, using C#?

var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

I jumped in for the top rated answer and found myself not getting what I expected. I had to read the comments to find what I was looking for.

For that reason I am posting the answer listed in the comments to give it the exposure it deserves.

Error "The input device is not a TTY"

when using 'git bash',

1) I execute the command:

docker exec -it 726fe4999627 /bin/bash

I have the error:

the input device is not a TTY.  If you are using mintty, try prefixing the command with 'winpty'

2) then, I execute the command:

winpty docker exec -it 726fe4999627 /bin/bash

I have another error:

OCI runtime exec failed: exec failed: container_linux.go:344: starting container process caused "exec: \"D:/Git/usr/bin/
bash.exe\": stat D:/Git/usr/bin/bash.exe: no such file or directory": unknown

3) third, I execute the:

winpty docker exec -it 726fe4999627 bash

it worked.

when I using 'powershell', all worked well.

What does %>% function mean in R?

The R packages dplyr and sf import the operator %>% from the R package magrittr.

Help is available by using the following command:

?'%>%'

Of course the package must be loaded before by using e.g.

library(sf)

The documentation of the magrittr forward-pipe operator gives a good example: When functions require only one argument, x %>% f is equivalent to f(x)

Read/Write String from/to a File in Android

Hope this might be useful to you.

Write File:

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

Read File:

private String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

How to set focus on input field?

Here is my original solution:

plunker

var app = angular.module('plunker', []);
app.directive('autoFocus', function($timeout) {
    return {
        link: function (scope, element, attrs) {
            attrs.$observe("autoFocus", function(newValue){
                if (newValue === "true")
                    $timeout(function(){element[0].focus()});
            });
        }
    };
});

And the HTML:

<button ng-click="isVisible = !isVisible">Toggle input</button>
<input ng-show="isVisible" auto-focus="{{ isVisible }}" value="auto-focus on" />

What it does:

It focuses the input as it becomes visible with ng-show. No use of $watch or $on here.

Populating a ListView using an ArrayList?

tutorial

Also look up ArrayAdapter interface:

ArrayAdapter(Context context, int textViewResourceId, List<T> objects)

C# : Out of Memory exception

My Development Team resolved this situation:

We added the following Post-Build script into the .exe project and compiled again, setting the target to x86 and increasing by 1.5 gb and also x64 Platform target increasing memory using 3.2 gb. Our application is 32 bit.

Related URLs:

Script:

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
    call "$(DevEnvDir)..\tools\vsvars32.bat"
    editbin /largeaddressaware "$(TargetPath)"
)

How do I uninstall a package installed using npm link?

The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global flag needs to be provided.

In order to uninstall the globally linked foo package, the following command can be used (using sudo if necessary, depending on your setup and permissions)

sudo npm rm --global foo

This will uninstall the package.

To check whether a package is installed, the npm ls command can be used:

npm ls --global foo

Get real path from URI, Android KitKat new storage access framework

Here is an updated version of Paul Burke's answer. In versions below Android 4.4 (KitKat) we don't have the DocumentsContract class.

In order to work on versions below KitKat create this class:

public class DocumentsContract {
    private static final String DOCUMENT_URIS =
        "com.android.providers.media.documents " +
        "com.android.externalstorage.documents " +
        "com.android.providers.downloads.documents " +
        "com.android.providers.media.documents";

    private static final String PATH_DOCUMENT = "document";
    private static final String TAG = DocumentsContract.class.getSimpleName();

    public static String getDocumentId(Uri documentUri) {
        final List<String> paths = documentUri.getPathSegments();
        if (paths.size() < 2) {
            throw new IllegalArgumentException("Not a document: " + documentUri);
        }

        if (!PATH_DOCUMENT.equals(paths.get(0))) {
            throw new IllegalArgumentException("Not a document: " + documentUri);
        }
        return paths.get(1);
    }

    public static boolean isDocumentUri(Uri uri) {
        final List<String> paths = uri.getPathSegments();
        Logger.v(TAG, "paths[" + paths + "]");
        if (paths.size() < 2) {
            return false;
        }
        if (!PATH_DOCUMENT.equals(paths.get(0))) {
            return false;
        }
        return DOCUMENT_URIS.contains(uri.getAuthority());
    }
}

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

How to call a stored procedure (with parameters) from another stored procedure without temp table

 Create PROCEDURE  Stored_Procedure_Name_2
  (
  @param1 int = 5  ,
  @param2 varchar(max),
  @param3 varchar(max)

 )
AS


DECLARE @Table TABLE
(
   /*TABLE DEFINITION*/
   id int,
   name varchar(max),
   address varchar(max)
)

INSERT INTO @Table 
EXEC Stored_Procedure_Name_1 @param1 , @param2 = 'Raju' ,@param3 =@param3

SELECT id ,name ,address  FROM @Table  

Nested objects in javascript, best practices

var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};

href="tel:" and mobile numbers

The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.

For Safari:

<meta name="format-detection" content="telephone=no">

For BlackBerry:

<meta http-equiv="x-rim-auto-match" content="none">

Source: mobilexweb.com

How to replace item in array?

To replace the second element in the array

arr = [1, 7, 9]

with the value 8

arr[1] = 8

check if file exists in php

Based on your comment to Haim, is this a file on your own server? If so, you need to use the file system path, not url (e.g. file_exists( '/path/to/images/thumbnail.jpg' )).

What is a provisioning profile used for when developing iPhone applications?

Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:

  • When you need to test/debug an app on a real device the Development Provisioning Profile allows you to do it
  • When you publish an app you send a Distribution Provisioning Profile[About] and Apple after review reassign it by they own key

Development Provisioning Profile is stored on device and contains:

  • Application ID - application which are going to run
  • List of Development certificates - who can debug the app
  • List of devices - which devices can run this app

Xcode by default take cares about

ESLint Parsing error: Unexpected token

"parser": "babel-eslint" helped me to fix the issue

{
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true,
            "modules": true,
            "experimentalObjectRestSpread": true
        }
    },
    "plugins": [
        "react"
    ],
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "rules": {
        "comma-dangle": 0,
        "react/jsx-uses-vars": 1,
        "react/display-name": 1,
        "no-unused-vars": "warn",
        "no-console": 1,
        "no-unexpected-multiline": "warn"
    },
    "settings": {
        "react": {
            "pragma": "React",
            "version": "15.6.1"
        }
    }
}

Reference

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
 print "Please choose what you'd like to do:"

Illegal Escape Character "\"

Use "\\" to escape the \ character.

Copy rows from one table to another, ignoring duplicates

Something like this?:

INSERT INTO destTable
SELECT s.* FROM srcTable s
LEFT JOIN destTable d ON d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...
WHERE d.Key1 IS NULL

Automatically start a Windows Service on install

After refactoring a little bit, this is an example of a complete windows service installer with automatic start:

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace Example.of.name.space
{
[RunInstaller(true)]
public partial class ServiceInstaller : Installer
{
    private readonly ServiceProcessInstaller processInstaller;
    private readonly System.ServiceProcess.ServiceInstaller serviceInstaller;

    public ServiceInstaller()
    {
        InitializeComponent();
        processInstaller = new ServiceProcessInstaller();
        serviceInstaller = new System.ServiceProcess.ServiceInstaller();

        // Service will run under system account
        processInstaller.Account = ServiceAccount.LocalSystem;

        // Service will have Automatic Start Type
        serviceInstaller.StartType = ServiceStartMode.Automatic;

        serviceInstaller.ServiceName = "Windows Automatic Start Service";

        Installers.Add(serviceInstaller);
        Installers.Add(processInstaller);
        serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall;            
    }
    private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
    {
        ServiceController sc = new ServiceController("Windows Automatic Start Service");
        sc.Start();
    }
}
}

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

Python: finding lowest integer

l is a list of strings. When you put numbers between single quotes like that, you are creating strings, which are just a sequence of characters. To make your code work properly, you would have to do this:

l = [-1.2, 0.0, 1]  # no quotation marks

x = 100.0
for i in l:
    if i < x:
        x = i
print x

If you must use a list of strings, you can try to let Python try to make a number out of each string. This is similar to Justin's answer, except it understands floating-point (decimal) numbers correctly.

l = ['-1.2', '0.0', '1']

x = 100.0
for i in l:
    inum = float(i)
    if inum < x:
        x = inum
print x

I hope that this is code that you are writing to learn either Python or programming in general. If this is the case, great. However, if this is production code, consider using Python's built-in functions.

l = ['-1.2', '0.0', '1']
lnums = map(float, l)  # turn strings to numbers
x = min(lnums)  # find minimum value
print x

alternatives to REPLACE on a text or ntext datatype

IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

For SQL Server 2005+:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

Delete from a table based on date

or an ORACLE version:

delete
  from table_name
 where trunc(table_name.date) > to_date('01/01/2009','mm/dd/yyyy') 

Change Tomcat Server's timeout in Eclipse

I also had the issue of the Eclipse Tomcat Server timing out and tried every suggestion including:

  • increasing timeout seconds
  • deleting various .metadata files in workspace directory
  • deleting the server instance in Eclipse along with the Run Config

Nothing worked until I read Rohitdev's comment and realized that I had, in fact added a breakpoint in an interceptor class after a big code change and had forgotten to toggle it off. I removed it and all other breakpoints and Tomcat started right up.

Add default value of datetime field in SQL Server to a timestamp

In SQLPlus while creating a table it is be like as

SQL> create table Test

 ( Test_ID number not null,
   Test_Date date default sysdate not null );

SQL> insert into Test(id) values (1);

 Test_ID Test_Date
       1 08-MAR-19

how do I query sql for a latest record date for each user

This should also work in order to get all the latest entries for users.

SELECT username, MAX(date) as Date, value
FROM MyTable
GROUP BY username, value

How do I dynamically assign properties to an object in TypeScript?

To guarantee that the type is an Object (i.e. key-value pairs), use:

const obj: {[x: string]: any} = {}
obj.prop = 'cool beans'

Python slice first and last element in list

Actually, I just figured it out:

In [20]: some_list[::len(some_list) - 1]
Out[20]: ['1', 'F']

Command to delete all pods in all kubernetes namespaces

You can use kubectl delete pods -l dev-lead!=carisa or what label you have.

Advantages of SQL Server 2008 over SQL Server 2005?

I guess it depends on your role

For me as a developer:

  • Merge statement
  • Reporting Services improvement
  • Date/time changes

Edit, late update, after using it

  • filtered indexes
  • table valued parameters
  • Reporting Services without IIS

How to enable NSZombie in Xcode?

NSZombieEnabled is used for Debugging BAD_ACCESS,

enable the NSZombiesEnabled environment variable from Xcode’s schemes sheet.

Click on Product?Edit Scheme to open the sheet and set the Enable Zombie Objects check box

this video will help you to see what i'm trying to say.

Setting environment variables on OS X

Just did this really easy and quick. First create a ~/.bash_profile from terminal:

touch .bash_profile

then

open -a TextEdit.app .bash_profile

add

export TOMCAT_HOME=/Library/Tomcat/Home

save documement and you are done.

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I found this MSDN forum post which suggests two solutions to your problem.

First solution (not recommended):

Find the .Net Framework 3.5 and 2.0 folder

Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder

Add the reference to these two assemblies

Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work

Second solution (Use a different class / library):

The user who had posted the question claimed that Uri.EscapeUriString and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer.

You could also try to use Json.Net. It's a third party library and pretty powerful.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Right Align button in horizontal LinearLayout

Real solution for it case:

android:layout_weight="1" for TextView, and your button move to right!

Regex: match word that ends with "Id"

This may do the trick:

\b\p{L}*Id\b

Where \p{L} matches any (Unicode) letter and \b matches a word boundary.

How to use Lambda in LINQ select statement

Using Lambda expressions:

  1. If we don't have a specific class to bind the result:

     var stores = context.Stores.Select(x => new { x.id, x.name, x.city }).ToList();
    
  2. If we have a specific class then we need to bind the result with it:

    List<SelectListItem> stores = context.Stores.Select(x => new SelectListItem { Id = x.id, Name = x.name, City = x.city }).ToList();
    

Using simple LINQ expressions:

  1. If we don't have a specific class to bind the result:

    var stores = (from a in context.Stores select new { x.id, x.name, x.city }).ToList();
    
  2. If we have a specific class then we need to bind the result with it:

    List<SelectListItem> stores = (from a in context.Stores select new SelectListItem{ Id = x.id, Name = x.name, City = x.city }).ToList();
    

Django ChoiceField

If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .

Example:

views.py:

def my_view(request, interview_pk):
    interview = Interview.objects.get(pk=interview_pk)
    all_rounds = interview.round_set.order_by('created_at')
    all_round_names = [rnd.name for rnd in all_rounds]
    form = forms.AddRatingForRound(all_round_names)
    return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})

forms.py

class AddRatingForRound(forms.ModelForm):

    def __init__(self, round_list, *args, **kwargs):
        super(AddRatingForRound, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))

    class Meta:
        model = models.RatingSheet
        fields = ('name', )

template:

<form method="post">
    {% csrf_token %}
    {% if interview %}
         {{ interview }}
    {% endif %}
    {% if rounds %}
    <hr>
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    {% else %}
        <h3>No rounds found</h3>
    {% endif %}

</form>

How to get the first and last date of the current year?

If it reaches the 1st of Jan you might it to be still last years date.

select
convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AS StartOfYear,
convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 )AS EndOfYear

What is managed or unmanaged code in programming?

From Pro C# 5 and the .NET 4.5 Framework:

Managed vs. Unmanaged Code: Perhaps the most important point to understand about the C# language is that it can produce code that can execute only within the .NET runtime (you could never use C# to build a native COM server or an unmanaged C/C++ application). Officially speaking, the term used to describe the code targeting the .NET runtime is managed code. The binary unit that contains the managed code is termed an assembly (more details on assemblies in just a bit). Conversely, code that cannot be directly hosted by the .NET runtime is termed unmanaged code.

How to undo a successful "git cherry-pick"?

git reflog can come to your rescue.

Type it in your console and you will get a list of your git history along with SHA-1 representing them.

Simply checkout any SHA-1 that you wish to revert to


Before answering let's add some background, explaining what is this HEAD.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

First letter capitalization for EditText

if you are writing styles in styles.xml then

remove android:inputType property and add below lines

<item name="android:capitalize">words</item>

How do I measure the execution time of JavaScript code with callbacks?

Surprised no one had mentioned yet the new built in libraries:

Available in Node >= 8.5, and should be in Modern Browers

https://developer.mozilla.org/en-US/docs/Web/API/Performance

https://nodejs.org/docs/latest-v8.x/api/perf_hooks.html#

Node 8.5 ~ 9.x (Firefox, Chrome)

_x000D_
_x000D_
// const { performance } = require('perf_hooks'); // enable for node
const delay = time => new Promise(res=>setTimeout(res,time))
async function doSomeLongRunningProcess(){
  await delay(1000);
}
performance.mark('A');
(async ()=>{
  await doSomeLongRunningProcess();
  performance.mark('B');
  performance.measure('A to B', 'A', 'B');
  const measure = performance.getEntriesByName('A to B')[0];
  // firefox appears to only show second precision.
  console.log(measure.duration);
  // apparently you should clean up...
  performance.clearMarks();
  performance.clearMeasures();         
  // Prints the number of milliseconds between Mark 'A' and Mark 'B'
})();
_x000D_
_x000D_
_x000D_

https://repl.it/@CodyGeisler/NodeJsPerformanceHooks

Node 12.x

https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html

const { PerformanceObserver, performance } = require('perf_hooks');
const delay = time => new Promise(res => setTimeout(res, time))
async function doSomeLongRunningProcess() {
    await delay(1000);
}
const obs = new PerformanceObserver((items) => {
    console.log('PerformanceObserver A to B',items.getEntries()[0].duration);
      // apparently you should clean up...
      performance.clearMarks();
      // performance.clearMeasures(); // Not a function in Node.js 12
});
obs.observe({ entryTypes: ['measure'] });

performance.mark('A');

(async function main(){
    try{
        await performance.timerify(doSomeLongRunningProcess)();
        performance.mark('B');
        performance.measure('A to B', 'A', 'B');
    }catch(e){
        console.log('main() error',e);
    }
})();

How to scan a folder in Java?

You can also use the FileFilter interface to filter out what you want. It is best used when you create an anonymous class that implements it:

import java.io.File;
import java.io.FileFilter;

public class ListFiles {
    public File[] findDirectories(File root) { 
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();
            }});
    }

    public File[] findFiles(File root) {
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isFile();
            }});
    }
}

PHP header redirect 301 - what are the implications?

This is better:

<?php
//* Permanently redirect page
header("Location: new_page.php",TRUE,301);
?>

Just one call including code 301. Also notice the relative path to the file in the same directory (not "/dir/dir/new_page.php", etc.), which all modern browsers seem to support.

I think this is valid since PHP 5.1.2, possibly earlier.

I need to round a float to two decimal places in Java

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

Warn user before leaving web page with unsaved changes

Universal solution requiring no configuration that automatically detects all input modification, including contenteditable elements:

"use strict";
(() => {
const modified_inputs = new Set;
const defaultValue = "defaultValue";
// store default values
addEventListener("beforeinput", (evt) => {
    const target = evt.target;
    if (!(defaultValue in target || defaultValue in target.dataset)) {
        target.dataset[defaultValue] = ("" + (target.value || target.textContent)).trim();
    }
});
// detect input modifications
addEventListener("input", (evt) => {
    const target = evt.target;
    let original;
    if (defaultValue in target) {
        original = target[defaultValue];
    } else {
        original = target.dataset[defaultValue];
    }
    if (original !== ("" + (target.value || target.textContent)).trim()) {
        if (!modified_inputs.has(target)) {
            modified_inputs.add(target);
        }
    } else if (modified_inputs.has(target)) {
        modified_inputs.delete(target);
    }
});
// clear modified inputs upon form submission
addEventListener("submit", () => {
    modified_inputs.clear();
    // to prevent the warning from happening, it is advisable
    // that you clear your form controls back to their default
    // state with form.reset() after submission
});
// warn before closing if any inputs are modified
addEventListener("beforeunload", (evt) => {
    if (modified_inputs.size) {
        const unsaved_changes_warning = "Changes you made may not be saved.";
        evt.returnValue = unsaved_changes_warning;
        return unsaved_changes_warning;
    }
});
})();

How do you query for "is not null" in Mongo?

The simplest way to check the existence of the column in mongo compass is :

{ 'column_name': { $exists: true } }

Cannot run emulator in Android Studio

  • Open Android studio.
  • Go to setting > System Setting > Android SDK
  • Get the "Android SDK Location".
  • Set the environment variable ANDROID_SDK_ROOT to this value.

It worked for me and I'm on Windows 10 and Android studio 2.3.3

Defining array with multiple types in TypeScript

I've settled on the following format for typing arrays that can have items of multiple types.

Array<ItemType1 | ItemType2 | ItemType3>

This works well with testing and type guards. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

This format doesn't work well with testing or type guards:

(ItemType1 | ItemType2 | ItemType3)[]

Countdown timer in React

Countdown of user input

Interface Screenshot screenshot

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      hours: 0,
      minutes: 0,
      seconds:0
    }
    this.hoursInput = React.createRef();
    this.minutesInput= React.createRef();
    this.secondsInput = React.createRef();
  }

  inputHandler = (e) => {
    this.setState({[e.target.name]: e.target.value});
  }

  convertToSeconds = ( hours, minutes,seconds) => {
    return seconds + minutes * 60 + hours * 60 * 60;
  }

  startTimer = () => {
    this.timer = setInterval(this.countDown, 1000);
  }

  countDown = () => {
    const  { hours, minutes, seconds } = this.state;
    let c_seconds = this.convertToSeconds(hours, minutes, seconds);

    if(c_seconds) {

      // seconds change
      seconds ? this.setState({seconds: seconds-1}) : this.setState({seconds: 59});

      // minutes change
      if(c_seconds % 60 === 0 && minutes) {
        this.setState({minutes: minutes -1});
      }

      // when only hours entered
      if(!minutes && hours) {
        this.setState({minutes: 59});
      }

      // hours change
      if(c_seconds % 3600 === 0 && hours) {
        this.setState({hours: hours-1});
      }

    } else {
      clearInterval(this.timer);
    }
  }


  stopTimer = () => {
    clearInterval(this.timer);
  }

  resetTimer = () => {
    this.setState({
      hours: 0,
      minutes: 0,
      seconds: 0
    });
    this.hoursInput.current.value = 0;
    this.minutesInput.current.value = 0;
    this.secondsInput.current.value = 0;
  }


  render() {
    const { hours, minutes, seconds } = this.state;

    return (
      <div className="App">
         <h1 className="title"> (( React Countdown )) </h1>
         <div className="inputGroup">
            <h3>Hrs</h3>
            <input ref={this.hoursInput} type="number" placeholder={0}  name="hours"  onChange={this.inputHandler} />
            <h3>Min</h3>
            <input  ref={this.minutesInput} type="number"  placeholder={0}   name="minutes"  onChange={this.inputHandler} />
            <h3>Sec</h3>
            <input   ref={this.secondsInput} type="number"  placeholder={0}  name="seconds"  onChange={this.inputHandler} />
         </div>
         <div>
            <button onClick={this.startTimer} className="start">start</button>
            <button onClick={this.stopTimer}  className="stop">stop</button>
            <button onClick={this.resetTimer}  className="reset">reset</button>
         </div>
         <h1> Timer {hours}: {minutes} : {seconds} </h1>
      </div>

    );
  }
}

export default App;

What's the proper value for a checked attribute of an HTML checkbox?

Well, to use it i dont think matters (similar to disabled and readonly), personally i use checked="checked" but if you are trying to manipulate them with JavaScript, you use true/false

Align text in a table header

Try using style for th

th {text-align:center}

htaccess redirect to https://www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Notes: Make sure you have done the following steps

  1. sudo a2enmod rewrite
  2. sudo service apache2 restart
  3. Add Following in your vhost file, located at /etc/apache2/sites-available/000-default.conf
<Directory /var/www/html>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  allow from all
  Require all granted
</Directory>

Now your .htaccess will work and your site will redirect to http:// to https://www

Upload file to SFTP using PowerShell

You didn't tell us what particular problem do you have with the WinSCP, so I can really only repeat what's in WinSCP documentation.

  • Download WinSCP .NET assembly.
    The latest package as of now is WinSCP-5.17.10-Automation.zip;

  • Extract the .zip archive along your script;

  • Use a code like this (based on the official PowerShell upload example):

      # Load WinSCP .NET assembly
      Add-Type -Path "WinSCPnet.dll"
    
      # Setup session options
      $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
          Protocol = [WinSCP.Protocol]::Sftp
          HostName = "example.com"
          UserName = "user"
          Password = "mypassword"
          SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
      }
    
      $session = New-Object WinSCP.Session
    
      try
      {
          # Connect
          $session.Open($sessionOptions)
    
          # Upload
          $session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
      }
      finally
      {
          # Disconnect, clean up
          $session.Dispose()
      }
    

You can have WinSCP generate the PowerShell script for the upload for you:

  • Login to your server with WinSCP GUI;
  • Navigate to the target directory in the remote file panel;
  • Select the file for upload in the local file panel;
  • Invoke the Upload command;
  • On the Transfer options dialog, go to Transfer Settings > Generate Code;
  • On the Generate transfer code dialog, select the .NET assembly code tab;
  • Choose PowerShell language.

You will get a code like above with all session and transfer settings filled in.

Generate transfer code dialog

(I'm the author of WinSCP)

JavaScript/jQuery - How to check if a string contain specific words

you can use indexOf for this

var a = 'how are you';
if (a.indexOf('are') > -1) {
  return true;
} else {
  return false;
}

Edit: This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if clause is not required at all because the expression itself is a boolean. Here is a better version of it which you should use,

var a = 'how are you';
return a.indexOf('are') > -1;

Update in ECMAScript2016:

var a = 'how are you';
return a.includes('are');  //true

Use CSS to make a span not clickable

Yes you can.... you can place something on top of the link element.

<!DOCTYPE html>
<html>
<head>
    <title>Yes you CAN</title>
    <style type="text/css">
        ul{
            width: 500px;
            border: 5px solid black; 
        }
        .product-type-simple {
            position: relative;
            height: 150px;
            width: 150px;
        }
        .product-type-simple:before{
            position: absolute;
            height: 100% ;
            width: 100% ;
            content: '';
            background: green;//for debugging purposes , remove this if you want to see whats behind
            z-index: 999999999999;
        }
    </style>
</head>
<body>
<ul>
    <li class='product-type-simple'>
        <a href="/link1">
            <img src="http://placehold.it/150x150">
        </a>
    </li>
    <li class='product-type-simple'>
        <a href="/link2">
            <img src="http://placehold.it/150x150">
        </a>
    </li>
</ul>
</body>
</html>

the magic sauce happens at product-type-simple:before class Whats happening here is that for each element that has class of product-type-simple you create something that has the width and height equal to that of the product-type-simple , then you increase its z-index to make sure it will place it self on top of the content of product-type-simple. You can toggle the background color if you want to see whats going on.

here is an example of the code https://jsfiddle.net/92qky63j/

What are the different NameID format used for?

1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:

Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:

urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:

How to write std::string to file?

remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()

How do I do a simple 'Find and Replace" in MsSQL?

This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:

Argument data type ntext is invalid for argument 1 of replace function.

The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:

UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'

This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!

Twitter Bootstrap dropdown menu

<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js"></script>

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).

import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * This class provide various static methods that relax X509 certificate and
 * hostname verification while using the SSL over the HTTP protocol.
 *  
 * @author Jiramot.info
 */
public final class SSLUtilities {

  /**
   * Hostname verifier for the Sun's deprecated API.
   *
   * @deprecated see {@link #_hostnameVerifier}.
   */
  private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
  /**
   * Thrust managers for the Sun's deprecated API.
   *
   * @deprecated see {@link #_trustManagers}.
   */
  private static com.sun.net.ssl.TrustManager[] __trustManagers;
  /**
   * Hostname verifier.
   */
  private static HostnameVerifier _hostnameVerifier;
  /**
   * Thrust managers.
   */
  private static TrustManager[] _trustManagers;

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames. This method uses the old deprecated API from the
   * com.sun.ssl package.
   *  
   * @deprecated see {@link #_trustAllHostnames()}.
   */
  private static void __trustAllHostnames() {
    // Create a trust manager that does not validate certificate chains
    if (__hostnameVerifier == null) {
        __hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
    } // if
    // Install the all-trusting host name verifier
    com.sun.net.ssl.HttpsURLConnection
            .setDefaultHostnameVerifier(__hostnameVerifier);
  } // __trustAllHttpsCertificates

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones. This method uses the
   * old deprecated API from the com.sun.ssl package.
   *
   * @deprecated see {@link #_trustAllHttpsCertificates()}.
   */
  private static void __trustAllHttpsCertificates() {
    com.sun.net.ssl.SSLContext context;

    // Create a trust manager that does not validate certificate chains
    if (__trustManagers == null) {
        __trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
    } // if
    // Install the all-trusting trust manager
    try {
        context = com.sun.net.ssl.SSLContext.getInstance("SSL");
        context.init(null, __trustManagers, new SecureRandom());
    } catch (GeneralSecurityException gse) {
        throw new IllegalStateException(gse.getMessage());
    } // catch
    com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
            .getSocketFactory());
  } // __trustAllHttpsCertificates

  /**
   * Return true if the protocol handler property java. protocol.handler.pkgs
   * is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
   * one, false otherwise.
   *
   * @return true if the protocol handler property is set to the Sun's
   * deprecated one, false otherwise.
   */
  private static boolean isDeprecatedSSLProtocol() {
    return ("com.sun.net.ssl.internal.www.protocol".equals(System
            .getProperty("java.protocol.handler.pkgs")));
  } // isDeprecatedSSLProtocol

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames.
   */
  private static void _trustAllHostnames() {
      // Create a trust manager that does not validate certificate chains
      if (_hostnameVerifier == null) {
          _hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
      } // if
      // Install the all-trusting host name verifier:
      HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
  } // _trustAllHttpsCertificates

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones.
   */
  private static void _trustAllHttpsCertificates() {
    SSLContext context;

      // Create a trust manager that does not validate certificate chains
      if (_trustManagers == null) {
          _trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
      } // if
      // Install the all-trusting trust manager:
      try {
          context = SSLContext.getInstance("SSL");
          context.init(null, _trustManagers, new SecureRandom());
      } catch (GeneralSecurityException gse) {
          throw new IllegalStateException(gse.getMessage());
      } // catch
      HttpsURLConnection.setDefaultSSLSocketFactory(context
            .getSocketFactory());
  } // _trustAllHttpsCertificates

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames.
   */
  public static void trustAllHostnames() {
      // Is the deprecated protocol setted?
      if (isDeprecatedSSLProtocol()) {
          __trustAllHostnames();
      } else {
          _trustAllHostnames();
      } // else
  } // trustAllHostnames

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones.
   */
  public static void trustAllHttpsCertificates() {
    // Is the deprecated protocol setted?
    if (isDeprecatedSSLProtocol()) {
        __trustAllHttpsCertificates();
    } else {
        _trustAllHttpsCertificates();
    } // else
  } // trustAllHttpsCertificates

  /**
   * This class implements a fake hostname verificator, trusting any host
   * name. This class uses the old deprecated API from the com.sun. ssl
   * package.
   *
   * @author Jiramot.info
   *
   * @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
   */
  public static class _FakeHostnameVerifier implements
        com.sun.net.ssl.HostnameVerifier {

    /**
     * Always return true, indicating that the host name is an acceptable
     * match with the server's authentication scheme.
     *
     * @param hostname the host name.
     * @param session the SSL session used on the connection to host.
     * @return the true boolean value indicating the host name is trusted.
     */
    public boolean verify(String hostname, String session) {
        return (true);
    } // verify
  } // _FakeHostnameVerifier

  /**
   * This class allow any X509 certificates to be used to authenticate the
   * remote side of a secure socket, including self-signed certificates. This
   * class uses the old deprecated API from the com.sun.ssl package.
   *
   * @author Jiramot.info
   *
   * @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
   */
  public static class _FakeX509TrustManager implements
        com.sun.net.ssl.X509TrustManager {

    /**
     * Empty array of certificate authority certificates.
     */
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

    /**
     * Always return true, trusting for client SSL chain peer certificate
     * chain.
     *
     * @param chain the peer certificate chain.
     * @return the true boolean value indicating the chain is trusted.
     */
    public boolean isClientTrusted(X509Certificate[] chain) {
        return (true);
    } // checkClientTrusted

    /**
     * Always return true, trusting for server SSL chain peer certificate
     * chain.
     *
     * @param chain the peer certificate chain.
     * @return the true boolean value indicating the chain is trusted.
     */
    public boolean isServerTrusted(X509Certificate[] chain) {
        return (true);
    } // checkServerTrusted

    /**
     * Return an empty array of certificate authority certificates which are
     * trusted for authenticating peers.
     *
     * @return a empty array of issuer certificates.
     */
    public X509Certificate[] getAcceptedIssuers() {
        return (_AcceptedIssuers);
    } // getAcceptedIssuers
  } // _FakeX509TrustManager

  /**
   * This class implements a fake hostname verificator, trusting any host
   * name.
   *
   * @author Jiramot.info
   */
  public static class FakeHostnameVerifier implements HostnameVerifier {

    /**
     * Always return true, indicating that the host name is an acceptable
     * match with the server's authentication scheme.
     *
     * @param hostname the host name.
     * @param session the SSL session used on the connection to host.
     * @return the true boolean value indicating the host name is trusted.
     */
    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
        return (true);
    } // verify
  } // FakeHostnameVerifier

  /**
   * This class allow any X509 certificates to be used to authenticate the
   * remote side of a secure socket, including self-signed certificates.
   *
   * @author Jiramot.info
   */
  public static class FakeX509TrustManager implements X509TrustManager {

    /**
     * Empty array of certificate authority certificates.
     */
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

    /**
     * Always trust for client SSL chain peer certificate chain with any
     * authType authentication types.
     *
     * @param chain the peer certificate chain.
     * @param authType the authentication type based on the client
     * certificate.
     */
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
    } // checkClientTrusted

    /**
     * Always trust for server SSL chain peer certificate chain with any
     * authType exchange algorithm types.
     *
     * @param chain the peer certificate chain.
     * @param authType the key exchange algorithm used.
     */
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
    } // checkServerTrusted

    /**
     * Return an empty array of certificate authority certificates which are
     * trusted for authenticating peers.
     *
     * @return a empty array of issuer certificates.
     */
    public X509Certificate[] getAcceptedIssuers() {
        return (_AcceptedIssuers);
    } // getAcceptedIssuers
  } // FakeX509TrustManager
} // SSLUtilities

Clear text in EditText when entered

I am not sure if your searching for this one

    {
    <EditText
     .
     . 
     android:hint="Please enter your name here">
    }

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

You are trying to use it as a CSS file, probably by using

<link rel=stylesheet href=ABCD.html>

or

<style>
@import url("ABCD.html");
</style>

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

Cassandra cqlsh - connection refused

try changing the native_transport_protocol to port 9160 (if it is set to anything other than 9160; it might be pointing to 9042). Check your logs and see on which port cassandra is listening for CQL clients?

How to make a smaller RatingBar?

The best answer I got

  <style name="MyRatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:minHeight">15dp</item>
    <item name="android:maxHeight">15dp</item>
    <item name="colorControlNormal">@color/white</item>
    <item name="colorControlActivated">@color/home_add</item>
</style>

user like this

<RatingBar
                style="?android:attr/ratingBarStyleIndicator"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:isIndicator="false"
                android:max="5"
                android:rating="3"
                android:scaleX=".8"
                android:scaleY=".8"
                android:theme="@style/MyRatingBar" />

Increase/Decrease sizes by using scaleX and scaleY value

What is the difference between visibility:hidden and display:none?

They're not synonyms - display: none removes the element from the flow of the page, and rest of the page flows as if it weren't there.

visibility: hidden hides the element from view but not the page flow, leaving space for it on the page.

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

Setting up a git remote origin

You can include the branch to track when setting up remotes, to keep things working as you might expect:

git remote add --track master origin [email protected]:group/project.git   # git
git remote add --track master origin [email protected]:group/project.git   # git w/IP
git remote add --track master origin http://github.com/group/project.git   # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/           # local
git remote add --track master origin G:/group/project/                     # local, Win

This keeps you from having to manually edit your git config or specify branch tracking manually.

Parse an URL in JavaScript

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]

Worked for me. But the first var should be var url = window.location.href

Conditional Replace Pandas

I would use lambda function on a Series of a DataFrame like this:

f = lambda x: 0 if x>100 else 1
df['my_column'] = df['my_column'].map(f)

I do not assert that this is an efficient way, but it works fine.

Using sed to mass rename files

 ls F00001-0708-*|sed 's|^F0000\(.*\)|mv & F000\1|' | bash

How to display the current time and date in C#

DateTime.Now.Tostring();

. You can supply parameters to To string function in a lot of ways like given in this link http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

This will be a lot useful. If you reside somewhere else than the regular format (MM/dd/yyyy)

use always MM not mm, mm gives minutes and MM gives month.

How to change Elasticsearch max memory size

If you installed ES using the RPM/DEB packages as provided (as you seem to have), you can adjust this by editing the init script (/etc/init.d/elasticsearch on RHEL/CentOS). If you have a look in the file you'll see a block with the following:

export ES_HEAP_SIZE
export ES_HEAP_NEWSIZE
export ES_DIRECT_SIZE
export ES_JAVA_OPTS
export JAVA_HOME

To adjust the size, simply change the ES_HEAP_SIZE line to the following:

export ES_HEAP_SIZE=xM/xG

(where x is the number of MB/GB of RAM that you would like to allocate)

Example:

export ES_HEAP_SIZE=1G

Would allocate 1GB.

Once you have edited the script, save and exit, then restart the service. You can check if it has been correctly set by running the following:

ps aux | grep elasticsearch

And checking for the -Xms and -Xmx flags in the java process that returns:

/usr/bin/java -Xms1G -Xmx1G

Hope this helps :)

Trying to check if username already exists in MySQL database using PHP

Here's one that i wrote:

$error = false;
$sql= "SELECT username FROM users WHERE username = '$username'";
$checkSQL = mysqli_query($db, $checkSQL);

if(mysqli_num_rows($checkSQL) != 0) {
   $error = true;
   echo '<span class="error">Username taken.</span>';
}

Works like a charm!

how to append a css class to an element by javascript?

When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.

Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.

document.addClass= function(el, css){
    var tem, C= el.className.split(/\s+/), A=[];    
    while(C.length){
        tem= C.shift();
        if(tem && tem!= css) A[A.length]= tem;
    }
    A[A.length]= css;
    return el.className= A.join(' ');   
}

How to calculate mean, median, mode and range from a set of numbers

As already pointed out by Nico Huysamen, finding multiple mode in Java 1.8 can be done alternatively as below.

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public static void mode(List<Integer> numArr) {
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();;
    Map<Integer, List<Integer>> mode = new HashMap<Integer, List<Integer>>();

    int modeFreq = 1; //record the highest frequence
    for(int x=0; x<numArr.size(); x++) { //1st for loop to record mode
        Integer curr = numArr.get(x); //O(1)
        freq.merge(curr, 1, (a, b) -> a + b); //increment the frequency for existing element, O(1)
        int currFreq = freq.get(curr); //get frequency for current element, O(1)

        //lazy instantiate a list if no existing list, then
        //record mapping of frequency to element (frequency, element), overall O(1)
        mode.computeIfAbsent(currFreq, k -> new ArrayList<>()).add(curr);

        if(modeFreq < currFreq) modeFreq = currFreq; //update highest frequency
    }
    mode.get(modeFreq).forEach(x -> System.out.println("Mode = " + x)); //pretty print the result //another for loop to return result
}

Happy coding!

jQuery: Check if div with certain class name exists

check if the div exists with a certain class

if ($(".mydivclass").length > 0) //it exists 
{

}

Correct Semantic tag for copyright info - html5

it is better to include it in a <small> tag The HTML <small> tag is used for specifying small print.

Small print (also referred to as "fine print" or "mouseprint") usually refers to the part of a document that contains disclaimers, caveats, or legal restrictions, such as copyrights. And this tag is supported in all major browsers.

<footer>
 <small>&copy; Copyright 2058, Example Corporation</small>
</footer>

Sqlite in chrome

I'm not quite sure if you mean 'can i use sqlite (websql) in chrome' or 'can i use sqlite (websql) in firefox', so I'll answer both:

Note that WebSQL is not a full-access pipe into an .sqlite database. It's WebSQL. You will not be able to run some specific queries like VACUUM

It's awesome for Create / Read / Update / Delete though. I made a little library that helps with all the annoying nitty gritty like creating tables and querying and a provides a little ORM/ActiveRecord pattern with relations and all and a huge stack of examples that should get you started in no-time, you can check that here

Also, be aware that if you want to build a FireFox extension: Their extension format is about to change. Make sure you want to invest the time twice.

While the WebSQL spec has been deprecated for years, even now in 2017 still does not look like it will be be removed from Chrome for the foreseeable time. They are tracking usage statistics and there are still a large number of chrome extensions and websites out there in the real world implementing the spec.

How do I compare two variables containing strings in JavaScript?

instead of using the == sign, more safer use the === sign when compare, the code that you post is work well

Android Studio build fails with "Task '' not found in root project 'MyProject'."

This is what I did

  1. Remove .idea folder

    $ mv .idea .idea.bak

  2. Import the project again

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

This errors occurs when we use same method name for Jaxb2Marshaller for exemple:

    @Bean
    public Jaxb2Marshaller marshallerClient() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        marshaller.setContextPath("library.io.github.walterwhites.loans");

        return marshaller;
    }

And on other file

    @Bean
    public Jaxb2Marshaller marshallerClient() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        marshaller.setContextPath("library.io.github.walterwhites.client");

        return marshaller;
    }

Even It's different class, you should named them differently

XPath to select multiple tags

Why not a/b/(c|d|e)? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work. abc.xml is the doc described by OP.

(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
    #<XdmNode <d>D1</d>>
    #<XdmNode <e>E1</e>>
    #<XdmNode <c>C2</c>>
    #<XdmNode <d>D2</d>>
    #<XdmNode <e>E1</e>>)

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

install apt-get on linux Red Hat server

If you insist on using yum, try yum install apt. As read on this site: Link

Get Unix timestamp with C++

As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:

#include <chrono>

//...

using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.

How to align an indented line in a span that wraps into multiple lines?

<span> elements are inline elements, as such layout properties such as width or margin don't work. You can fix that by either changing the <span> to a block element (such as <div>), or by using padding instead.

Note that making a span element a block element by adding display: block; is redundant, as a span is by definition a otherwise style-less inline element whereas div is an otherwise style-less block element. So the correct solution is to use a div instead of a block-span.

Multiline TextBox multiple newline

You need to set the textbox to be multiline, this can be done two ways:

In the control:

<asp:TextBox runat="server" ID="MyBox" TextMode="MultiLine" Rows="10" />

Code Behind:

MyBox.TextMode = TextBoxMode.MultiLine;
MyBox.Rows = 10;

This will render as a <textarea>

Add two numbers and display result in textbox with Javascript

It should be document.getElementById("txtresult").value= result;

You are setting the value of the textbox to the result. The id="txtresult" is not an HTML element.

How to Return partial view of another controller by controller?

Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared folder if shared between controllers (hence the name).

"Answer" (but not recommended - see below):

You can refer to views/partial views from another controller, by specifying the full path (including extension) like:

return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

or a relative path (no extension), based on the answer by @Max Toro

return PartialView("../ABC/XXX", zyxmodel);

BUT THIS IS NOT A GOOD IDEA ANYWAY

*Note: These are the only two syntax that work. not ABC\\XXX or ABC/XXX or any other variation as those are all relative paths and do not find a match.

Better Alternatives:

You can use Html.Renderpartial in your view instead, but it requires the extension as well:

Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);

Use @Html.Partial for inline Razor syntax:

@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)

You can use the ../controller/view syntax with no extension (again credit to @Max Toro):

@Html.Partial("../ControllerName/ViewName", modeldata)

Note: Apparently RenderPartial is slightly faster than Partial, but that is not important.

If you want to actually call the other controller, use:

@Html.Action("action", "controller", parameters)

Recommended solution: @Html.Action

My personal preference is to use @Html.Action as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).

You would normally pass just the required key values (like any other view) e.g. for your example:

@Html.Action("XXX", "ABC", new {id = model.xyzId })

This will execute the ABC.XXX action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).

Update Sep 2014:

I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action and controller names. To that end I added this simple View extension method to UrlHelper so you can say return PartialView(Url.View("actionName", "controllerName"), modelData):

public static class UrlHelperExtension
{
    /// <summary>
    /// Return a view path based on an action name and controller name
    /// </summary>
    /// <param name="url">Context for extension method</param>
    /// <param name="action">Action name</param>
    /// <param name="controller">Controller name</param>
    /// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
    public static string View(this UrlHelper url, string action, string controller)
    {
        return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
    }
}

How do I set the default font size in Vim?

The other answers are what you asked about, but in case it’s useful to anyone else, here’s how to set the font conditionally from the screen DPI (Windows only):

set guifont=default
if has('windows')
    "get dpi, strip out utf-16 garbage and new lines
    "system() converts 0x00 to 0x01 for 'platform independence'
    "should return something like 'PixelsPerXLogicalInch=192'
    "get the part from the = to the end of the line (eg '=192') and strip
    "the first character
    "and convert to a number
    let dpi = str2nr(strpart(matchstr(substitute(
        \system('wmic desktopmonitor get PixelsPerXLogicalInch /value'),
        \'\%x01\|\%x0a\|\%x0a\|\%xff\|\%xfe', '', 'g'),
        \'=.*$'), 1))
    if dpi > 100
        set guifont=high_dpi_font
    endif
endif

How to get a complete list of object's methods and attributes?

Only to supplement:

  1. dir() is the most powerful/fundamental tool. (Most recommended)
  2. Solutions other than dir() merely provide their way of dealing the output of dir().

    Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __, but sometimes you may well need the __doc__ doc-string.

  3. __dir__() and dir() returns identical content.
  4. __dict__ and dir() are different. __dict__ returns incomplete content.
  5. IMPORTANT: __dir__() can be sometimes overwritten with a function, value or type, by the author for whatever purpose.

    Here is an example:

    \\...\\torchfun.py in traverse(self, mod, search_attributes)
    445             if prefix in traversed_mod_names:
    446                 continue
    447             names = dir(m)
    448             for name in names:
    449                 obj = getattr(m,name)
    

    TypeError: descriptor __dir__ of 'object' object needs an argument

    The author of PyTorch modified the __dir__() method to something that requires an argument. This modification makes dir() fail.

  6. If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

Similar to the solution of making sure org.springframework.boot:spring-boot-starter-tomcat was installed, I was missing org.eclipse.jetty:jetty-server from my build.gradle

org.springframework.boot:spring-boot-starter-web needs a server be it Tomcat, Jetty or something else - it will compile but not run without one.

MSIE and addEventListener Problem in Javascript?

The problem is that IE does not have the standard addEventListener method. IE uses its own attachEvent which does pretty much the same.

Good explanation of the differences, and also about the 3rd parameter can be found at quirksmode.

How to extract svg as file from web page

For me its very easy just install following tool in chrome server :

svg-grabber

Once you're on a web page, click the extension's icon next to the URL bar and a new tab will open showing you all the SVG files it found on the page. You can copy an SVG file to your clipboard, download only the few you need, or click the 'Download all SVGs' button to add them all to a zipped file and download them.

For detail check here

Hope it will helpful.

Address already in use: JVM_Bind

Your local port 443 / 8181 / 3820 is used.

If you are on linux/unix:

  • use netstat -an and lsof -n to check who is using this port

If you are on windows

  • use netstat -an and tcpview to check.

Give column name when read csv file pandas

we can do it with a single line of code.

 user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)

How to change colour of blue highlight on select box dropdown

i just found this site that give a cool themes for the select box http://gregfranko.com/jquery.selectBoxIt.js/

and you can try this themes if your problem with the overall look blue - yellow - grey

How can I read and manipulate CSV file data in C++?

More information would be useful.

But the simplest form:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream  data("plop.csv");

    std::string line;
    while(std::getline(data,line))
    {
        std::stringstream  lineStream(line);
        std::string        cell;
        while(std::getline(lineStream,cell,','))
        {
            // You have a cell!!!!
        }
    }
 }

Also see this question: CSV parser in C++

How can I zoom an HTML element in Firefox and Opera?

zoom: 145%;
-moz-transform: scale(1.45);

use this to be on the safer side

What does this GCC error "... relocation truncated to fit..." mean?

Minimal example that generates the error

main.S moves an address into %eax (32-bit).

main.S

_start:
    mov $_start, %eax

linker.ld

SECTIONS
{
    /* This says where `.text` will go in the executable. */
    . = 0x100000000;
    .text :
    {
        *(*)
    }
}

Compile on x86-64:

as -o main.o main.S
ld -o main.out -T linker.ld main.o

Outcome of ld:

(.text+0x1): relocation truncated to fit: R_X86_64_32 against `.text'

Keep in mind that:

  • as puts everything on the .text if no other section is specified
  • ld uses the .text as the default entry point if ENTRY. Thus _start is the very first byte of .text.

How to fix it: use this linker.ld instead, and subtract 1 from the start:

SECTIONS
{
    . = 0xFFFFFFFF;
    .text :
    {
        *(*)
    }
}

Notes:

  • we cannot make _start global in this example with .global _start, otherwise it still fails. I think this happens because global symbols have alignment constraints (0xFFFFFFF0 works). TODO where is that documented in the ELF standard?

  • the .text segment also has an alignment constraint of p_align == 2M. But our linker is smart enough to place the segment at 0xFFE00000, fill with zeros until 0xFFFFFFFF and set e_entry == 0xFFFFFFFF. This works, but generates an oversized executable.

Tested on Ubuntu 14.04 AMD64, Binutils 2.24.

Explanation

First you must understand what relocation is with a minimal example: https://stackoverflow.com/a/30507725/895245

Next, take a look at objdump -Sr main.o:

0000000000000000 <_start>:
   0:   b8 00 00 00 00          mov    $0x0,%eax
                        1: R_X86_64_32  .text

If we look into how instructions are encoded in the Intel manual, we see that:

  • b8 says that this is a mov to %eax
  • 0 is an immediate value to be moved to %eax. Relocation will then modify it to contain the address of _start.

When moving to 32-bit registers, the immediate must also be 32-bit.

But here, the relocation has to modify those 32-bit to put the address of _start into them after linking happens.

0x100000000 does not fit into 32-bit, but 0xFFFFFFFF does. Thus the error.

This error can only happen on relocations that generate truncation, e.g. R_X86_64_32 (8 bytes to 4 bytes), but never on R_X86_64_64.

And there are some types of relocation that require sign extension instead of zero extension as shown here, e.g. R_X86_64_32S. See also: https://stackoverflow.com/a/33289761/895245

R_AARCH64_PREL32

Asked at: How to prevent "main.o:(.eh_frame+0x1c): relocation truncated to fit: R_AARCH64_PREL32 against `.text'" when creating an aarch64 baremetal program?

How do I find the CPU and RAM usage using PowerShell?

To export the output to file on a continuous basis (here every five seconds) and save to a CSV file with the Unix date as the filename:

while ($true) {
     [int]$date = get-date -Uformat %s
     $exportlocation = New-Item -type file -path "c:\$date.csv"
     Get-Counter -Counter "\Processor(_Total)\% Processor Time" | % {$_} | Out-File $exportlocation
     start-sleep -s 5
}

Creating a new column based on if-elif-else condition

For this particular relationship, you could use np.sign:

>>> df["C"] = np.sign(df.A - df.B)
>>> df
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

Another "solution": skip all this frustration and use a UIScrollView instead to get a result that looks and feels identical to UITableView.

That was the painful "solution" for me, after having put in literally 20+ very frustrating hours total trying to build something like what smileyborg suggested and failing over many months and three versions of App Store releases.

My take is that if you really need iOS 7 support (for us, it's essential) then the technology is just too brittle and you'll pull your hair out trying. And that UITableView is complete overkill generally unless you're using some of the advanced row editing features and/or really need to support 1000+ "rows" (in our app, it's realistically never more than 20 rows).

The added bonus is that the code gets insanely simple versus all the delegate crap and back and forth that comes with UITableView. It's just one single loop of code in viewOnLoad that looks elegant and is easy to manage.

Here's some tips on how to do it:

  1. Using either Storyboard or a nib file, create a ViewController and associated root view.

  2. Drag over a UIScrollView onto your root view.

  3. Add constraints top, bottom, left and right constraints to the top-level view so the UIScrollView fills the entire root view.

  4. Add a UIView inside the UIScrollView and call it "container". Add top, bottom, left and right constraints to the UIScrollView (its parent). KEY TRICK: Also add a "Equal widths" constraints to link the UIScrollView and UIView.

    NOTE: You will get an error "scroll view has ambiguous scrollable content height" and that your container UIView should have a height of 0 pixels. Neither error seems to matter when the app is running.

  5. Create nib files and controllers for each of your "cells". Use UIView not UITableViewCell.

  6. In your root ViewController, you essentially add all the "rows" to the container UIView and programmatically add constraints linking their left and right edges to the container view, their top edges to either the container view top (for the first item) or the previous cell. Then link the final cell to the container bottom.

For us, each "row" is in a nib file. So the code looks something like this:

class YourRootViewController {

    @IBOutlet var container: UIView! //container mentioned in step 4

    override func viewDidLoad() {
        
        super.viewDidLoad()

        var lastView: UIView?
        for data in yourDataSource {

            var cell = YourCellController(nibName: "YourCellNibName", bundle: nil)
            UITools.addViewToTop(container, child: cell.view, sibling: lastView)
            lastView = cell.view
            //Insert code here to populate your cell
        }

        if(lastView != nil) {
            container.addConstraint(NSLayoutConstraint(
                item: lastView!,
                attribute: NSLayoutAttribute.Bottom,
                relatedBy: NSLayoutRelation.Equal,
                toItem: container,
                attribute: NSLayoutAttribute.Bottom,
                multiplier: 1,
                constant: 0))
        }

        ///Add a refresh control, if you want - it seems to work fine in our app:
        var refreshControl = UIRefreshControl()
        container.addSubview(refreshControl!)
    }
}

And here's the code for UITools.addViewToTop:

class UITools {
    ///Add child to container, full width of the container and directly under sibling (or container if sibling nil):
    class func addViewToTop(container: UIView, child: UIView, sibling: UIView? = nil)
    {
        child.setTranslatesAutoresizingMaskIntoConstraints(false)
        container.addSubview(child)
        
        //Set left and right constraints so fills full horz width:
        
        container.addConstraint(NSLayoutConstraint(
            item: child,
            attribute: NSLayoutAttribute.Leading,
            relatedBy: NSLayoutRelation.Equal,
            toItem: container,
            attribute: NSLayoutAttribute.Left,
            multiplier: 1,
            constant: 0))
        
        container.addConstraint(NSLayoutConstraint(
            item: child,
            attribute: NSLayoutAttribute.Trailing,
            relatedBy: NSLayoutRelation.Equal,
            toItem: container,
            attribute: NSLayoutAttribute.Right,
            multiplier: 1,
            constant: 0))
        
        //Set vertical position from last item (or for first, from the superview):
        container.addConstraint(NSLayoutConstraint(
            item: child,
            attribute: NSLayoutAttribute.Top,
            relatedBy: NSLayoutRelation.Equal,
            toItem: sibling == nil ? container : sibling,
            attribute: sibling == nil ? NSLayoutAttribute.Top : NSLayoutAttribute.Bottom,
            multiplier: 1,
            constant: 0))
    }
}

The only "gotcha" I've found with this approach so far is that UITableView has a nice feature of "floating" section headers at the top of the view as you scroll. The above solution won't do that unless you add more programming but for our particular case this feature wasn't 100% essential and nobody noticed when it went away.

If you want dividers between your cells, just add a 1 pixel high UIView at the bottom of your custom "cell" that looks like a divider.

Be sure to turn on "bounces" and "bounce vertically" for the refresh control to work and so it seems more like a tableview.

TableView shows some empty rows and dividers under your content, if it doesn't fill the full screen where as this solution doesn't. But personally, I prefer if those empty rows weren't there anyway - with variable cell height it always looked "buggy" to me anyway to have the empty rows in there.

Here's hoping some other programmer reads my post BEFORE wasting 20+ hours trying to figure it out with Table View in their own app. :)

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

As all the other answers show, the problem is that adding a std::string and a const char* using + results in a std::string, while system() expects a const char*. And the solution is to use c_str(). However, you can also do it without a temporary:

string name = "john";
system((" quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'").c_str());

When should I use "this" in a class?

The only need to use the this. qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x and this.x.

How to add hyperlink in JLabel?

Maybe use JXHyperlink from SwingX instead. It extends JButton. Some useful links:

What's the best way to parse command line arguments?

Lightweight command line argument defaults

Although argparse is great and is the right answer for fully documented command line switches and advanced features, you can use function argument defaults to handles straightforward positional arguments very simply.

import sys

def get_args(name='default', first='a', second=2):
    return first, int(second)

first, second = get_args(*sys.argv)
print first, second

The 'name' argument captures the script name and is not used. Test output looks like this:

> ./test.py
a 2
> ./test.py A
A 2
> ./test.py A 20
A 20

For simple scripts where I just want some default values, I find this quite sufficient. You might also want to include some type coercion in the return values or command line values will all be strings.

How do I select last 5 rows in a table without sorting?

When number of rows in table is less than 5 the answers of Matt Hamilton and msuvajac is Incorrect. Because a TOP N rowcount value may not be negative.
A great example can be found Here.

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Spark dataframe: collect () vs select ()

Short answer in bolds:

  • collect is mainly to serialize
    (loss of parallelism preserving all other data characteristics of the dataframe)
    For example with a PrintWriter pw you can't do direct df.foreach( r => pw.write(r) ), must to use collect before foreach, df.collect.foreach(etc).
    PS: the "loss of parallelism" is not a "total loss" because after serialization it can be distributed again to executors.

  • select is mainly to select columns, similar to projection in relational algebra
    (only similar in framework's context because Spark select not deduplicate data).
    So, it is also a complement of filter in the framework's context.


Commenting explanations of other answers: I like the Jeff's classification of Spark operations in transformations (as select) and actions (as collect). It is also good remember that transforms (including select) are lazily evaluated.

Peak signal detection in realtime timeseries data

Thought I would provide my Julia implementation of the algorithm for others. The gist can be found here

using Statistics
using Plots
function SmoothedZscoreAlgo(y, lag, threshold, influence)
    # Julia implimentation of http://stackoverflow.com/a/22640362/6029703
    n = length(y)
    signals = zeros(n) # init signal results
    filteredY = copy(y) # init filtered series
    avgFilter = zeros(n) # init average filter
    stdFilter = zeros(n) # init std filter
    avgFilter[lag - 1] = mean(y[1:lag]) # init first value
    stdFilter[lag - 1] = std(y[1:lag]) # init first value

    for i in range(lag, stop=n-1)
        if abs(y[i] - avgFilter[i-1]) > threshold*stdFilter[i-1]
            if y[i] > avgFilter[i-1]
                signals[i] += 1 # postive signal
            else
                signals[i] += -1 # negative signal
            end
            # Make influence lower
            filteredY[i] = influence*y[i] + (1-influence)*filteredY[i-1]
        else
            signals[i] = 0
            filteredY[i] = y[i]
        end
        avgFilter[i] = mean(filteredY[i-lag+1:i])
        stdFilter[i] = std(filteredY[i-lag+1:i])
    end
    return (signals = signals, avgFilter = avgFilter, stdFilter = stdFilter)
end


# Data
y = [1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
       1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
       2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1]

# Settings: lag = 30, threshold = 5, influence = 0
lag = 30
threshold = 5
influence = 0

results = SmoothedZscoreAlgo(y, lag, threshold, influence)
upper_bound = results[:avgFilter] + threshold * results[:stdFilter]
lower_bound = results[:avgFilter] - threshold * results[:stdFilter]
x = 1:length(y)

yplot = plot(x,y,color="blue", label="Y",legend=:topleft)
yplot = plot!(x,upper_bound, color="green", label="Upper Bound",legend=:topleft)
yplot = plot!(x,results[:avgFilter], color="cyan", label="Average Filter",legend=:topleft)
yplot = plot!(x,lower_bound, color="green", label="Lower Bound",legend=:topleft)
signalplot = plot(x,results[:signals],color="red",label="Signals",legend=:topleft)
plot(yplot,signalplot,layout=(2,1),legend=:topleft)

Results

Safely turning a JSON string into an object

You also can use reviver function to filter.

var data = JSON.parse(jsonString, function reviver(key, value) {
   //your code here to filter
});

For more information read JSON.parse.

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Is it safe to delete the "InetPub" folder?

As long as you go into the IIS configuration and change the default location from %SystemDrive%\InetPub to %SystemDrive%\www for each of the services (web, ftp) there shouldn't be any problems. Of course, you can't protect against other applications that might install stuff into that directory by default, instead of checking the configuration.

My recommendation? Don't change it -- it's not that hard to live with, and it reduces the confusion level for the next person who has to administrate the machine.

Escape double quotes for JSON in Python

>>> s = 'my string with \\"double quotes\\" blablabla'
>>> s
'my string with \\"double quotes\\" blablabla'
>>> print s
my string with \"double quotes\" blablabla
>>> 

When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...

>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>> 

How to use "Share image using" sharing Intent to share images in android?

First add permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

using Bitmap from resources

Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri =  Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));

Tested via bluetooth and other messengers

How can I give an imageview click effect like a button on Android?

For defining the selector drawable choice

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"   
        android:drawable="@drawable/img_down" />
    <item android:state_selected="false"   
        android:drawable="@drawable/img_up" />
</selector>

I have to use android:state_pressed instead of android:state_selected

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed ="true"   
        android:drawable="@drawable/img_down" />
    <item android:state_pressed ="false"   
        android:drawable="@drawable/img_up" />
</selector>

AngularJS ng-style with a conditional expression

For single css property

ng-style="1==1 && {'color':'red'}"

For multiple css properties below can be referred

ng-style="1==1 && {'color':'red','font-style': 'italic'}"

Replace 1==1 with your condition expression