Programs & Examples On #Worker process

How prevent CPU usage 100% because of worker process in iis

There are a lot of reasons that you can be seeing w3wp.exe high CPU usage. I have selected six common causes to cover.

  1. High error rates within your ASP.NET web application
  2. Increase in web traffic causing high CPU
  3. Problems with application dependencies
  4. Garbage collection
  5. Requests getting blocked or hung somewhere in the ASP.NET pipeline
  6. Inefficient .NET code that needs to be optimized

How to prevent scanf causing a buffer overflow in C?

If you are using gcc, you can use the GNU-extension a specifier to have scanf() allocate memory for you to hold the input:

int main()
{
  char *str = NULL;

  scanf ("%as", &str);
  if (str) {
      printf("\"%s\"\n", str);
      free(str);
  }
  return 0;
}

Edit: As Jonathan pointed out, you should consult the scanf man pages as the specifier might be different (%m) and you might need to enable certain defines when compiling.

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

Command copy exited with code 4 when building - Visual Studio restart solves it

As I am writing a DLL library I used the xcopy command to copy the library where the program can find and load it. After several times of opening and closing the program there was still an open process of it in taskmanager which i did not recognized.

Look for any process from which the file may be used and close it.

Why does Lua have no "continue" statement?

In Lua 5.2 the best workaround is to use goto:

-- prints odd numbers in [|1,10|]
for i=1,10 do
  if i % 2 == 0 then goto continue end
  print(i)
  ::continue::
end

This is supported in LuaJIT since version 2.0.1

Show values from a MySQL database table inside a HTML table on a webpage

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
     border: 1px solid black;
}
</style>
</head>
<center>
<body>

<?php

$con = mysql_connect("localhost","root","");
mysql_select_db("rachna",$con);



$query = "SELECT SUM( Ivalue ) AS RESULT FROM loan WHERE cname = 'A' GROUP BY Iyear";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) > 0) {
     echo "<table><tr><th></th><th>1999</th><th>2000</th><th>2001</th><th>2003</th></tr>";
     echo "<th>A</th>"; 

     //Code for A Customer-------------------------------------------
     while($row =mysql_fetch_array($result)) {
         echo "<th>" . $row['RESULT'] . "</th>";
         }

          echo"<tr></tr>";  

           //COde of B Customer--------------------------------------

         echo "<th>B</th>";
     $query = "SELECT SUM( Ivalue ) AS RESULT FROM loan WHERE cname = 'B' GROUP BY Iyear";
    $result1 = mysql_query($query) or die(mysql_error());


     while($row = mysql_fetch_array($result1)) {
         echo "<th> " . $row["RESULT"]. "</th>";
     }
     echo "</table>";
} else {
     echo "0 results";
}


?>  
</center>
</body>
</html>

Replace string in text file using PHP

Thanks to your comments. I've made a function that give an error message when it happens:

/**
 * Replaces a string in a file
 *
 * @param string $FilePath
 * @param string $OldText text to be replaced
 * @param string $NewText new text
 * @return array $Result status (success | error) & message (file exist, file permissions)
 */
function replace_in_file($FilePath, $OldText, $NewText)
{
    $Result = array('status' => 'error', 'message' => '');
    if(file_exists($FilePath)===TRUE)
    {
        if(is_writeable($FilePath))
        {
            try
            {
                $FileContent = file_get_contents($FilePath);
                $FileContent = str_replace($OldText, $NewText, $FileContent);
                if(file_put_contents($FilePath, $FileContent) > 0)
                {
                    $Result["status"] = 'success';
                }
                else
                {
                   $Result["message"] = 'Error while writing file';
                }
            }
            catch(Exception $e)
            {
                $Result["message"] = 'Error : '.$e;
            }
        }
        else
        {
            $Result["message"] = 'File '.$FilePath.' is not writable !';
        }
    }
    else
    {
        $Result["message"] = 'File '.$FilePath.' does not exist !';
    }
    return $Result;
}

Delete forked repo from GitHub

select project to delete->settings->buttom click delete button->enter name of the repositories

Run jar file in command prompt

Try this

java -jar <jar-file-name>.jar

Getting number of elements in an iterator in Python

No. It's not possible.

Example:

import random

def gen(n):
    for i in xrange(n):
        if random.randint(0, 1) == 0:
            yield i

iterator = gen(10)

Length of iterator is unknown until you iterate through it.

Nginx location priority

From the HTTP core module docs:

  1. Directives with the "=" prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the "^~" prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

Example from the documentation:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

If it's still confusing, here's a longer explanation.

PHP Fatal error: Cannot redeclare class

I had the same problem "PHP Fatal error: Cannot redeclare class XYZ.php".

I have two directories like controller and model and I uploaded by mistakenly XYZ.php in both directories.(so file with the same name cause the issue).

First solution:

Find in your whole project and make sure you have only one class XYZ.php.

Second solution:

Add a namespace in your class so you can use the same class name.

Does static constexpr variable inside a function make sense?

In addition to given answer, it's worth noting that compiler is not required to initialize constexpr variable at compile time, knowing that the difference between constexpr and static constexpr is that to use static constexpr you ensure the variable is initialized only once.

Following code demonstrates how constexpr variable is initialized multiple times (with same value though), while static constexpr is surely initialized only once.

In addition the code compares the advantage of constexpr against const in combination with static.

#include <iostream>
#include <string>
#include <cassert>
#include <sstream>

const short const_short = 0;
constexpr short constexpr_short = 0;

// print only last 3 address value numbers
const short addr_offset = 3;

// This function will print name, value and address for given parameter
void print_properties(std::string ref_name, const short* param, short offset)
{
    // determine initial size of strings
    std::string title = "value \\ address of ";
    const size_t ref_size = ref_name.size();
    const size_t title_size = title.size();
    assert(title_size > ref_size);

    // create title (resize)
    title.append(ref_name);
    title.append(" is ");
    title.append(title_size - ref_size, ' ');

    // extract last 'offset' values from address
    std::stringstream addr;
    addr << param;
    const std::string addr_str = addr.str();
    const size_t addr_size = addr_str.size();
    assert(addr_size - offset > 0);

    // print title / ref value / address at offset
    std::cout << title << *param << " " << addr_str.substr(addr_size - offset) << std::endl;
}

// here we test initialization of const variable (runtime)
void const_value(const short counter)
{
    static short temp = const_short;
    const short const_var = ++temp;
    print_properties("const", &const_var, addr_offset);

    if (counter)
        const_value(counter - 1);
}

// here we test initialization of static variable (runtime)
void static_value(const short counter)
{
    static short temp = const_short;
    static short static_var = ++temp;
    print_properties("static", &static_var, addr_offset);

    if (counter)
        static_value(counter - 1);
}

// here we test initialization of static const variable (runtime)
void static_const_value(const short counter)
{
    static short temp = const_short;
    static const short static_var = ++temp;
    print_properties("static const", &static_var, addr_offset);

    if (counter)
        static_const_value(counter - 1);
}

// here we test initialization of constexpr variable (compile time)
void constexpr_value(const short counter)
{
    constexpr short constexpr_var = constexpr_short;
    print_properties("constexpr", &constexpr_var, addr_offset);

    if (counter)
        constexpr_value(counter - 1);
}

// here we test initialization of static constexpr variable (compile time)
void static_constexpr_value(const short counter)
{
    static constexpr short static_constexpr_var = constexpr_short;
    print_properties("static constexpr", &static_constexpr_var, addr_offset);

    if (counter)
        static_constexpr_value(counter - 1);
}

// final test call this method from main()
void test_static_const()
{
    constexpr short counter = 2;

    const_value(counter);
    std::cout << std::endl;

    static_value(counter);
    std::cout << std::endl;

    static_const_value(counter);
    std::cout << std::endl;

    constexpr_value(counter);
    std::cout << std::endl;

    static_constexpr_value(counter);
    std::cout << std::endl;
}

Possible program output:

value \ address of const is               1 564
value \ address of const is               2 3D4
value \ address of const is               3 244

value \ address of static is              1 C58
value \ address of static is              1 C58
value \ address of static is              1 C58

value \ address of static const is        1 C64
value \ address of static const is        1 C64
value \ address of static const is        1 C64

value \ address of constexpr is           0 564
value \ address of constexpr is           0 3D4
value \ address of constexpr is           0 244

value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0

As you can see yourself constexpr is initilized multiple times (address is not the same) while static keyword ensures that initialization is performed only once.

The calling thread cannot access this object because a different thread owns it

The problem is that you are calling GetGridData from a background thread. This method accesses several WPF controls which are bound to the main thread. Any attempt to access them from a background thread will lead to this error.

In order to get back to the correct thread you should use SynchronizationContext.Current.Post. However in this particular case it seems like the majority of the work you are doing is UI based. Hence you would be creating a background thread just to go immediately back to the UI thread and do some work. You need to refactor your code a bit so that it can do the expensive work on the background thread and then post the new data to the UI thread afterwards

How to lowercase a pandas dataframe string column if it has missing values?

Pandas >= 0.25: Remove Case Distinctions with str.casefold

Starting from v0.25, I recommend using the "vectorized" string method str.casefold if you're dealing with unicode data (it works regardless of string or unicodes):

s = pd.Series(['lower', 'CAPITALS', np.nan, 'SwApCaSe'])
s.str.casefold()

0       lower
1    capitals
2         NaN
3    swapcase
dtype: object

Also see related GitHub issue GH25405.

casefold lends itself to more aggressive case-folding comparison. It also handles NaNs gracefully (just as str.lower does).

But why is this better?

The difference is seen with unicodes. Taking the example in the python str.casefold docs,

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

Compare the output of lower for,

s = pd.Series(["der Fluß"])
s.str.lower()

0    der fluß
dtype: object

Versus casefold,

s.str.casefold()

0    der fluss
dtype: object

Also see Python: lower() vs. casefold() in string matching and converting to lowercase.

How to increment datetime by custom months in python without using library

from datetime import timedelta
try:
    next = (x.replace(day=1) + timedelta(days=31)).replace(day=x.day)
except ValueError:  # January 31 will return last day of February.
    next = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)

If you simply want the first day of the next month:

next = (x.replace(day=1) + timedelta(days=31)).replace(day=1)

How to flatten only some dimensions of a numpy array

Take a look at numpy.reshape .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

How to include clean target in Makefile?

In makefile language $@ means "name of the target", so rm -f $@ translates to rm -f clean.

You need to specify to rm what exactly you want to delete, like rm -f *.o code1 code2

Querying a linked sql server

SELECT * FROM [server].[database].[schema].[table]

This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.

How to replace a char in string with an Empty character in C#.NET

This seems too simple, but:

val.Replace("-","");

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

How to test if a string contains one of the substrings in a list, in pandas?

One option is just to use the regex | character to try to match each of the substrings in the words in your Series s (still using str.contains).

You can construct the regex by joining the words in searchfor with |:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $ and ^ which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.

You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape:

>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']

The strings with in this new list will match each character literally when used with str.contains.

How do I install Keras and Theano in Anaconda Python on Windows?

It is my solution for the same problem

  • Install TDM GCC x64.
  • Install Anaconda x64.
  • Open the Anaconda prompt
  • Run conda update conda
  • Run conda update --all
  • Run conda install mingw libpython
  • Install the latest version of Theano, pip install git+git://github.com/Theano/Theano.git
  • Run pip install git+git://github.com/fchollet/keras.git

How to compress an image via Javascript in the browser?

i improved the function a head to be this :

var minifyImg = function(dataUrl,newWidth,imageType="image/jpeg",resolve,imageArguments=0.7){
    var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;
    (new Promise(function(resolve){
      image = new Image(); image.src = dataUrl;
      log(image);
      resolve('Done : ');
    })).then((d)=>{
      oldWidth = image.width; oldHeight = image.height;
      log([oldWidth,oldHeight]);
      newHeight = Math.floor(oldHeight / oldWidth * newWidth);
      log(d+' '+newHeight);

      canvas = document.createElement("canvas");
      canvas.width = newWidth; canvas.height = newHeight;
      log(canvas);
      ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, newWidth, newHeight);
      //log(ctx);
      newDataUrl = canvas.toDataURL(imageType, imageArguments);
      resolve(newDataUrl);
    });
  };

the use of it :

minifyImg(<--DATAURL_HERE-->,<--new width-->,<--type like image/jpeg-->,(data)=>{
   console.log(data); // the new DATAURL
});

enjoy ;)

How to make IPython notebook matplotlib plot inline

Ctrl + Enter

%matplotlib inline

Magic Line :D

See: Plotting with Matplotlib.

Jackson how to transform JsonNode to ArrayNode without casting?

I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )

Best practices for styling HTML emails

Campaign Monitor have an excellent support matrix detailing what's supported and what isn't among various mail clients.

You can use a service like Litmus to view how an email appears across several clients and whether they get caught by filters, etc.

How do I use this JavaScript variable in HTML?

You can create a <p> element:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <script>_x000D_
  var name = prompt("What's your name?");_x000D_
  var lengthOfName = name.length_x000D_
  p = document.createElement("p");_x000D_
  p.innerHTML = "Your name is "+lengthOfName+" characters long.";_x000D_
  document.body.appendChild(p);_x000D_
  </script>_x000D_
  <body>_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

Get height and width of a layout programmatically

Most easiest way is to use ViewTreeObserver, if you directly use .height or .width you get values as 0, due to views are not have size until they draw on our screen. Following example will show how to use ViewTreeObserver

ViewTreeObserver viewTreeObserver = YOUR_VIEW_TO_MEASURE.getViewTreeObserver();
        if (viewTreeObserver.isAlive()) {
            viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {

                    YOUR_VIEW_TO_MEASURE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    int viewHeight = YOUR_VIEW_TO_MEASURE.getHeight();
                    int viewWeight = YOUR_VIEW_TO_MEASURE.getWidth();

                }
            });
        }

if you need to use this on method, use like this and to save the values you can use globle variables.

Animate visibility modes, GONE and VISIBLE

There is no easy way to animate hiding/showing views. You can try method described in following answer: How do I animate View.setVisibility(GONE)

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

You can do this go to Settings > Storage, clicking on the setting menu icon in the top right hand corner and selecting "USB computer connection". I then changed the storage mode to "Camera (PTP)". Done try re installing the driver from device manager.

Structs data type in php?

Closest you'd get to a struct is an object with all members public.

class MyStruct {
    public $foo;
    public $bar;
}

$obj = new MyStruct();
$obj->foo = 'Hello';
$obj->bar = 'World';

I'd say looking at the PHP Class Documentation would be worth it. If you need a one-off struct, use the StdObject as mentioned in alex's answer.

Creating a generic method in C#

Convert.ChangeType() doesn't correctly handle nullable types or enumerations in .NET 2.0 BCL (I think it's fixed for BCL 4.0 though). Rather than make the outer implementation more complex, make the converter do more work for you. Here's an implementation I use:

public static class Converter
{
  public static T ConvertTo<T>(object value)
  {
    return ConvertTo(value, default(T));
  }

  public static T ConvertTo<T>(object value, T defaultValue)
  {
    if (value == DBNull.Value)
    {
      return defaultValue;
    }
    return (T) ChangeType(value, typeof(T));
  }

  public static object ChangeType(object value, Type conversionType)
  {
    if (conversionType == null)
    {
      throw new ArgumentNullException("conversionType");
    }

    // if it's not a nullable type, just pass through the parameters to Convert.ChangeType
    if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
      // null input returns null output regardless of base type
      if (value == null)
      {
        return null;
      }

      // it's a nullable type, and not null, which means it can be converted to its underlying type,
      // so overwrite the passed-in conversion type with this underlying type
      conversionType = Nullable.GetUnderlyingType(conversionType);
    }
    else if (conversionType.IsEnum)
    {
      // strings require Parse method
      if (value is string)
      {
        return Enum.Parse(conversionType, (string) value);          
      }
      // primitive types can be instantiated using ToObject
      else if (value is int || value is uint || value is short || value is ushort || 
           value is byte || value is sbyte || value is long || value is ulong)
      {
        return Enum.ToObject(conversionType, value);
      }
      else
      {
        throw new ArgumentException(String.Format("Value cannot be converted to {0} - current type is " +
                              "not supported for enum conversions.", conversionType.FullName));
      }
    }

    return Convert.ChangeType(value, conversionType);
  }
}

Then your implementation of GetQueryString<T> can be:

public static T GetQueryString<T>(string key)
{
    T result = default(T);
    string value = HttpContext.Current.Request.QueryString[key];

    if (!String.IsNullOrEmpty(value))
    {
        try
        {
            result = Converter.ConvertTo<T>(value);  
        }
        catch
        {
            //Could not convert.  Pass back default value...
            result = default(T);
        }
    }

    return result;
}

What's the difference between "Layers" and "Tiers"?

Read Scott Hanselman's post on the issue: http://www.hanselman.com/blog/AReminderOnThreeMultiTierLayerArchitectureDesignBroughtToYouByMyLateNightFrustrations.aspx

Remember though, that in "Scott World" (which is hopefully your world also :) ) a "Tier" is a unit of deployment, while a "Layer" is a logical separation of responsibility within code. You may say you have a "3-tier" system, but be running it on one laptop. You may say your have a "3-layer" system, but have only ASP.NET pages that talk to a database. There's power in precision, friends.

Bootstrap with jQuery Validation Plugin

for total compatibility with twitter bootstrap 3, I need to override some plugins methods:

// override jquery validate plugin defaults
$.validator.setDefaults({
    highlight: function(element) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-error');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }
});

See Example: http://jsfiddle.net/mapb_1990/hTPY7/7/

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

If you want to convert string to double data type then most choose parseDouble() method. See the example code:

String str = "123.67";
double d = parseDouble(str);

You will get the value in double. See the StringToDouble tutorial at tutorialData.

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I have encounter this issue too. And I'm running in XP SP3.

The following website http://www.docin.com/p-60410380.html# pointing out the solution. But it's simplified Chinese.

I translated its main idea into English here.

run regedit; open HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DirectX Then you must change the following two items: Item 1: Name: Version, Type:REG_SZ, The value should be a rather little number to make the installation success.

Item 2: Name: SDKVersion. But in your machine, the name can be different, for example, it can be ManagedDirectXVersion. But the type should be REG_SZ. Type:REG_SZ, The value should be a rather little number to make the installation success.

In fact, you can refer to the DirectX.lgo file to find the exact version number.

It works for me.

no operator "<<" matches these operands

If you want to use std::string reliably, you must #include <string>.

Java stack overflow error - how to increase the stack size in Eclipse?

Add the flag -Xss1024k in the VM Arguments.

You can also increase stack size in mb by using -Xss1m for example .

What is the proper way to re-throw an exception in C#?

You should always use following syntax to rethrow an exception, else you'll stomp the stack trace:

throw;

If you print the trace resulting from "throw ex", you'll see that it ends on that statement and not at the real source of the exception.

Basically, it should be deemed a criminal offense to use "throw ex".

How to hide iOS status bar

From UIKit>UIApplication.h:

// Setting statusBarHidden does nothing if your application is using the default UIViewController-based status bar system.
@property(nonatomic,getter=isStatusBarHidden) BOOL statusBarHidden;
- (void)setStatusBarHidden:(BOOL)hidden withAnimation:(UIStatusBarAnimation)animation NS_AVAILABLE_IOS(3_2);

So should set View controller-based status bar appearance to NO

How to update the constant height constraint of a UIView programmatically?

Create an IBOutlet of NSLayoutConstraint of yourView and update the constant value accordingly the condition specifies.

//Connect them from Interface 
@IBOutlet viewHeight: NSLayoutConstraint! 
@IBOutlet view: UIView!

private func updateViewHeight(height:Int){
   guard let aView = view, aViewHeight = viewHeight else{
      return
   }
   aViewHeight.constant = height
   aView.layoutIfNeeded()
}

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one()_x000D_
{_x000D_
    alert("The function called 'function_one' has been called.")_x000D_
    //Here u would like to call function_two._x000D_
    function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
    alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
_x000D_
_x000D_

How to align a div to the top of its parent but keeping its inline-block behaviour?

Try the vertical-align CSS property.

#box1 {
    width: 50px;
    height: 50px;
    background: #999;
    display: inline-block;
    vertical-align: top; /* here */
}

Apply it to #box3 too.

Reverse a string in Python

This class uses python magic functions to reverse a string:

class Reverse(object):
    """ Builds a reverse method using magic methods """

    def __init__(self, data):
        self.data = data
        self.index = len(data)


    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration

        self.index = self.index - 1
        return self.data[self.index]


REV_INSTANCE = Reverse('hello world')

iter(REV_INSTANCE)

rev_str = ''
for char in REV_INSTANCE:
    rev_str += char

print(rev_str)  

Output

dlrow olleh

Reference

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

Is mongodb running?

I know this is for php, but I got here looking for a solution for node. Using mongoskin:

mongodb.admin().ping(function(err) {
    if(err === null)
        // true - you got a conntion, congratulations
    else if(err.message.indexOf('failed to connect') !== -1)
        // false - database isn't around
    else
        // actual error, do something about it
})

With other drivers, you can attempt to make a connection and if it fails, you know the mongo server's down. Mongoskin needs to actually make some call (like ping) because it connects lazily. For php, you can use the try-to-connect method. Make a script!

PHP:

$dbIsRunning = true
try {
  $m = new MongoClient('localhost:27017');
} catch($e) {
  $dbIsRunning = false
}

Invariant Violation: _registerComponent(...): Target container is not a DOM element

If you use webpack for rendering your react and use HtmlWebpackPlugin in your react,this plugin builds its blank index.html by itself and injects js file in it,so it does not contain div element,as HtmlWebpackPlugin docs you can build your own index.html and give its address to this plugin, in my webpack.config.js

plugins: [            
    new HtmlWebpackPlugin({
        title: 'dev',
        template: 'dist/index.html'
    })
],

and this is my index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="shortcut icon" href="">
    <meta name="viewport" content="width=device-width">
    <title>Epos report</title>
</head>
<body>
   <div id="app"></div>
   <script src="./bundle.js"></script>
</body>
</html>

Android - Center TextView Horizontally in LinearLayout

Use android:gravity="center" in TextView instead of layout_gravity.

Show a child form in the centre of Parent form in C#

You can set the StartPosition in the constructor of the child form so that all new instances of the form get centered to it's parent:

public MyForm()
{
    InitializeComponent();

    this.StartPosition = FormStartPosition.CenterParent;
}

Of course, you could also set the StartPosition property in the Designer properties for your child form. When you want to display the child form as a modal dialog, just set the window owner in the parameter for the ShowDialog method:

private void buttonShowMyForm_Click(object sender, EventArgs e)
{
    MyForm form = new MyForm();
    form.ShowDialog(this);
}

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

You can set HorizontalAlignment to Left, set your MaxWidth and then bind Width to the ActualWidth of the parent element:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel Name="Container">   
    <TextBox Background="Azure" 
    Width="{Binding ElementName=Container,Path=ActualWidth}"
    Text="Hello" HorizontalAlignment="Left" MaxWidth="200" />
  </StackPanel>
</Page>

Symfony 2 EntityManager injection in service

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

Check my post How to use Repository with Doctrine as Service in Symfony for more general description.


To your specific case, original code with tuning would look like this:

1. Use in your services or Controller

<?php

namespace Test\CommonBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class UserService
{
    private $userRepository;

    // use custom repository over direct use of EntityManager
    // see step 2
    public function __constructor(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        return $this->userRepository->find($userId);
    }
}

2. Create new custom repository

<?php

namespace Test\CommonBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(UserEntity::class);
    }

    public function find($userId)
    {
        return  $this->repository->find($userId);
    }
}

3. Register services

# app/config/services.yml
services:
    _defaults:
        autowire: true

    Test\CommonBundle\:
       resource: ../../Test/CommonBundle

JPA Native Query select and cast object

When your native query is based on joins, in that case you can get the result as list of objects and process it.

one simple example.

@Autowired
EntityManager em;

    String nativeQuery = "select name,age from users where id=?";   
    Query query = em.createNativeQuery(nativeQuery);
    query.setParameter(1,id);

    List<Object[]> list = query.getResultList();

    for(Object[] q1 : list){

        String name = q1[0].toString();
        //..
        //do something more on 
     }

What's the difference between Visual Studio Community and other, paid versions?

Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!

How to append a newline to StringBuilder

Escape should be done with \, not /.

So r.append('\n'); or r.append("\n"); will work (StringBuilder has overloaded methods for char and String type).

Variable not accessible when initialized outside function

My guess is that the system-status element is declared after the variable declaration is run. Thus, at the time the variable is declared, it is actually being set to null?

You should declare it only, then assign its value from an onLoad handler instead, because then you will be sure that it has properly initialized (loaded) the element in question.

You could also try putting the script at the bottom of the page (or at least somewhere after the system-status element is declared) but it's not guaranteed to always work.

c# regex matches example

This pattern should work:

#\d

foreach(var match in System.Text.RegularExpressions.RegEx.Matches(input, "#\d"))
{
    Console.WriteLine(match.Value);
}

(I'm not in front of Visual Studio, but even if that doesn't compile as-is, it should be close enough to tweak into something that works).

Open web in new tab Selenium + Python

In a discussion, Simon clearly mentioned that:

While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.


Using Selenium v3.x opening a website in a New Tab through Python is much easier now. We have to induce an WebDriverWait for number_of_windows_to_be(2) and then collect the window handles every time we open a new tab/window and finally iterate through the window handles and switchTo().window(newly_opened) as required. Here is a solution where you can open http://www.google.co.in in the initial TAB and https://www.yahoo.com in the adjacent TAB:

  • Code Block:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("http://www.google.co.in")
    print("Initial Page Title is : %s" %driver.title)
    windows_before  = driver.current_window_handle
    print("First Window Handle is : %s" %windows_before)
    driver.execute_script("window.open('https://www.yahoo.com')")
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
    windows_after = driver.window_handles
    new_window = [x for x in windows_after if x != windows_before][0]
    driver.switch_to_window(new_window)
    print("Page Title after Tab Switching is : %s" %driver.title)
    print("Second Window Handle is : %s" %new_window)
    
  • Console Output:

    Initial Page Title is : Google
    First Window Handle is : CDwindow-B2B3DE3A222B3DA5237840FA574AF780
    Page Title after Tab Switching is : Yahoo
    Second Window Handle is : CDwindow-D7DA7666A0008ED91991C623105A2EC4
    
  • Browser Snapshot:

multiple__tabs


Outro

You can find the based discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium

How to access the value of a promise?

I am a slow learner of javascript promises, by default all async functions return a promise, you can wrap your result as:

(async () => {
//Optional "await"
  await yourAsyncFunctionOrPromise()
    .then(function (result) {
      return result +1;
    })
    .catch(function (error) {
      return error;
    })()
})

"The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise. If the Promise is rejected, the await expression throws the rejected value."

Read more about await and promises at MDN Web Docs

Apply CSS to jQuery Dialog Buttons

You can use the open event handler to apply additional styling:

 open: function(event) {
     $('.ui-dialog-buttonpane').find('button:contains("Cancel")').addClass('cancelButton');
 }

Redirection of standard and error output appending to the same log file

Andy gave me some good pointers, but I wanted to do it in an even cleaner way. Not to mention that with the 2>&1 >> method PowerShell complained to me about the log file being accessed by another process, i.e. both stderr and stdout trying to lock the file for access, I guess. So here's how I worked it around.

First let's generate a nice filename, but that's really just for being pedantic:

$name = "sync_common"
$currdate = get-date -f yyyy-MM-dd
$logfile = "c:\scripts\$name\log\$name-$currdate.txt"

And here's where the trick begins:

start-transcript -append -path $logfile

write-output "starting sync"
robocopy /mir /copyall S:\common \\10.0.0.2\common 2>&1 | Write-Output
some_other.exe /exeparams 2>&1 | Write-Output
...
write-output "ending sync"

stop-transcript

With start-transcript and stop-transcript you can redirect ALL output of PowerShell commands to a single file, but it doesn't work correctly with external commands. So let's just redirect all the output of those to the stdout of PS and let transcript do the rest.

In fact, I have no idea why the MS engineers say they haven't fixed this yet "due to the high cost and technical complexities involved" when it can be worked around in such a simple way.

Either way, running every single command with start-process is a huge clutter IMHO, but with this method, all you gotta do is append the 2>&1 | Write-Output code to each line which runs external commands.

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

Python executable not finding libpython shared library

I had the same problem and I solved it this way:

If you know where libpython resides at, I supposed it would be /usr/local/lib/libpython2.7.so.1.0 in your case, you can just create a symbolic link to it:

sudo ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/lib/libpython2.7.so.1.0

Then try running ldd again and see if it worked.

How to get the system uptime in Windows?

Two ways to do that..

Option 1:

1.  Go to "Start" -> "Run".

2.  Write "CMD" and press on "Enter" key.

3.  Write the command "net statistics server" and press on "Enter" key.

4.  The line that start with "Statistics since …" provides the time that the server was up from.


  The command "net stats srv" can be use instead.

Option 2:

Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher

http://support.microsoft.com/kb/232243

Hope it helped you!!

Mysql service is missing

Go to

C:\Program Files\MySQL\MySQL Server 5.2\bin

then Open MySQLInstanceConfig file

then complete the wizard.

Click finish

Solve the problem

I think this is the best way to change the port number also.

It works for me

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

The solutions above though they will get the job done do so at the risk of dropping user permissions. I prefer to do my create or replace views or stored procedures as follows.

IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_myView]'))
    EXEC sp_executesql N'CREATE VIEW [dbo].[vw_myView] AS SELECT ''This is a code stub which will be replaced by an Alter Statement'' as [code_stub]'
GO

ALTER VIEW [dbo].[vw_myView]
AS
SELECT 'This is a code which should be replaced by the real code for your view' as [real_code]
GO

How to select a div element in the code-behind page?

Give ID and attribute runat='server' as :

<div class="tab-pane active" id="portlet_tab1" runat="server">

//somecode Codebehind:

Access at code behind

    Control Test = Page.FindControl("portlet_tab1");
    Test.Style.Add("display", "none"); 

    or 

    portlet_tab1.Style.Add("display", "none"); 

Simplest two-way encryption using PHP

PHP 7.2 moved completely away from Mcrypt and the encryption now is based on the maintainable Libsodium library.

All your encryption needs can be basically resolved through Libsodium library.

// On Alice's computer:
$msg = 'This comes from Alice.';
$signed_msg = sodium_crypto_sign($msg, $secret_sign_key);


// On Bob's computer:
$original_msg = sodium_crypto_sign_open($signed_msg, $alice_sign_publickey);
if ($original_msg === false) {
    throw new Exception('Invalid signature');
} else {
    echo $original_msg; // Displays "This comes from Alice."
}

Libsodium documentation: https://github.com/paragonie/pecl-libsodium-doc

Update Git branches from master

If you've been working on a branch on-and-off, or lots has happened in other branches while you've been working on something, it's best to rebase your branch onto master. This keeps the history tidy and makes things a lot easier to follow.

git checkout master
git pull
git checkout local_branch_name
git rebase master
git push --force # force required if you've already pushed

Notes:

  • Don't rebase branches that you've collaborated with others on.
  • You should rebase on the branch to which you will be merging which may not always be master.

There's a chapter on rebasing at http://git-scm.com/book/ch3-6.html, and loads of other resources out there on the web.

How can I compare a date and a datetime in Python?

Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:

datetime.datetime(d.year, d.month, d.day)

Suggestion:

from datetime import datetime

def ensure_datetime(d):
    """
    Takes a date or a datetime as input, outputs a datetime
    """
    if isinstance(d, datetime):
        return d
    return datetime.datetime(d.year, d.month, d.day)

def datetime_cmp(d1, d2):
    """
    Compares two timestamps.  Tolerates dates.
    """
    return cmp(ensure_datetime(d1), ensure_datetime(d2))

Send attachments with PHP Mail()?

you can send regular or attachment emails using this class that I created.

here is the link with examples of how to use it.

https://github.com/jerryurenaa/EZMAIL/blob/main/SMTP/Mail.php

How to mount host volumes into docker containers in Dockerfile during build

It's ugly, but I achieved a semblance of this like so:

Dockerfile:

FROM foo
COPY ./m2/ /root/.m2
RUN stuff

imageBuild.sh:

docker build . -t barImage
container="$(docker run -d barImage)"
rm -rf ./m2
docker cp "$container:/root/.m2" ./m2
docker rm -f "$container"

I have a java build that downloads the universe into /root/.m2, and did so every single time. imageBuild.sh copies the contents of that folder onto the host after the build, and Dockerfile copies them back into the image for the next build.

This is something like how a volume would work (i.e. it persists between builds).

The thread has exited with code 0 (0x0) with no unhandled exception

if your application uses threads directly or indirectly (i.e. behind the scene like in a 3rd-party library) it is absolutely common to have threads terminate after they are done... which is basically what you describe... the debugger shows this message... you can configure the debugger to not display this message if you don't want it...

If the above does not help then please provide more details since I am not sure what exactly the problem is you face...

How to output git log with the first line only?

if you only want the first line of the messages (the subject):

git log --pretty=format:"%s"

and if you want all the messages on this branch going back to master:

git log --pretty=format:"%s" master..HEAD

Last but not least, if you want to add little bullets for quick markdown release notes:

git log --pretty=format:"- %s" master..HEAD

Spring MVC - How to return simple String as JSON in Rest Controller

Add this annotation to your method

@RequestMapping(value = "/getString", method = RequestMethod.GET, produces = "application/json")

Open fancybox from function

if jQuery.fancybox.open is not available (on fancybox 1.3.4) you may need to use semafor to get around the recursion problem:

<a href="/index.html" onclick="return myfunction(this)">click me</a>

<script>

var clickSemafor = false;
myfunction(el)
{
 if (!clickSemafor) {
   clickSemafor = true; 
   return false; // do nothing here when in recursion
 }
 var e = jQuery(el); 
 e.fancybox({
    type: 'iframe',
    href: el.href
  }); 
 e.click();  // you could also use e.trigger('click');
 return false; // prevent default

}
</script>

How to insert a SQLite record with a datetime set to 'now' in Android application?

Method 1

CURRENT_TIME – Inserts only time
CURRENT_DATE – Inserts only date
CURRENT_TIMESTAMP – Inserts both time and date

CREATE TABLE users(
    id INTEGER PRIMARY KEY,
    username TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

Method 2

db.execSQL("INSERT INTO users(username, created_at) 
            VALUES('ravitamada', 'datetime()'");

Method 3 Using java Date functions

private String getDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);
}

ContentValues values = new ContentValues();
values.put('username', 'ravitamada');
values.put('created_at', getDateTime());
// insert the row
long id = db.insert('users', null, values);

Get the index of a certain value in an array in PHP

// or considering your array structure:

$array = array(
  'string1' => array('a' => '', 'b' => '', 'c' => ''),
  'string2' => array('a' => '', 'b' => '', 'c' => ''),
  'string3' => array('a' => '', 'b' => '', 'c' => ''),
);

// you could just

function findIndexOfKey($key_to_index,$array){
  return array_search($key_to_index,array_keys($array));
}

// executed

print "\r\n//-- Method 1 --//\r\n";
print '#index of: string1 = '.findIndexofKey('string1',$array)."\r\n";
print '#index of: string2 = '.findIndexofKey('string2',$array)."\r\n";
print '#index of: string3 = '.findIndexofKey('string3',$array)."\r\n";

// alternatively

print "\r\n//-- Method 2 --//\r\n";
print '#index of: string1 = '.array_search('string1',array_keys($array))."\r\n";
print '#index of: string2 = '.array_search('string2',array_keys($array))."\r\n";
print '#index of: string3 = '.array_search('string3',array_keys($array))."\r\n";

// recursersively

print "\r\n//-- Method 3 --//\r\n";
foreach(array_keys($array) as $key => $value){
  print '#index of: '.$value.' = '.$key."\r\n";
}

// outputs

//-- Method 1 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

//-- Method 2 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

//-- Method 3 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

Regex to match only uppercase "words" with some exceptions

For the first case you propose you can use: '[[:blank:]]+[A-Z0-9]+[[:blank:]]+', for example:

echo "The thing P1 must connect to the J236 thing in the Foo position" | grep -oE '[[:blank:]]+[A-Z0-9]+[[:blank:]]+'

In the second case maybe you need to use something else and not a regex, maybe a script with a dictionary of technical words...

Cheers, Fernando

Android: Force EditText to remove focus?

You can add this to onCreate and it will hide the keyboard every time the Activity starts.

You can also programmatically change the focus to another item.

 this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

How do I detect IE 8 with jQuery?

Note:

1) $.browser appears to be dropped in jQuery 1.9+ (as noted by Mandeep Jain). It is recommended to use .support instead.

2) $.browser.version can return "7" in IE >7 when the browser is in "compatibility" mode.

3) As of IE 10, conditional comments will no longer work.

4) jQuery 2.0+ will drop support for IE 6/7/8

5) document.documentMode appears to be defined only in Internet Explorer 8+ browsers. The value returned will tell you in what "compatibility" mode Internet Explorer is running. Still not a good solution though.

I tried numerous .support() options, but it appears that when an IE browser (9+) is in compatibility mode, it will simply behave like IE 7 ... :(

So far I only found this to work (kind-a):

(if documentMode is not defined and htmlSerialize and opacity are not supported, then you're very likely looking at IE <8 ...)

if(!document.documentMode && !$.support.htmlSerialize && !$.support.opacity) 
{
    // IE 6/7 code
}

How to compare timestamp dates with date-only parameter in MySQL?

When I read your question, I thought your were on Oracle DB until I saw the tag 'MySQL'. Anyway, for people working with Oracle here is the way:

SELECT *
FROM table
where timestamp = to_timestamp('21.08.2017 09:31:57', 'dd-mm-yyyy hh24:mi:ss');

Array initialization in Perl

If I understand you, perhaps you don't need an array of zeroes; rather, you need a hash. The hash keys will be the values in the other array and the hash values will be the number of times the value exists in the other array:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my %tallies;
$tallies{$_} ++ for @other_array;

print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;    

Output:

0 => 3
1 => 1
2 => 2
3 => 3
4 => 1

To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples:

my @zeroes = (0) x 5;            # (0,0,0,0,0)

my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
                                 # This works because in scalar context
                                 # an array evaluates to its size.

CSS - Syntax to select a class within an id

Here's two options. I prefer the navigationAlt option since it involves less work in the end:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <style type="text/css">_x000D_
    #navigation li {_x000D_
      color: green;_x000D_
    }_x000D_
    #navigation li .navigationLevel2 {_x000D_
      color: red;_x000D_
    }_x000D_
    #navigationAlt {_x000D_
      color: green;_x000D_
    }_x000D_
    #navigationAlt ul {_x000D_
      color: red;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <ul id="navigation">_x000D_
    <li>Level 1 item_x000D_
      <ul>_x000D_
        <li class="navigationLevel2">Level 2 item</li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
  <ul id="navigationAlt">_x000D_
    <li>Level 1 item_x000D_
      <ul>_x000D_
        <li>Level 2 item</li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What happens to a declared, uninitialized variable in C? Does it have a value?

The Value of num will be some garbage value from the main memory(RAM). its better if you initialize the variable just after creating.

How to set root password to null

If you know your Root Password and just wish to reset it then do as below:

  • Start MySQL Service from control panel > Administrative Tools > Services. (only if it was stopped by you earlier ! Otherwise, just skip this step)

  • Start MySQL Workbench

  • Type in this command/SQL line

    ALTER USER 'root'@'localhost' PASSWORD EXPIRE;

To reset any other user password... just type other user name instead of root.

How can I use a search engine to search for special characters?

A great search engine for special characters that I recenetly found: amp-what?

You can even search by object name, like "arrow", "chess", etc...

Best way to detect when a user leaves a web page?

I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:

window.onbeforeunload = function (e) {
        if ((window.event.clientY < 0)) {
            //window.localStorage.clear();
            //alert("Y coords: " + window.event.clientY)
        }
};

In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.

How do I concatenate two arrays in C#?

What you need to remember is that when using LINQ you are utilizing delayed execution. The other methods described here all work perfectly, but they are executed immediately. Furthermore the Concat() function is probably optimized in ways you can't do yourself (calls to internal API's, OS calls etc.). Anyway, unless you really need to try and optimize, you're currently on your path to "the root of all evil" ;)

Remove non-ascii character in string

To use ASCII with accents:

var str = str.replace(/[^\x00-\xFF]/g, "");

Running MSBuild fails to read SDKToolsPath

I fixed it by passing this as command-line parameter to msbuild.exe:

Your mileage will vary depending on the SDK version you have on your system

/p:TargetFrameworkSDKToolsDirectory="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools

Can you hide the controls of a YouTube embed without enabling autoplay?

You can hide the "Watch Later" Button by using "Youtube-nocookie" (this will not hide the share Button)

Adding controls=0 will also remove the video control bar at the bottom of the screen and using modestbranding=1 will remove the youtube logo at bottom right of the screen

However using them both doesn't works as expected (it only hides the video control bar)

<iframe width="100%" height="100%" src="https://www.youtube-nocookie.com/embed/fNb-DTEb43M?controls=0" frameborder="0" allowfullscreen></iframe>

Referencing a string in a string array resource with xml

Unfortunately:

  • It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.

  • It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.

What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.

Here's the code I was hoping would complete this task:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());  
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(),   android.R.layout.simple_list_item_1);  
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);  


for (int i = 0; i < 16; i++) {  
    if (prefs.getBoolean("itemKey[i]", true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
} 

What I did:

  • I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.

  • To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.

Here's the new code:

for (int i = 0; i < 16; i++) {  
        if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
}

Detecting Browser Autofill

For anyone looking for a 2020 pure JS solution to detect autofill, here ya go.

Please forgive tab errors, can't get this to sit nicely on SO

    //Chose the element you want to select - in this case input
    var autofill = document.getElementsByTagName('input');
    for (var i = 0; i < autofill.length; i++) {
      //Wrap this in a try/catch because non webkit browsers will log errors on this pseudo element
      try{
        if (autofill[i].matches(':-webkit-autofill')) {
            //Do whatever you like with each autofilled element
        }
      }
      catch(error){
        return(false);
      }
     }

Can't connect to MySQL server on 'localhost' (10061)

I got this error when I ran out of space on my drive.

Split string with delimiters in C

I think strsep is still the best tool for this:

while ((token = strsep(&str, ","))) my_fn(token);

That is literally one line that splits a string.

The extra parentheses are a stylistic element to indicate that we're intentionally testing the result of an assignment, not an equality operator ==.

For that pattern to work, token and str both have type char *. If you started with a string literal, then you'd want to make a copy of it first:

// More general pattern:
const char *my_str_literal = "JAN,FEB,MAR";
char *token, *str, *tofree;

tofree = str = strdup(my_str_literal);  // We own str's memory now.
while ((token = strsep(&str, ","))) my_fn(token);
free(tofree);

If two delimiters appear together in str, you'll get a token value that's the empty string. The value of str is modified in that each delimiter encountered is overwritten with a zero byte - another good reason to copy the string being parsed first.

In a comment, someone suggested that strtok is better than strsep because strtok is more portable. Ubuntu and Mac OS X have strsep; it's safe to guess that other unixy systems do as well. Windows lacks strsep, but it has strbrk which enables this short and sweet strsep replacement:

char *strsep(char **stringp, const char *delim) {
  if (*stringp == NULL) { return NULL; }
  char *token_start = *stringp;
  *stringp = strpbrk(token_start, delim);
  if (*stringp) {
    **stringp = '\0';
    (*stringp)++;
  }
  return token_start;
}

Here is a good explanation of strsep vs strtok. The pros and cons may be judged subjectively; however, I think it's a telling sign that strsep was designed as a replacement for strtok.

How to change Android version and code version number?

The easiest way to set the version in Android Studio:

1. Press SHIFT+CTRL+ALT+S (or File -> Project Structure -> app)

Android Studio < 3.4:

  1. Choose tab 'Flavors'
  2. The last two fields are 'Version Code' and 'Version Name'

Android Studio >= 3.4:

  1. Choose 'Modules' in the left panel.
  2. Choose 'app' in middle panel.
  3. Choose 'Default Config' tab in the right panel.
  4. Scroll down to see and edit 'Version Code' and 'Version Name' fields.

Spring 3 MVC resources and tag <mvc:resources />

<mvc:resources mapping="/resources/**"
               location="/, classpath:/WEB-INF/public-resources/"
               cache-period="10000" />

Put the resources under: src/main/webapp/images/logo.png and then access them via /resources/images/logo.png.

In the war they will be then located at images/logo.png. So the first location (/) form mvc:resources will pick them up.

The second location (classpath:/WEB-INF/public-resources/) in mvc:resources (looks like you used some roo based template) can be to expose resources (for example js-files) form jars, if they are located in the directory WEB-INF/public-resources in the jar.

SVN Repository Search

  1. Create git-svn mirror of that repository.
  2. Search for added or removed strings inside git: git log -S'my line of code' or the same in gitk

The advantage is that you can do many searches locally, without loading the server and network connection.

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

Calculating Distance between two Latitude and Longitude GeoCoordinates

Here is the JavaScript version guys and gals

function distanceTo(lat1, lon1, lat2, lon2, unit) {
      var rlat1 = Math.PI * lat1/180
      var rlat2 = Math.PI * lat2/180
      var rlon1 = Math.PI * lon1/180
      var rlon2 = Math.PI * lon2/180
      var theta = lon1-lon2
      var rtheta = Math.PI * theta/180
      var dist = Math.sin(rlat1) * Math.sin(rlat2) + Math.cos(rlat1) * Math.cos(rlat2) * Math.cos(rtheta);
      dist = Math.acos(dist)
      dist = dist * 180/Math.PI
      dist = dist * 60 * 1.1515
      if (unit=="K") { dist = dist * 1.609344 }
      if (unit=="N") { dist = dist * 0.8684 }
      return dist
}

R object identification

attributes(someObject) 

Can also be useful

How to stop mongo DB in one command

My special case is:

previously start mongod by:

sudo -u mongod mongod -f /etc/mongod.conf

now, want to stop mongod.

and refer official doc Stop mongod Processes, has tried:

(1) shutdownServer but failed:

> use admin
switched to db admin
> db.shutdownServer()
2019-03-06T14:13:15.334+0800 E QUERY    [thread1] Error: shutdownServer failed: {
        "ok" : 0,
        "errmsg" : "shutdown must run from localhost when running db without auth",
        "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.shutdownServer@src/mongo/shell/db.js:302:1
@(shell):1:1

(2) --shutdown still failed:

# mongod --shutdown
There doesn't seem to be a server running with dbpath: /data/db

(3) previous start command adding --shutdown:

sudo -u mongod mongod -f /etc/mongod.conf --shutdown
killing process with pid: 30213
failed to kill process: errno:1 Operation not permitted

(4) use service to stop:

service mongod stop

and

service mongod status

show expected Active: inactive (dead) but mongod actually still running, for can see process from ps:

# ps -edaf | grep mongo | grep -v grep
root     30213     1  0 Feb04 ?        03:33:22 mongod --port PORT --dbpath=/var/lib/mongo

and finally, really stop mongod by:

# sudo mongod -f /etc/mongod.conf --shutdown
killing process with pid: 30213

until now, root cause: still unknown ...

hope above solution is useful for your.

"unrecognized selector sent to instance" error in Objective-C

I had the same error and I discovered the following:

When you use the code

[self.refreshControl addTarget:self action:@selector(yourRefreshMethod:) forControlEvents:UIControlEventValueChanged];

You may think it's looking for the selector:

- (void)yourRefreshMethod{
    (your code here)
}

But it's actually looking for the selector:

- (void)yourRefreshMethod:(id)sender{
    (your code here)
}

That selector doesn't exist, so you get the crash.

You can change the selector to receive (id)sender in order to solve the error.

But what if you have other functions that call the refresh function without providing a sender? You need one function that works for both. Easy solution is to add another function:

- (void)yourRefreshMethodWithSender:(id)sender{
    [self yourRefreshMethod];
}

And then modify the refresh pulldown code to call that selector instead:

[self.refreshControl addTarget:self action:@selector(yourRefreshMethodWithSender:) forControlEvents:UIControlEventValueChanged];

I'm also doing the Stanford iOS course on an older Mac that can't be upgraded to the newest version of Mac OSX. So I'm still building for iOS 6.1, and this solved the problem for me.

Automatically size JPanel inside JFrame

You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);

This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.

Why is document.body null in my javascript?

document.body is not yet available when your code runs.

What you can do instead:

var docBody=document.getElementsByTagName("body")[0];
docBody.appendChild(mySpan);

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Run a string as a command within a Bash script

To see all commands that are being executed by the script, add the -x flag to your shabang line, and execute the command normally:

#! /bin/bash -x

matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"

teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'

cd $matchdir
$serverbin include="$include" server::team_l_start="${teamAComm}" server::team_r_start="${teamBComm}" CSVSaver::save='true' CSVSaver::filename='out.csv'

Then if you sometimes want to ignore the debug output, redirect stderr somewhere.

In SQL Server, what does "SET ANSI_NULLS ON" mean?

It means that no rows will be returned if @region is NULL, when used in your first example, even if there are rows in the table where Region is NULL.

When ANSI_NULLS is on (which you should always set on anyway, since the option to not have it on is going to be removed in the future), any comparison operation where (at least) one of the operands is NULL produces the third logic value - UNKNOWN (as opposed to TRUE and FALSE).

UNKNOWN values propagate through any combining boolean operators if they're not already decided (e.g. AND with a FALSE operand or OR with a TRUE operand) or negations (NOT).

The WHERE clause is used to filter the result set produced by the FROM clause, such that the overall value of the WHERE clause must be TRUE for the row to not be filtered out. So, if an UNKNOWN is produced by any comparison, it will cause the row to be filtered out.


@user1227804's answer includes this quote:

If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.

from SET ANSI_NULLS*

However, I'm not sure what point it's trying to make, since if two NULL columns are compared (e.g. in a JOIN), the comparison still fails:

create table #T1 (
    ID int not null,
    Val1 varchar(10) null
)
insert into #T1(ID,Val1) select 1,null

create table #T2 (
    ID int not null,
    Val1 varchar(10) null
)
insert into #T2(ID,Val1) select 1,null

select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and t1.Val1 = t2.Val1

The above query returns 0 rows, whereas:

select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and (t1.Val1 = t2.Val1 or t1.Val1 is null and t2.Val1 is null)

Returns one row. So even when both operands are columns, NULL does not equal NULL. And the documentation for = doesn't have anything to say about the operands:

When you compare two NULL expressions, the result depends on the ANSI_NULLS setting:

If ANSI_NULLS is set to ON, the result is NULL1, following the ANSI convention that a NULL (or unknown) value is not equal to another NULL or unknown value.

If ANSI_NULLS is set to OFF, the result of NULL compared to NULL is TRUE.

Comparing NULL to a non-NULL value always results in FALSE2.

However, both 1 and 2 are incorrect - the result of both comparisons is UNKNOWN.


*The cryptic meaning of this text was finally discovered years later. What it actually means is that, for those comparisons, the setting has no effect and it always acts as if the setting were ON. Would have been clearer if it had stated that SET ANSI_NULLS OFF was the setting that had no affect.

Update TensorFlow

Tensorflow upgrade -Python3

>> pip3 install --upgrade tensorflow --user

if you got this

"ERROR: tensorboard 2.0.2 has requirement grpcio>=1.24.3, but you'll have grpcio 1.22.0 which is incompatible."

Upgrade grpcio

>> pip3 install --upgrade grpcio --user

How to resolve "local edit, incoming delete upon update" message

So you can just revert the file that you deleted but remember, If you are working on any type of project with a set project file (like iOS), reverting the file will add it to your system folder structure but not your project file structure. additional steps may be required if you are in this case

iOS / Android cross platform development

Disclaimer: I work for a company, Particle Code, that makes a cross-platform framework. There are a ton of companies in this space. New ones seem to spring up every week. Good news for you: you have a lot of choices.

These frameworks take different approaches, and many of them are fundamentally designed to solve different problems. Some are focused on games, some are focused on apps. I would ask the following questions:

What do you want to write? Enterprise application, personal productivity application, puzzle game, first-person shooter?

What kind of development environment do you prefer? IDE or plain ol' text editor?

Do you have strong feelings about programming languages? Of the frameworks I'm familiar with, you can choose from ActionScript, C++, C#, Java, Lua, and Ruby.

My company is more in the game space, so I haven't played as much with the JavaScript+CSS frameworks like Titanium, PhoneGap, and Sencha. But I can tell you a bit about some of the games-oriented frameworks. Games and rich internet applications are an area where cross-platform frameworks can shine, because these applications tend to place more importance of being visually unique and less on blending in with native UIs. Here are a few frameworks to look for:

  • Unity www.unity3d.com is a 3D games engine. It's really unlike any other development environment I've worked in. You build scenes with 3D models, and define behavior by attaching scripts to objects. You can script in JavaScript, C#, or Boo. If you want to write a 3D physics-based game that will run on iOS, Android, Windows, OS X, or consoles, this is probably the tool for you. You can also write 2D games using 3D assets--a fine example of this is indie game Max and the Magic Marker, a 2D physics-based side-scroller written in Unity. If you don't know it, I recommend checking it out (especially if there are any kids in your household). Max is available for PC, Wii, iOS and Windows Phone 7 (although the latter version is a port, since Unity doesn't support WinPhone). Unity comes with some sample games complete with 3D assets and textures, which really helps getting up to speed with what can be a pretty complicated environment.

  • Corona www.anscamobile.com/corona is a 2D games engine that uses the Lua scripting language and supports iOS and Android. The selling point of Corona is the ability to write physics-based games very quickly in few lines of code, and the large number of Corona-based games in the iOS app store is a testament to its success. The environment is very lean, which will appeal to some people. It comes with a simulator and debugger. You add your text editor of choice, and you have a development environment. The base SDK doesn't include any UI components, like buttons or list boxes, but a CoronaUI add-on is available to subscribers.

  • The Particle SDK www.particlecode.com is a slightly more general cross-platform solution with a background in games. You can write in either Java or ActionScript, using a MVC application model. It includes an Eclipse-based IDE with a WYSIWYG UI editor. We currently support building for Android, iOS, webOS, and Windows Phone 7 devices. You can also output Flash or HTML5 for the web. The framework was originally developed for online multiplayer social games, such as poker and backgammon, and it suits 2D games and apps with complex logic. The framework supports 2D graphics and includes a 2D physics engine.

NB:

Today we announced that Particle Code has been acquired by Appcelerator, makers of the Titanium cross-platform framework.

...

As of January 1, 2012, [Particle Code] will no longer officially support the [Particle SDK] platform.

Source

  • The Airplay SDK www.madewithmarmalade.com is a C++ framework that lets you develop in either Visual Studio or Xcode. It supports both 2D and 3D graphics. Airplay targets iOS, Android, Bada, Symbian, webOS, and Windows Mobile 6. They also have an add-on to build AirPlay apps for PSP. My C++ being very rusty, I haven't played with it much, but it looks cool.

In terms of learning curve, I'd say that Unity had the steepest learning curve (for me), Corona was the simplest, and Particle and Airplay are somewhere in between.

Another interesting point is how the frameworks handle different form factors. Corona supports dynamic scaling, which will be familiar to Flash developers. This is very easy to use but means that you end up wasting screen space when going from a 4:3 screen like the iPhone to a 16:9 like the new qHD Android devices. The Particle SDK's UI editor lets you design flexible layouts that scale, but also lets you adjust the layouts for individual screen sizes. This takes a little more time but lets you make the app look custom made for each screen.

Of course, what works for you depends on your individual taste and work style as well as your goals -- so I recommend downloading a couple of these tools and giving them a shot. All of these tools are free to try.

Also, if I could just put in a public service announcement -- most of these tools are in really active development. If you find a framework you like, by all means send feedback and let them know what you like, what you don't like, and features you'd like to see. You have a real opportunity to influence what goes into the next versions of these tools.

Hope this helps.

How to hide collapsible Bootstrap 4 navbar on click

This code simulates a click on the burguer button to close the navbar by clicking on a link in the menu, keeping the fade out effect. Solution with typescript for angular 7. Avoid routerLink problems.

ToggleNavBar () {
    let element: HTMLElement = document.getElementsByClassName( 'navbar-toggler' )[ 0 ] as HTMLElement;
    if ( element.getAttribute( 'aria-expanded' ) == 'true' ) {
        element.click();
    }
}

<li class="nav-item" [routerLinkActive]="['active']">
    <a class="nav-link" [routerLink]="['link1']" title="link1" (click)="ToggleNavBar()">link1</a>
</li>

Filter array to have unique values

_x000D_
_x000D_
arr = ["I", "do", "love", "JavaScript", "and", "I", "also", "do", "love", "Java"];_x000D_
_x000D_
uniqueArr = [... new Set(arr)];_x000D_
_x000D_
// or_x000D_
_x000D_
reallyUniqueArr = arr.filter((item, pos, ar) => ar.indexOf(item) === pos)_x000D_
_x000D_
console.log(`${uniqueArr}\n${reallyUniqueArr}`)
_x000D_
_x000D_
_x000D_

Removing object properties with Lodash

Lodash unset is suitable for removing a few unwanted keys.

_x000D_
_x000D_
const myObj = {
    keyOne: "hello",
    keyTwo: "world"
}

unset(myObj, "keyTwo");

console.log(myObj); /// myObj = { keyOne: "hello" }
_x000D_
_x000D_
_x000D_

MessageBodyWriter not found for media type=application/json

Uncommenting the below code helped

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
</dependency>

which was present in pom.xml in my maven based project resolved this error for me.

How to do jquery code AFTER page loading?

write the code that you want to be executed inside this. When your document is ready, this will be executed.

$(document).ready(function() { 

});

How to set a CheckBox by default Checked in ASP.Net MVC

Old question, but another "pure razor" answer would be:

@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )

rails bundle clean

When searching for an answer to the very same question I came across gem_unused.
You also might wanna read this article: http://chill.manilla.com/2012/12/31/clean-up-your-dirty-gemsets/
The source code is available on GitHub: https://github.com/apolzon/gem_unused

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

It sounds like a classpath issue, so there are a few different ways to go about it. Where does org/hamcret/SelfDescribing come from? Is that your class or in a different jar?

Try going to your project Build Path and on the Libraries tab, add a Library. You should be able to choose JUnit to your project. This is a little bit different than just having the JUnit jar file In your project.

In your Run Configuration for the JUnit test, check the Classpath. You could probably fix this by adding making sure your Classpath can see that SelfDescribing class there. The Run option in Eclipse has a different set of options for the JUnit options.

How to disable all <input > inside a form with jQuery?

In older versions you could use attr. As of jQuery 1.6 you should use prop instead:

$("#target :input").prop("disabled", true);

To disable all form elements inside 'target'. See :input:

Matches all input, textarea, select and button elements.

If you only want the <input> elements:

$("#target input").prop("disabled", true);

Import and Export Excel - What is the best library?

We have just identified a similar need. And I think it's important to consider the user experience.

We nearly got sidetracked along the same:

  1. Prepare/work in spreadsheet file
  2. Save file
  3. Import file
  4. Work with data in system

... workflow

Add-in Express allows you to create a button within Excel without all that tedious mucking about with VSTO. Then the workflow becomes:

  1. Prepare/work in spreadsheet file
  2. Import file (using button inside Excel)
  3. Work with data in system

Have the code behind the button use the "native" Excel API (via Add-in Express) and push direct into the recipient system. You can't get much more transparent for the developer or the user. Worth considering.

iOS - Ensure execution on main thread

i think this is cool, even tho in general its good form to leave the caller of a method responsible for ensuring its called on the right thread.

if (![[NSThread currentThread] isMainThread]) {
    [self performSelector:_cmd onThread:[NSThread mainThread] withObject:someObject waitUntilDone:NO];
    return;
}

Plot multiple lines in one graph

The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.

plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) )  )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
  } 
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

jackson deserialization json to java-objects

It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {} but your JSON actually starts with square brackets [] designating an array.

What you actually have is a List<product> To describe generic types, due to Java's type erasure, you must use a TypeReference. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});

A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception which saves you all the useless catch blocks.

How to zip a file using cmd line?

If you want a simple program that will run with .net 4.6.1 or above on Windows, I wrote this for my own purposes after finding this question.

You simply cd to the directory above the folder you want to zip, then pass in the directory name and it will output mydir.zip. Add zipper to your path, I personally have a utils folder on C:\utils that have things like this in it.

cd C:\Users\SomeUser\Desktop\
zipper myfolder

Below is the source code and copy of the exe:

https://github.com/tryonlinux/commandLineZipper

File path issues in R using Windows ("Hex digits in character string" error)

A simple way is to use python. in python terminal type

r"C:\Users\surfcat\Desktop\2006_dissimilarity.csv" and you'll get back 'C:\Users\surfcat\Desktop\2006_dissimilarity.csv'

Automatic vertical scroll bar in WPF TextBlock?

Wrap it in a scroll viewer:

<ScrollViewer>
    <TextBlock />
</ScrollViewer>

NOTE this answer applies to a TextBlock (a read-only text element) as asked for in the original question.

If you want to show scroll bars in a TextBox (an editable text element) then use the ScrollViewer attached properties:

<TextBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         ScrollViewer.VerticalScrollBarVisibility="Auto" />

Valid values for these two properties are Disabled, Auto, Hidden and Visible.

Is there a way to 'pretty' print MongoDB shell output to a file?

Since you are doing this on a terminal and just want to inspect a record in a sane way, you can use a trick like this:

mongo | tee somefile

Use the session as normal - db.collection.find().pretty() or whatever you need to do, ignore the long output, and exit. A transcript of your session will be in the file tee wrote to.

Be mindful that the output might contain escape sequences and other garbage due to the mongo shell expecting an interactive session. less handles these gracefully.

Algorithm to find Largest prime factor of a number

It seems to me that step #2 of the algorithm given isn't going to be all that efficient an approach. You have no reasonable expectation that it is prime.

Also, the previous answer suggesting the Sieve of Eratosthenes is utterly wrong. I just wrote two programs to factor 123456789. One was based on the Sieve, one was based on the following:

1)  Test = 2 
2)  Current = Number to test 
3)  If Current Mod Test = 0 then  
3a)     Current = Current Div Test 
3b)     Largest = Test
3c)     Goto 3. 
4)  Inc(Test) 
5)  If Current < Test goto 4
6)  Return Largest

This version was 90x faster than the Sieve.

The thing is, on modern processors the type of operation matters far less than the number of operations, not to mention that the algorithm above can run in cache, the Sieve can't. The Sieve uses a lot of operations striking out all the composite numbers.

Note, also, that my dividing out factors as they are identified reduces the space that must be tested.

How to add a "sleep" or "wait" to my Lua Script?

function wait(time)
    local duration = os.time() + time
    while os.time() < duration do end
end

This is probably one of the easiest ways to add a wait/sleep function to your script

A JOIN With Additional Conditions Using Query Builder or Eloquent

I am using laravel5.2 and we can add joins with different options, you can modify as per your requirement.

Option 1:    
    DB::table('users')
            ->join('contacts', function ($join) {
                $join->on('users.id', '=', 'contacts.user_id')->orOn(...);//you add more joins here
            })// and you add more joins here
        ->get();

Option 2:
    $users = DB::table('users')
        ->join('contacts', 'users.id', '=', 'contacts.user_id')
        ->join('orders', 'users.id', '=', 'orders.user_id')// you may add more joins
        ->select('users.*', 'contacts.phone', 'orders.price')
        ->get();

option 3:
    $users = DB::table('users')
        ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
        ->leftJoin('...', '...', '...', '...')// you may add more joins
        ->get();

How to loop through files matching wildcard in batch file

You can use this line to print the contents of your desktop:

FOR %%I in (C:\windows\desktop\*.*) DO echo %%I 

Once you have the %%I variable it's easy to perform a command on it (just replace the word echo with your program)

In addition, substitution of FOR variable references has been enhanced You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only (directory with \)
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

https://ss64.com/nt/syntax-args.html

In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.

You can get the full documentation by typing FOR /?

Using git to get just the latest revision

Alternate solution to doing shallow clone (git clone --depth=1 <URL>) would be, if remote side supports it, to use --remote option of git archive:

$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.

java.net.URL read stream to byte[]

It's important to specify timeouts, especially when the server takes to respond. With pure Java, without using any dependency:

public static byte[] copyURLToByteArray(final String urlStr,
        final int connectionTimeout, final int readTimeout) 
                throws IOException {
    final URL url = new URL(urlStr);
    final URLConnection connection = url.openConnection();
    connection.setConnectTimeout(connectionTimeout);
    connection.setReadTimeout(readTimeout);
    try (InputStream input = connection.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        final byte[] buffer = new byte[8192];
        for (int count; (count = input.read(buffer)) > 0;) {
            output.write(buffer, 0, count);
        }
        return output.toByteArray();
    }
}

Using dependencies, e.g., HC Fluent:

public byte[] copyURLToByteArray(final String urlStr,
        final int connectionTimeout, final int readTimeout)
                throws IOException {
    return Request.Get(urlStr)
            .connectTimeout(connectionTimeout)
            .socketTimeout(readTimeout)
            .execute()
            .returnContent()
            .asBytes();
}

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

Parsing a CSV file using NodeJS

Seems like you need to use a stream-based library such as fast-csv, which also includes validation support.

Parse DateTime string in JavaScript

This function handles also the invalid 29.2.2001 date.

function parseDate(str) {
    var dateParts = str.split(".");
    if (dateParts.length != 3)
        return null;
    var year = dateParts[2];
    var month = dateParts[1];
    var day = dateParts[0];

    if (isNaN(day) || isNaN(month) || isNaN(year))
        return null;

    var result = new Date(year, (month - 1), day);
    if (result == null)
        return null;
    if (result.getDate() != day)
        return null;
    if (result.getMonth() != (month - 1))
        return null;
    if (result.getFullYear() != year)
        return null;

    return result;
}

JavaScript closures vs. anonymous functions

I wrote this a while ago to remind myself of what a closure is and how it works in JS.

A closure is a function that, when called, uses the scope in which it was declared, not the scope in which it was called. In javaScript, all functions behave like this. Variable values in a scope persist as long as there is a function that still points to them. The exception to the rule is 'this', which refers to the object that the function is inside when it is called.

var z = 1;
function x(){
    var z = 2; 
    y(function(){
      alert(z);
    });
}
function y(f){
    var z = 3;
    f();
}
x(); //alerts '2' 

Switch to selected tab by name in Jquery-UI Tabs

$('#tabs').tabs('select', index); 

Methods `'select' isn't support in jquery ui 1.10.0.http://api.jqueryui.com/tabs/

I use this code , and work correctly:

  $('#tabs').tabs({ active: index });

C# Sort and OrderBy comparison

Why not measure it:

class Program
{
    class NameComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return string.Compare(x, y, true);
        }
    }

    class Person
    {
        public Person(string id, string name)
        {
            Id = id;
            Name = name;
        }
        public string Id { get; set; }
        public string Name { get; set; }
    }

    static void Main()
    {
        List<Person> persons = new List<Person>();
        persons.Add(new Person("P005", "Janson"));
        persons.Add(new Person("P002", "Aravind"));
        persons.Add(new Person("P007", "Kazhal"));

        Sort(persons);
        OrderBy(persons);

        const int COUNT = 1000000;
        Stopwatch watch = Stopwatch.StartNew();
        for (int i = 0; i < COUNT; i++)
        {
            Sort(persons);
        }
        watch.Stop();
        Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int i = 0; i < COUNT; i++)
        {
            OrderBy(persons);
        }
        watch.Stop();
        Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
    }

    static void Sort(List<Person> list)
    {
        list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
    }

    static void OrderBy(List<Person> list)
    {
        var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
    }
}

On my computer when compiled in Release mode this program prints:

Sort: 1162ms
OrderBy: 1269ms

UPDATE:

As suggested by @Stefan here are the results of sorting a big list fewer times:

List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
    persons.Add(new Person("P" + i.ToString(), "Janson" + i.ToString()));
}

Sort(persons);
OrderBy(persons);

const int COUNT = 30;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
    Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
    OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);

Prints:

Sort: 8965ms
OrderBy: 8460ms

In this scenario it looks like OrderBy performs better.


UPDATE2:

And using random names:

List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
    persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
}

Where:

private static Random randomSeed = new Random();
public static string RandomString(int size, bool lowerCase)
{
    var sb = new StringBuilder(size);
    int start = (lowerCase) ? 97 : 65;
    for (int i = 0; i < size; i++)
    {
        sb.Append((char)(26 * randomSeed.NextDouble() + start));
    }
    return sb.ToString();
}

Yields:

Sort: 8968ms
OrderBy: 8728ms

Still OrderBy is faster

How I can filter a Datatable?

You can use DataView.

DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"


http://www.csharp-examples.net/dataview-rowfilter/

Split string into individual words Java

String[] str = s.split("[^a-zA-Z]+");

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Desktop: first-class support

Oracle JavaFX from Java SE supports only OS X (macOS), GNU/Linux and Microsoft Windows. On these platforms, JavaFX applications are typically run on JVM from Java SE or OpenJDK.

Android: should work

There is also a JavaFXPorts project, which is an open-source project sponsored by a third-party. It aims to port JavaFX library to Android and iOS.

On Android, this library can be used like any other Java library; the JVM bytecode is compiled to Dalvik bytecode. It's what people mean by saying that "Android runs Java".

iOS: status not clear

On iOS, situation is a bit more complex, as neither Java SE nor OpenJDK supports Apple mobile devices. Till recently, the only sensible option was to use RoboVM ahead-of-time Java compiler for iOS. Unfortunately, on 15 April 2015, RoboVM project was shut down.

One possible alternative is Intel's Multi-OS Engine. Till recently, it was a proprietary technology, but on 11 August 2016 it was open-sourced. Although it can be possible to compile an iOS JavaFX app using JavaFXPorts' JavaFX implementation, there is no evidence for that so far. As you can see, the situation is dynamically changing, and this answer will be hopefully updated when new information is available.

Windows Phone: no support

With Windows Phone it's simple: there is no JavaFX support of any kind.

How can I match a string with a regex in Bash?

Since you are using bash, you don't need to create a child process for doing this. Here is one solution which performs it entirely within bash:

[[ $TEST =~ ^(.*):\ +(.*)$ ]] && TEST=${BASH_REMATCH[1]}:${BASH_REMATCH[2]}

Explanation: The groups before and after the sequence "colon and one or more spaces" are stored by the pattern match operator in the BASH_REMATCH array.

APR based Apache Tomcat Native library was not found on the java.library.path?

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

NoClassDefFoundError on Maven dependency

I was able to work around it by running mvn install:install-file with -Dpackaging=class. Then adding entry to POM as described here:

Django. Override save for model

Query the database for an existing record with the same PK. Compare the file sizes and checksums of the new and existing images to see if they're the same.

How to select the last column of dataframe

These are few things which will help you in understanding everything... using iloc

In iloc, [initial row:ending row, initial column:ending column]

case 1: if you want only last column --- df.iloc[:,-1] & df.iloc[:,-1:] this means that you want only the last column...

case 2: if you want all columns and all rows except the last column --- df.iloc[:,:-1] this means that you want all columns and all rows except the last column...

case 3: if you want only last row --- df.iloc[-1:,:] & df.iloc[-1,:] this means that you want only the last row...

case 4: if you want all columns and all rows except the last row --- df.iloc[:-1,:] this means that you want all columns and all rows except the last column...

case 5: if you want all columns and all rows except the last row and last column --- df.iloc[:-1,:-1] this means that you want all columns and all rows except the last column and last row...

ASP.NET MVC DropDownListFor with model of type List<string>

I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:

https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor

To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:

yourRecord.FieldName = Request.Form["FieldNameInModel"];

As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.

No, I did not dig down to see how th4e magic works under the covers. I just know it works...

I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.

What is the standard way to add N seconds to datetime.time in Python?

Old question, but I figured I'd throw in a function that handles timezones. The key parts are passing the datetime.time object's tzinfo attribute into combine, and then using timetz() instead of time() on the resulting dummy datetime. This answer partly inspired by the other answers here.

def add_timedelta_to_time(t, td):
    """Add a timedelta object to a time object using a dummy datetime.

    :param t: datetime.time object.
    :param td: datetime.timedelta object.

    :returns: datetime.time object, representing the result of t + td.

    NOTE: Using a gigantic td may result in an overflow. You've been
    warned.
    """
    # Create a dummy date object.
    dummy_date = date(year=100, month=1, day=1)

    # Combine the dummy date with the given time.
    dummy_datetime = datetime.combine(date=dummy_date, time=t, tzinfo=t.tzinfo)

    # Add the timedelta to the dummy datetime.
    new_datetime = dummy_datetime + td

    # Return the resulting time, including timezone information.
    return new_datetime.timetz()

And here's a really simple test case class (using built-in unittest):

import unittest
from datetime import datetime, timezone, timedelta, time

class AddTimedeltaToTimeTestCase(unittest.TestCase):
    """Test add_timedelta_to_time."""

    def test_wraps(self):
        t = time(hour=23, minute=59)
        td = timedelta(minutes=2)
        t_expected = time(hour=0, minute=1)
        t_actual = add_timedelta_to_time(t=t, td=td)
        self.assertEqual(t_expected, t_actual)

    def test_tz(self):
        t = time(hour=4, minute=16, tzinfo=timezone.utc)
        td = timedelta(hours=10, minutes=4)
        t_expected = time(hour=14, minute=20, tzinfo=timezone.utc)
        t_actual = add_timedelta_to_time(t=t, td=td)
        self.assertEqual(t_expected, t_actual)


if __name__ == '__main__':
    unittest.main()

Fatal Error :1:1: Content is not allowed in prolog

The real solution that I found for this issue was by disabling any XML Format post processors. I have added a post processor called "jp@gc - XML Format Post Processor" and started noticing the error "Fatal Error :1:1: Content is not allowed in prolog"

By disabling the post processor had stopped throwing those errors.

python list in sql query as parameter

Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue.

Here's a variant using a parameterised query that would work for both:

placeholder= '?' # For SQLite. See DBAPI paramstyle.
placeholders= ', '.join(placeholder for unused in l)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
cursor.execute(query, l)

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

Convert PDF to PNG using ImageMagick

Reducing the image size before output results in something that looks sharper, in my case:

convert -density 300 a.pdf -resize 25% a.png

How to solve a pair of nonlinear equations using Python?

If you prefer sympy you can use nsolve.

>>> nsolve([x+y**2-4, exp(x)+x*y-3], [x, y], [1, 1])
[0.620344523485226]
[1.83838393066159]

The first argument is a list of equations, the second is list of variables and the third is an initial guess.

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

How do I add a foreign key to an existing SQLite table?

Create a foreign key to the existing SQLLite table:

There is no direct way to do that for SQL LITE. Run the below query to recreate STUDENTS table with foreign keys. Run the query after creating initial STUDENTS table and inserting data into the table.

CREATE TABLE    STUDENTS    (       
    STUDENT_ID  INT NOT NULL,   
    FIRST_NAME  VARCHAR(50) NOT NULL,   
    LAST_NAME   VARCHAR(50) NOT NULL,   
    CITY    VARCHAR(50) DEFAULT NULL,   
    BADGE_NO    INT DEFAULT NULL
    PRIMARY KEY(STUDENT_ID) 
);

Insert data into STUDENTS table.

Then Add FOREIGN KEY : making BADGE_NO as the foreign key of same STUDENTS table

BEGIN;
CREATE TABLE STUDENTS_new (
    STUDENT_ID  INT NOT NULL,   
    FIRST_NAME  VARCHAR(50) NOT NULL,   
    LAST_NAME   VARCHAR(50) NOT NULL,   
    CITY    VARCHAR(50) DEFAULT NULL,   
    BADGE_NO    INT DEFAULT NULL,
    PRIMARY KEY(STUDENT_ID) ,
    FOREIGN KEY(BADGE_NO) REFERENCES STUDENTS(STUDENT_ID)   
);
INSERT INTO STUDENTS_new SELECT * FROM STUDENTS;
DROP TABLE STUDENTS;
ALTER TABLE STUDENTS_new RENAME TO STUDENTS;
COMMIT;

we can add the foreign key from any other table as well.

How to convert jsonString to JSONObject in Java

Converting String to Json Object by using org.json.simple.JSONObject

private static JSONObject createJSONObject(String jsonString){
    JSONObject  jsonObject=new JSONObject();
    JSONParser jsonParser=new  JSONParser();
    if ((jsonString != null) && !(jsonString.isEmpty())) {
        try {
            jsonObject=(JSONObject) jsonParser.parse(jsonString);
        } catch (org.json.simple.parser.ParseException e) {
            e.printStackTrace();
        }
    }
    return jsonObject;
}

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

Installing version 1.1.8 of enum34 worked for me.

I was able to fix this by adding enum34 = "==1.1.8" to pyproject.toml. Apparently enum34 had a feature in v1.1.8 that avoided this error, but this regressed in v1.1.9+. This is just a workaround though. The better solution would be for packages to use environment markers so you don't have to install enum34 at all unless needed.

Source: https://github.com/python-poetry/poetry/issues/1122

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402

How to convert a number to string and vice versa in C++

Update for C++11

As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).

string to numeric

float              stof(const string& str, size_t *idx = 0);
double             stod(const string& str, size_t *idx = 0);
long double        stold(const string& str, size_t *idx = 0);
int                stoi(const string& str, size_t *idx = 0, int base = 10);
long               stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long      stoul(const string& str, size_t *idx = 0, int base = 10);
long long          stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument or std::out_of_range).

If conversion succeeded and idx is not 0, idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.

Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10 until z=35). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.

Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.

numeric to string

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.

As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.

There are also similar functions defined that are named to_wstring, these will return a std::wstring.

See line breaks and carriage returns in editor

VI shows newlines (LF character, code x0A) by showing the subsequent text on the next line.

Use the -b switch for binary mode. Eg vi -b filename or vim -b filename --.

It will then show CR characters (x0D), which are not normally used in Unix style files, as the characters ^M.

How to match letters only using java regex, matches method?

matches method performs matching of full line, i.e. it is equivalent to find() with '^abc$'. So, just use Pattern.compile("[a-zA-Z]").matcher(str).find() instead. Then fix your regex. As @user unknown mentioned your regex actually matches only one character. You probably should say [a-zA-Z]+

What is the difference between Builder Design pattern and Factory Design pattern?

A complex construction is when the object to be constructed is composed of different other objects which are represented by abstractions.

Consider a menu in McDonald's. A menu contains a drink, a main and a side. Depending on which descendants of the individual abstractions are composed together, the created menu has another representation.

  1. Example: Cola, Big Mac, French Fries
  2. Example: Sprite, Nuggets, Curly Fries

There, we got two instances of the menu with different representations. The process of construction in turn remains the same. You create a menu with a drink, a main and a side.

By using the builder pattern, you separate the algorithm of creating a complex object from the different components used to create it.

In terms of the builder pattern, the algorithm is encapsulated in the director whereas the builders are used to create the integral parts. Varying the used builder in the algorithm of the director results in a different representation because other parts are composed to a menu. The way a menu is created remains the same.

Android Image View Pinch Zooming

Add bellow line in build.gradle:

compile 'com.commit451:PhotoView:1.2.4'

or

compile 'com.github.chrisbanes:PhotoView:1.3.0'

In Java file:

PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(Your_Image_View);
photoAttacher.update();

How to change Hash values?

If you know that the values are strings, you can call the replace method on them while in the cycle: this way you will change the value.

Altohugh this is limited to the case in which the values are strings and hence doesn't answer the question fully, I thought it can be useful to someone.

How to remove blank lines from a Unix file

sed -i '/^$/d' foo

This tells sed to delete every line matching the regex ^$ i.e. every empty line. The -i flag edits the file in-place, if your sed doesn't support that you can write the output to a temporary file and replace the original:

sed '/^$/d' foo > foo.tmp
mv foo.tmp foo

If you also want to remove lines consisting only of whitespace (not just empty lines) then use:

sed -i '/^[[:space:]]*$/d' foo

Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:

sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo

Is null check needed before calling instanceof?

Just as a tidbit:

Even (((A)null)instanceof A) will return false.


(If typecasting null seems surprising, sometimes you have to do it, for example in situations like this:

public class Test
{
  public static void test(A a)
  {
    System.out.println("a instanceof A: " + (a instanceof A));
  }

  public static void test(B b) {
    // Overloaded version. Would cause reference ambiguity (compile error)
    // if Test.test(null) was called without casting.
    // So you need to call Test.test((A)null) or Test.test((B)null).
  }
}

So Test.test((A)null) will print a instanceof A: false.)


P.S.: If you are hiring, please don't use this as a job interview question. :D

PHP "php://input" vs $_POST

Simple example of how to use it

 <?php  
     if(!isset($_POST) || empty($_POST)) { 
     ?> 
        <form name="form1" method="post" action=""> 
          <input type="text" name="textfield"><br /> 
          <input type="submit" name="Submit" value="submit"> 
        </form> 
   <?php  
        } else { 
        $example = file_get_contents("php://input");
        echo $example;  }  
   ?>

Using StringWriter for XML Serialization

It may have been covered elsewhere but simply changing the encoding line of the XML source to 'utf-16' allows the XML to be inserted into a SQL Server 'xml'data type.

using (DataSetTableAdapters.SQSTableAdapter tbl_SQS = new DataSetTableAdapters.SQSTableAdapter())
{
    try
    {
        bodyXML = @"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><test></test>";
        bodyXMLutf16 = bodyXML.Replace("UTF-8", "UTF-16");
        tbl_SQS.Insert(messageID, receiptHandle, md5OfBody, bodyXMLutf16, sourceType);
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        Console.WriteLine(ex.Message);
        Console.ReadLine();
    }
}

The result is all of the XML text is inserted into the 'xml' data type field but the 'header' line is removed. What you see in the resulting record is just

<test></test>

Using the serialization method described in the "Answered" entry is a way of including the original header in the target field but the result is that the remaining XML text is enclosed in an XML <string></string> tag.

The table adapter in the code is a class automatically built using the Visual Studio 2013 "Add New Data Source: wizard. The five parameters to the Insert method map to fields in a SQL Server table.

C# code to validate email address

I use this one to validate emails often and it works like a charm. This validates that the email must have atleast one character before the @, and at least one character before the "."

public static bool ValidateEmail(string value, bool required, int minLength, int maxLength)
        {
           value = value.Trim();
           if (required == false && value == "") return true;
           if (required && value == "") return false;
           if (value.Length < minLength || value.Length > maxLength) return false;

           //Email must have at least one character before an @, and at least one character before the .
           int index = value.IndexOf('@');
           if (index < 1 || value.LastIndexOf('.') < index + 2) return false;
           return true;
        }

Creating PHP class instance with a string

have a look at example 3 from http://www.php.net/manual/en/language.oop5.basic.php

$className = 'Foo';
$instance = new $className(); // Foo()

did you specify the right host or port? error on Kubernetes

I had this problem using a local docker. The thing to do is check the logs of the containers its spins up to figure out what went wrong. For me it transpired that etcd had fallen over

   $ docker logs <etcdContainerId>
   <snip>
   2016-06-15 09:02:32.868569 C | etcdmain: listen tcp 127.0.0.1:7001: bind: address already in use

Aha! I'd been playing with Cassandra in a docker container and I'd forwarded all the ports since I wasn't sure which it needed exposed and 7001 is one of its ports. Stopping Cassandra, cleaning up the mess and restarting it fixed things.

Download JSON object as a file from browser

This would be a pure JS version (adapted from cowboy's):

var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

var a = document.createElement('a');
a.href = 'data:' + data;
a.download = 'data.json';
a.innerHTML = 'download JSON';

var container = document.getElementById('container');
container.appendChild(a);

http://jsfiddle.net/sz76c083/1

I want to exception handle 'list index out of range.'

You have two options; either handle the exception or test the length:

if len(dlist) > 1:
    newlist.append(dlist[1])
    continue

or

try:
    newlist.append(dlist[1])
except IndexError:
    pass
continue

Use the first if there often is no second item, the second if there sometimes is no second item.

Custom HTTP Authorization Header

Put it in a separate, custom header.

Overloading the standard HTTP headers is probably going to cause more confusion than it's worth, and will violate the principle of least surprise. It might also lead to interoperability problems for your API client programmers who want to use off-the-shelf tool kits that can only deal with the standard form of typical HTTP headers (such as Authorization).

SQL Server convert select a column and convert it to a string

Use simplest way of doing this-

SELECT GROUP_CONCAT(Column) from table

Checking if a collection is null or empty in Groovy

There is indeed a Groovier Way.

if(members){
    //Some work
}

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)

Question mark and colon in JavaScript

? : isn't this the ternary operator?

var x= expression ? true:false

How can I check if a string represents an int, without using try/except?

Uh.. Try this:

def int_check(a):
    if int(a) == a:
        return True
    else:
        return False

This works if you don't put a string that's not a number.

And also (I forgot to put the number check part. ), there is a function checking if the string is a number or not. It is str.isdigit(). Here's an example:

a = 2
a.isdigit()

If you call a.isdigit(), it will return True.

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

DataRow: Select cell value by a given column name

for (int i=0;i < Table.Rows.Count;i++)
{
      Var YourValue = Table.Rows[i]["ColumnName"];
}

Casting variables in Java

Casting a reference will only work if it's an instanceof that type. You can't cast random references. Also, you need to read more on Casting Objects.

e.g.

String string = "String";

Object object = string; // Perfectly fine since String is an Object

String newString = (String)object; // This only works because the `reference` object is pointing to a valid String object.

Explicitly calling return in a function or not

My question is: Why is not calling return faster

It’s faster because return is a (primitive) function in R, which means that using it in code incurs the cost of a function call. Compare this to most other programming languages, where return is a keyword, but not a function call: it doesn’t translate to any runtime code execution.

That said, calling a primitive function in this way is pretty fast in R, and calling return incurs a minuscule overhead. This isn’t the argument for omitting return.

or better, and thus preferable?

Because there’s no reason to use it.

Because it’s redundant, and it doesn’t add useful redundancy.

To be clear: redundancy can sometimes be useful. But most redundancy isn’t of this kind. Instead, it’s of the kind that adds visual clutter without adding information: it’s the programming equivalent of a filler word or chartjunk).

Consider the following example of an explanatory comment, which is universally recognised as bad redundancy because the comment merely paraphrases what the code already expresses:

# Add one to the result
result = x + 1

Using return in R falls in the same category, because R is a functional programming language, and in R every function call has a value. This is a fundamental property of R. And once you see R code from the perspective that every expression (including every function call) has a value, the question then becomes: “why should I use return?” There needs to be a positive reason, since the default is not to use it.

One such positive reason is to signal early exit from a function, say in a guard clause:

f = function (a, b) {
    if (! precondition(a)) return() # same as `return(NULL)`!
    calculation(b)
}

This is a valid, non-redundant use of return. However, such guard clauses are rare in R compared to other languages, and since every expression has a value, a regular if does not require return:

sign = function (num) {
    if (num > 0) {
        1
    } else if (num < 0) {
        -1
    } else {
        0
    }
}

We can even rewrite f like this:

f = function (a, b) {
    if (precondition(a)) calculation(b)
}

… where if (cond) expr is the same as if (cond) expr else NULL.

Finally, I’d like to forestall three common objections:

  1. Some people argue that using return adds clarity, because it signals “this function returns a value”. But as explained above, every function returns something in R. Thinking of return as a marker of returning a value isn’t just redundant, it’s actively misleading.

  2. Relatedly, the Zen of Python has a marvellous guideline that should always be followed:

    Explicit is better than implicit.

    How does dropping redundant return not violate this? Because the return value of a function in a functional language is always explicit: it’s its last expression. This is again the same argument about explicitness vs redundancy.

    In fact, if you want explicitness, use it to highlight the exception to the rule: mark functions that don’t return a meaningful value, which are only called for their side-effects (such as cat). Except R has a better marker than return for this case: invisible. For instance, I would write

    save_results = function (results, file) {
        # … code that writes the results to a file …
        invisible()
    }
    
  3. But what about long functions? Won’t it be easy to lose track of what is being returned?

    Two answers: first, not really. The rule is clear: the last expression of a function is its value. There’s nothing to keep track of.

    But more importantly, the problem in long functions isn’t the lack of explicit return markers. It’s the length of the function. Long functions almost (?) always violate the single responsibility principle and even when they don’t they will benefit from being broken apart for readability.

Force git stash to overwrite added files

To force git stash pop run this command

git stash show -p | git apply && git stash drop

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

Remove trailing comma from comma-separated string

    String str = "kushalhs , mayurvm , narendrabz ,";
    System.out.println(str.replaceAll(",([^,]*)$", "$1"));

Spring Data: "delete by" is supported?

@Query(value = "delete from addresses u where u.ADDRESS_ID LIKE %:addressId%", nativeQuery = true)
void deleteAddressByAddressId(@Param("addressId") String addressId);

"OverflowError: Python int too large to convert to C long" on windows but not mac

You'll get that error once your numbers are greater than sys.maxsize:

>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

You can confirm this by checking:

>>> import sys
>>> sys.maxsize
2147483647

To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:

>>> preds = np.zeros((1, 3))

How to update PATH variable permanently from Windows command line?

You can use:

setx PATH "%PATH%;C:\\Something\\bin"

However, setx will truncate the stored string to 1024 bytes, potentially corrupting the PATH.

/M will change the PATH in HKEY_LOCAL_MACHINE instead of HKEY_CURRENT_USER. In other words, a system variable, instead of the user's. For example:

SETX /M PATH "%PATH%;C:\your path with spaces"

You have to keep in mind, the new PATH is not visible in your current cmd.exe.

But if you look in the registry or on a new cmd.exe with "set p" you can see the new value.

How to update nested state properties in React

Here's a variation on the first answer given in this thread which doesn't require any extra packages, libraries or special functions.

state = {
  someProperty: {
    flag: 'string'
  }
}

handleChange = (value) => {
  const newState = {...this.state.someProperty, flag: value}
  this.setState({ someProperty: newState })
}

In order to set the state of a specific nested field, you have set the whole object. I did this by creating a variable, newState and spreading the contents of the current state into it first using the ES2015 spread operator. Then, I replaced the value of this.state.flag with the new value (since I set flag: value after I spread the current state into the object, the flag field in the current state is overridden). Then, I simply set the state of someProperty to my newState object.

How to use a App.config file in WPF applications?

You have to add the reference to System.configuration in your solution. Also, include using System.Configuration;. Once you do that, you'll have access to all the configuration settings.

Get all table names of a particular database by SQL query?

In order if someone would like to list all tables within specific database without using the "use" keyword:

SELECT TABLE_NAME FROM databasename.INFORMATION_SCHEMA.TABLES

How do I get the position selected in a RecyclerView?

To complement @tyczj answer:

Generic Adapter Pseido code:

public abstract class GenericRecycleAdapter<T, K extends RecyclerView.ViewHolder> extends RecyclerView.Adapter{ 

private List<T> mList;
//default implementation code 

public abstract int getLayout();

@Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(getLayout(), parent, false);
        return getCustomHolder(v);
    }

    public Holders.TextImageHolder getCustomHolder(View v) {
        return new Holders.TextImageHolder(v){
            @Override
            public void onClick(View v) {
                onItem(mList.get(this.getAdapterPosition()));
            }
        };
    }

abstract void onItem(T t);

 @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    onSet(mList.get(position), (K) holder);

}

public abstract void onSet(T item, K holder);

}

ViewHolder:

public class Holders  {

    public static class TextImageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        public TextView text;

        public TextImageHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.text);
            text.setOnClickListener(this);


        }

        @Override
        public void onClick(View v) {

        }
    }


}

Adapter usage:

public class CategoriesAdapter extends GenericRecycleAdapter<Category, Holders.TextImageHolder> {


    public CategoriesAdapter(List<Category> list, Context context) {
        super(list, context);
    }

    @Override
    void onItem(Category category) {

    }


    @Override
    public int getLayout() {
        return R.layout.categories_row;
    }

    @Override
    public void onSet(Category item, Holders.TextImageHolder holder) {

    }



}

How to execute a remote command over ssh with arguments?

Do it this way instead:

function mycommand {
    ssh [email protected] "cd testdir;./test.sh \"$1\""
}

You still have to pass the whole command as a single string, yet in that single string you need to have $1 expanded before it is sent to ssh so you need to use "" for it.

Update

Another proper way to do this actually is to use printf %q to properly quote the argument. This would make the argument safe to parse even if it has spaces, single quotes, double quotes, or any other character that may have a special meaning to the shell:

function mycommand {
    printf -v __ %q "$1"
    ssh [email protected] "cd testdir;./test.sh $__"
}
  • When declaring a function with function, () is not necessary.
  • Don't comment back about it just because you're a POSIXist.

How do I print colored output to the terminal in Python?

What about the ansicolors library? You can simple do:

from colors import color, red, blue

# common colors
print(red('This is red'))
print(blue('This is blue'))

# colors by name or code
print(color('Print colors by name or code', 'white', '#8a2be2'))