Programs & Examples On #Android ksoap2

a lightweight and efficient SOAP client library for the Android platform

How to hide reference counts in VS2013?

Another option is to use mouse, right click on "x reference". Context menu "CodeLens Options" will appear, saving all the navigation headache.

A function to convert null to string

public string nullToString(string value)
{
    return value == null ?string.Empty: value;   
}

How to overwrite the previous print to stdout in python?

@Mike DeSimone answer will probably work most of the time. But...

for x in ['abc', 1]:
    print '{}\r'.format(x),

-> 1bc

This is because the '\r' only goes back to the beginning of the line but doesn't clear the output.

EDIT: Better solution (than my old proposal below)

If POSIX support is enough for you, the following would clear the current line and leave the cursor at its beginning:

print '\x1b[2K\r',

It uses ANSI escape code to clear the terminal line. More info can be found in wikipedia and in this great talk.

Old answer

The (not so good) solution I've found looks like this:

last_x = ''
for x in ['abc', 1]:
    print ' ' * len(str(last_x)) + '\r',
    print '{}\r'.format(x),
    last_x = x

-> 1

One advantage is that it will work on windows too.

Difference between filter and filter_by in SQLAlchemy

We actually had these merged together originally, i.e. there was a "filter"-like method that accepted *args and **kwargs, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over the difference between column == expression and keyword = expression. So we split them up.

How to pass extra variables in URL with WordPress

To make the round trip "The WordPress Way" on the "front-end" (doesn't work in the context of wp-admin), you need to use 3 WordPress functions:

  • add_query_arg() - to create the URL with your new query variable ('c' in your example)
  • the query_vars filter - to modify the list of public query variables that WordPress knows about (this only works on the front-end, because the WP Query is not used on the back end - wp-admin - so this will also not be available in admin-ajax)
  • get_query_var() - to retrieve the value of your custom query variable passed in your URL.

Note: there's no need to even touch the superglobals ($_GET) if you do it this way.

Example

On the page where you need to create the link / set the query variable:

if it's a link back to this page, just adding the query variable

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">

if it's a link to some other page

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) ) )?>">

In your functions.php, or some plugin file or custom class (front-end only):

function add_custom_query_var( $vars ){
  $vars[] = "c";
  return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );

On the page / function where you wish to retrieve and work with the query var set in your URL:

$my_c = get_query_var( 'c' );

On the Back End (wp-admin)

On the back end we don't ever run wp(), so the main WP Query does not get run. As a result, there are no query vars and the query_vars hook is not run.

In this case, you'll need to revert to the more standard approach of examining your $_GET superglobal. The best way to do this is probably:

$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );

though in a pinch you could do the tried and true

$my_c = isset( $_GET['c'] ? $_GET['c'] : "";

or some variant thereof.

file path Windows format to java format

String path = "C:\\Documents and Settings\\someDir";
path = path.replaceAll("\\\\", "/");

In Windows you should use four backslash but not two.

How to work with complex numbers in C?

This code will help you, and it's fairly self-explanatory:

#include <stdio.h>      /* Standard Library of Input and Output */
#include <complex.h>    /* Standard Library of Complex Numbers */

int main() {

    double complex z1 = 1.0 + 3.0 * I;
    double complex z2 = 1.0 - 4.0 * I;

    printf("Working with complex numbers:\n\v");

    printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));

    double complex sum = z1 + z2;
    printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));

    double complex difference = z1 - z2;
    printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));

    double complex product = z1 * z2;
    printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));

    double complex quotient = z1 / z2;
    printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));

    double complex conjugate = conj(z1);
    printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));

    return 0;
}

  with:

creal(z1): get the real part (for float crealf(z1), for long double creall(z1))

cimag(z1): get the imaginary part (for float cimagf(z1), for long double cimagl(z1))

Another important point to remember when working with complex numbers is that functions like cos(), exp() and sqrt() must be replaced with their complex forms, e.g. ccos(), cexp(), csqrt().

How to set UICollectionViewCell Width and Height programmatically

Try to use UICollectionViewDelegateFlowLayout method. In Xcode 11 or later, you need to set Estimate Size to none from storyboard.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: 
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let padding: CGFloat =  170
    let collectionViewSize = advertCollectionView.frame.size.width - padding
    return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
}

Console app arguments, how arguments are passed to Main method

The main method of the runtime engine looks something like int main(int argc, char *argv[]), where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.

Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().

Converting string format to datetime in mm/dd/yyyy

You need an uppercase M for the month part.

string strDate = DateTime.Now.ToString("MM/dd/yyyy");

Lowercase m is for outputting (and parsing) a minute (such as h:mm).

e.g. a full date time string might look like this:

string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");

Notice the uppercase/lowercase mM difference.


Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.

public static class DateTimeMyFormatExtensions
{
  public static string ToMyFormatString(this DateTime dt)
  {
    return dt.ToString("MM/dd/yyyy");
  }
}

public static class StringMyDateTimeFormatExtension
{
  public static DateTime ParseMyFormatDateTime(this string s)
  {
    var culture = System.Globalization.CultureInfo.CurrentCulture;
    return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
  }
}

EXAMPLE: Translating between DateTime/string

DateTime now = DateTime.Now;

string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();

Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.

System.Globalization.CultureInfo.CurrentCulture.

The only easy way you can do is to roll a custom extension method.

Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.

Share data between AngularJS controllers

There are many ways you can share the data between controllers

  1. using services
  2. using $state.go services
  3. using stateparams
  4. using rootscope

Explanation of each method:

  1. I am not going to explain as its already explained by someone

  2. using $state.go

      $state.go('book.name', {Name: 'XYZ'}); 
    
      // then get parameter out of URL
      $state.params.Name;
    
  3. $stateparam works in a similar way to $state.go, you pass it as object from sender controller and collect in receiver controller using stateparam

  4. using $rootscope

    (a) sending data from child to parent controller

      $scope.Save(Obj,function(data) {
          $scope.$emit('savedata',data); 
          //pass the data as the second parameter
      });
    
      $scope.$on('savedata',function(event,data) {
          //receive the data as second parameter
      }); 
    

    (b) sending data from parent to child controller

      $scope.SaveDB(Obj,function(data){
          $scope.$broadcast('savedata',data);
      });
    
      $scope.SaveDB(Obj,function(data){`enter code here`
          $rootScope.$broadcast('saveCallback',data);
      });
    

What is a "thread" (really)?

Processes are like two people using two different computers, who use the network to share data when necessary. Threads are like two people using the same computer, who don't have to share data explicitly but must carefully take turns.

Conceptually, threads are just multiple worker bees buzzing around in the same address space. Each thread has its own stack, its own program counter, etc., but all threads in a process share the same memory. Imagine two programs running at the same time, but they both can access the same objects.

Contrast this with processes. Processes each have their own address space, meaning a pointer in one process cannot be used to refer to an object in another (unless you use shared memory).

I guess the key things to understand are:

  • Both processes and threads can "run at the same time".
  • Processes do not share memory (by default), but threads share all of their memory with other threads in the same process.
  • Each thread in a process has its own stack and its own instruction pointer.

Node.js check if file exists

Old Version before V6: here's the documentation

  const fs = require('fs');    
  fs.exists('/etc/passwd', (exists) => {
     console.log(exists ? 'it\'s there' : 'no passwd!');
  });
// or Sync

  if (fs.existsSync('/etc/passwd')) {
    console.log('it\'s there');
  }

UPDATE

New versions from V6: documentation for fs.stat

fs.stat('/etc/passwd', function(err, stat) {
    if(err == null) {
        //Exist
    } else if(err.code == 'ENOENT') {
        // NO exist
    } 
});

How do you clear the console screen in C?

In Windows I have made the mistake of using

system("clear")

but that is actually for Linux

The Windows type is

system("cls")

without #include conio.h

Setting unique Constraint with fluent API?

Unfortunately this is not supported in Entity Framework. It was on the roadmap for EF 6, but it got pushed back: Workitem 299: Unique Constraints (Unique Indexes)

Echo off but messages are displayed

Save this as *.bat file and see differences

:: print echo command and its output
echo 1

:: does not print echo command just its output
@echo 2

:: print dir command but not its output
dir > null

:: does not print dir command nor its output
@dir c:\ > null

:: does not print echo (and all other commands) but print its output
@echo off
echo 3

@echo on
REM this comment will appear in console if 'echo off' was not set

@set /p pressedKey=Press any key to exit

Git error on git pull (unable to update local ref)

Speaking from a PC user - Reboot.

Honestly, it worked for me. I've solved two strange git issues I thought were corruptions this way.

How to limit google autocomplete results to City and Country only

You can try the country restriction

function initialize() {

 var options = {
  types: ['(cities)'],
  componentRestrictions: {country: "us"}
 };

 var input = document.getElementById('searchTextField');
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}

More info:

ISO 3166-1 alpha-2 can be used to restrict results to specific groups. Currently, you can use componentRestrictions to filter by country.

The country must be passed as as a two character, ISO 3166-1 Alpha-2 compatible country code.


Officially assigned country codes

How can I output a UTF-8 CSV in PHP that Excel will read properly?

Add:

fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));

Or:

fprintf($file, "\xEF\xBB\xBF");

Before writing any content to CSV file.

Example:

<?php
$file = fopen( "file.csv", "w");
fprintf( $file, "\xEF\xBB\xBF");
fputcsv( $file, ["english", 122, "?????"]);
fclose($file);

how to get the selected index of a drop down

If you are actually looking for the index number (and not the value) of the selected option then it would be

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */

or using jQuery

$('select[name="CCards"]')[0].selectedIndex 

Binding a generic list to a repeater - ASP.NET

Code Behind:

public class Friends
{
    public string   ID      { get; set; }
    public string   Name    { get; set; }
    public string   Image   { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
        List <Friends> friendsList = new List<Friends>();

        foreach (var friend  in friendz)
        {
            friendsList.Add(
                new Friends { ID = friend.id, Name = friend.name }    
            );

        }

        this.rptFriends.DataSource = friendsList;
        this.rptFriends.DataBind();
}

.aspx Page

<asp:Repeater ID="rptFriends" runat="server">
            <HeaderTemplate>
                <table border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                    <tr>
                        <td><%# Eval("ID") %></td>
                        <td><%# Eval("Name") %></td>
                    </tr>
            </ItemTemplate>
            <FooterTemplate>
                    </tbody>
                </table>
            </FooterTemplate>
        </asp:Repeater>

How to create standard Borderless buttons (like in the design guideline mentioned)?

Late answer, but many views. As APIs < 11 ain't dead yet, for those interested here is a trick.

Let your container have the desired color (may be transparent). Then give your buttons a selector with default transparent color, and some color when pressed. That way you'll have a transparent button, but will change color when pressed (like holo's). You can also add some animation (like holo's). The selector should be something like this:

res/drawable/selector_transparent_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" 
          android:exitFadeDuration="@android:integer/config_shortAnimTime">
     <item android:state_pressed="true"
         android:drawable="@color/blue" />

   <item android:drawable="@color/transparent" />
</selector>

And the button should have android:background="@drawable/selector_transparent_button"

PS: let you container have the dividers (android:divider='@android:drawable/... for API < 11)

PS [Newbies]: you should define those colors in values/colors.xml

Split Spark Dataframe string column into multiple columns

Here's a solution to the general case that doesn't involve needing to know the length of the array ahead of time, using collect, or using udfs. Unfortunately this only works for spark version 2.1 and above, because it requires the posexplode function.

Suppose you had the following DataFrame:

df = spark.createDataFrame(
    [
        [1, 'A, B, C, D'], 
        [2, 'E, F, G'], 
        [3, 'H, I'], 
        [4, 'J']
    ]
    , ["num", "letters"]
)
df.show()
#+---+----------+
#|num|   letters|
#+---+----------+
#|  1|A, B, C, D|
#|  2|   E, F, G|
#|  3|      H, I|
#|  4|         J|
#+---+----------+

Split the letters column and then use posexplode to explode the resultant array along with the position in the array. Next use pyspark.sql.functions.expr to grab the element at index pos in this array.

import pyspark.sql.functions as f

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .show()
#+---+------------+---+---+
#|num|     letters|pos|val|
#+---+------------+---+---+
#|  1|[A, B, C, D]|  0|  A|
#|  1|[A, B, C, D]|  1|  B|
#|  1|[A, B, C, D]|  2|  C|
#|  1|[A, B, C, D]|  3|  D|
#|  2|   [E, F, G]|  0|  E|
#|  2|   [E, F, G]|  1|  F|
#|  2|   [E, F, G]|  2|  G|
#|  3|      [H, I]|  0|  H|
#|  3|      [H, I]|  1|  I|
#|  4|         [J]|  0|  J|
#+---+------------+---+---+

Now we create two new columns from this result. First one is the name of our new column, which will be a concatenation of letter and the index in the array. The second column will be the value at the corresponding index in the array. We get the latter by exploiting the functionality of pyspark.sql.functions.expr which allows us use column values as parameters.

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .show()
#+---+-------+---+
#|num|   name|val|
#+---+-------+---+
#|  1|letter0|  A|
#|  1|letter1|  B|
#|  1|letter2|  C|
#|  1|letter3|  D|
#|  2|letter0|  E|
#|  2|letter1|  F|
#|  2|letter2|  G|
#|  3|letter0|  H|
#|  3|letter1|  I|
#|  4|letter0|  J|
#+---+-------+---+

Now we can just groupBy the num and pivot the DataFrame. Putting that all together, we get:

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .groupBy("num").pivot("name").agg(f.first("val"))\
    .show()
#+---+-------+-------+-------+-------+
#|num|letter0|letter1|letter2|letter3|
#+---+-------+-------+-------+-------+
#|  1|      A|      B|      C|      D|
#|  3|      H|      I|   null|   null|
#|  2|      E|      F|      G|   null|
#|  4|      J|   null|   null|   null|
#+---+-------+-------+-------+-------+

Remove a child with a specific attribute, in SimpleXML for PHP

If you extend the base SimpleXMLElement class, you can use this method:

class MyXML extends SimpleXMLElement {

    public function find($xpath) {
        $tmp = $this->xpath($xpath);
        return isset($tmp[0])? $tmp[0]: null;
    }

    public function remove() {
        $dom = dom_import_simplexml($this);
        return $dom->parentNode->removeChild($dom);
    }

}

// Example: removing the <bar> element with id = 1
$foo = new MyXML('<foo><bar id="1"/><bar id="2"/></foo>');
$foo->find('//bar[@id="1"]')->remove();
print $foo->asXML(); // <foo><bar id="2"/></foo>

ES6 export all values from object

I suggest the following, let's expect a module.js:

const values = { a: 1, b: 2, c: 3 };

export { values }; // you could use default, but I'm specific here

and then you can do in an index.js:

import { values } from "module";

// directly access the object
console.log(values.a); // 1

// object destructuring
const { a, b, c } = values; 
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

// selective object destructering with renaming
const { a:k, c:m } = values;
console.log(k); // 1
console.log(m); // 3

// selective object destructering with renaming and default value
const { a:x, b:y, d:z = 0 } = values;
console.log(x); // 1
console.log(y); // 2
console.log(z); // 0

More examples of destructering objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

Is it possible to interactively delete matching search pattern in Vim?

There are 3 ways I can think of:

The way that is easiest to explain is

:%s/phrase to delete//gc

but you can also (personally I use this second one more often) do a regular search for the phrase to delete

/phrase to delete

Vim will take you to the beginning of the next occurrence of the phrase.

Go into insert mode (hit i) and use the Delete key to remove the phrase.

Hit escape when you have deleted all of the phrase.

Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed

Continue hitting n and dot until you are done.

Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you

Count the number of characters you want to delete

Type that number in (with number keys)

Hit the x key - characters should get deleted

Continue through with n and dot like in the second method.

PS - And if you didn't know already you can do a capital n to move backwards through the search matches.

Understanding Linux /proc/id/maps

Please check: http://man7.org/linux/man-pages/man5/proc.5.html

address           perms offset  dev   inode       pathname
00400000-00452000 r-xp 00000000 08:02 173521      /usr/bin/dbus-daemon

The address field is the address space in the process that the mapping occupies.

The perms field is a set of permissions:

 r = read
 w = write
 x = execute
 s = shared
 p = private (copy on write)

The offset field is the offset into the file/whatever;

dev is the device (major:minor);

inode is the inode on that device.0 indicates that no inode is associated with the memoryregion, as would be the case with BSS (uninitialized data).

The pathname field will usually be the file that is backing the mapping. For ELF files, you can easily coordinate with the offset field by looking at the Offset field in the ELF program headers (readelf -l).

Under Linux 2.0, there is no field giving pathname.

Not showing placeholder for input type="date" field

As of today (2016), I have successfully used those 2 snippets (plus they work great with Bootstrap4).

Input data on the left, placeholder on the left

input[type=date] {
  text-align: right;
}

input[type="date"]:before {
  color: lightgrey;
  content: attr(placeholder) !important;
  margin-right: 0.5em;
}

Placeholder disappear when clicking

input[type="date"]:before {
  color: lightgrey;
  content: attr(placeholder) !important;
  margin-right: 0.5em;
}
input[type="date"]:focus:before {
  content: '' !important;
}

Update MySQL using HTML Form and PHP

Use mysqli instead of mysql, and you need to pass the database name or schema:

before:

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

after:

$conn = mysql_connect($dbhost, $dbuser, $dbpass, $myDBname);

Get file name from a file location in Java

From Apache Commons IO FileNameUtils

String fileName = FilenameUtils.getName(stringNameWithPath);

How can you run a command in bash over and over until success?

To elaborate on @Marc B's answer,

$ passwd
$ while [ $? -ne 0 ]; do !!; done

Is nice way of doing the same thing that's not command specific.

java howto ArrayList push, pop, shift, and unshift

ArrayList is unique in its naming standards. Here are the equivalencies:

Array.push    -> ArrayList.add(Object o); // Append the list
Array.pop     -> ArrayList.remove(int index); // Remove list[index]
Array.shift   -> ArrayList.remove(0); // Remove first element
Array.unshift -> ArrayList.add(int index, Object o); // Prepend the list

Note that unshift does not remove an element, but instead adds one to the list. Also note that corner-case behaviors are likely to be different between Java and JS, since they each have their own standards.

How can I change the value of the elements in a vector?

int main() {
  using namespace std;

  fstream input ("input.txt");
  if (!input) return 1;

  vector<double> v;
  for (double d; input >> d;) {
    v.push_back(d);
  }
  if (v.empty()) return 1;

  double total = std::accumulate(v.begin(), v.end(), 0.0);
  double mean = total / v.size();

  cout << "The values in the file input.txt are:\n";
  for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
    cout << *x << '\n';
  }
  cout << "The sum of the values is: " << total << '\n';
  cout << "The mean value is: " << mean << '\n';
  cout << "After subtracting the mean, The values are:\n";
  for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
    cout << *x - mean << '\n';  // outputs without changing
    *x -= mean;  // changes the values in the vector
  }

  return 0;
}

setting request headers in selenium

For those people using Python, you may consider using Selenium Wire, which can set request headers, as well as provide you with the ability to inspect requests and responses.

from seleniumwire import webdriver  # Import from seleniumwire

# Create a new instance of the Firefox driver (or Chrome)
driver = webdriver.Firefox()

# Create a request interceptor
def interceptor(request):
    del request.headers['Referer']  # Delete the header first
    request.headers['Referer'] = 'some_referer'

# Set the interceptor on the driver
driver.request_interceptor = interceptor

# All requests will now use 'some_referer' for the referer
driver.get('https://mysite')

Enable remote connections for SQL Server Express 2012

One more thing to check is that you have spelled the named instance correctly!

This article is very helpful in troubleshooting connection problems: How to Troubleshoot Connecting to the SQL Server Database Engine

Where can I find MySQL logs in phpMyAdmin?

I had the same problem of @rutherford, today the new phpMyAdmin's 3.4.11.1 GUI is different, so I figure out it's better if someone improves the answers with updated info.

Full mysql logs can be found in:

"Status"->"Binary Log"

This is the answer, doesn't matter if you're using MAMP, XAMPP, LAMP, etc.

How to unstage large number of files without deleting the content

Warning: do not use the following command unless you want to lose uncommitted work!

Using git reset has been explained, but you asked for an explanation of the piped commands as well, so here goes:

git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached

The command git ls-files lists all files git knows about. The option -z imposes a specific format on them, the format expected by xargs -0, which then invokes rm -f on them, which means to remove them without checking for your approval.

In other words, "list all files git knows about and remove your local copy".

Then we get to git diff, which shows changes between different versions of items git knows about. Those can be changes between different trees, differences between local copies and remote copies, and so on.
As used here, it shows the unstaged changes; the files you have changed but haven't committed yet. The option --name-only means you want the (full) file names only and --diff-filter=D means you're interested in deleted files only. (Hey, didn't we just delete a bunch of stuff?) This then gets piped into the xargs -0 we saw before, which invokes git rm --cached on them, meaning that they get removed from the cache, while the working tree should be left alone — except that you've just removed all files from your working tree. Now they're removed from your index as well.

In other words, all changes, staged or unstaged, are gone, and your working tree is empty. Have a cry, checkout your files fresh from origin or remote, and redo your work. Curse the sadist who wrote these infernal lines; I have no clue whatsoever why anybody would want to do this.


TL;DR: you just hosed everything; start over and use git reset from now on.

Redirect Windows cmd stdout and stderr to a single file

You want:

dir > a.txt 2>&1

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL, more explanation and examples on MSDN.

How to use the priority queue STL for objects?

You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement

bool operator<(const Person& lhs, const Person& rhs); 

it should work without any further changes. The implementation could be

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

then instantiate the queue like this:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

I know this is old, but Google sent me here so I guess others will come too like me.

The answer on 2018 is the selected one here: Pycharm: "unresolved reference" error on the IDE when opening a working project

Just be aware that you can only add one Content Root but you can add several Source Folders. No need to touch __init__.py files.

Can we pass an array as parameter in any function in PHP?

Yes, we can pass arrays to a function.

$arr = array(“a” => “first”, “b” => “second”, “c” => “third”);

function user_defined($item, $key)
{
    echo $key.”-”.$item.”<br/>”;
} 

array_walk($arr, ‘user_defined’);

We can find more array functions here

http://skillrow.com/array-functions-in-php-part1/

How to read and write xml files?

Ok, already having DOM, JaxB and XStream in the list of answers, there is still a complete different way to read and write XML: Data projection You can decouple the XML structure and the Java structure by using a library that provides read and writeable views to the XML Data as Java interfaces. From the tutorials:

Given some real world XML:

<weatherdata>
  <weather
    ... 
    degreetype="F"
    lat="50.5520210266113" lon="6.24060010910034" 
    searchlocation="Monschau, Stadt Aachen, NW, Germany" 
            ... >
    <current ... skytext="Clear" temperature="46"/>
  </weather>
</weatherdata>

With data projection you can define a projection interface:

public interface WeatherData {

@XBRead("/weatherdata/weather/@searchlocation")   
String getLocation();

@XBRead("/weatherdata/weather/current/@temperature")
int getTemperature();

@XBRead("/weatherdata/weather/@degreetype")
String getDegreeType();

@XBRead("/weatherdata/weather/current/@skytext")
String getSkytext();

/**
 * This would be our "sub projection". A structure grouping two attribute
 * values in one object.
 */
interface Coordinates {
    @XBRead("@lon")
    double getLongitude();

    @XBRead("@lat")
    double getLatitude();
}

@XBRead("/weatherdata/weather")
Coordinates getCoordinates();
}

And use instances of this interface just like POJOs:

private void printWeatherData(String location) throws IOException {

final String BaseURL = "http://weather.service.msn.com/find.aspx?outputview=search&weasearchstr=";

// We let the projector fetch the data for us
WeatherData weatherData = new XBProjector().io().url(BaseURL + location).read(WeatherData.class);

// Print some values
System.out.println("The weather in " + weatherData.getLocation() + ":");
System.out.println(weatherData.getSkytext());
System.out.println("Temperature: " + weatherData.getTemperature() + "°"
                                   + weatherData.getDegreeType());

// Access our sub projection
Coordinates coordinates = weatherData.getCoordinates();
System.out.println("The place is located at " + coordinates.getLatitude() + ","
                                              + coordinates.getLongitude());
}

This works even for creating XML, the XPath expressions can be writable.

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

For me, it worked once I changed

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

to:

in POM

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre8</version>
</dependency>

and then:

import com.microsoft.sqlserver.jdbc.SQLServerDriver;

...

DriverManager.registerDriver(SQLServerDriver());    
Connection connection = DriverManager.getConnection(connectionUrl); 

How to convert JSON to XML or XML to JSON?

I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly/project. I came up with the following thanks to the source code of the DynamicJson project:

public XmlDocument JsonToXML(string json)
{
    XmlDocument doc = new XmlDocument();

    using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
    {
        XElement xml = XElement.Load(reader);
        doc.LoadXml(xml.ToString());
    }

    return doc;
}

Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from JSON to XML, there are various ways to do the opposite.

get dictionary value by key

          private void button2_Click(object sender, EventArgs e)
            {
                Dictionary<string, string> Data_Array = new Dictionary<string, string>();
                Data_Array.Add("XML_File", "Settings.xml");

                XML_Array(Data_Array);
            }
          static void XML_Array(Dictionary<string, string> Data_Array)
            {
                String xmlfile = Data_Array["XML_File"];
            }

System.Net.WebException: The remote name could not be resolved:

I had a similar issue when trying to access a service (old ASMX service). The call would work when accessing via an IP however when calling with an alias I would get the remote name could not be resolved.

Added the following to the config and it resolved the issue:

<system.net>
    <defaultProxy enabled="true">
    </defaultProxy>
</system.net>

jQuery - Create hidden form element on the fly

$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');

Routing with multiple Get methods in ASP.NET Web API

There are lots of good answers already for this question. However nowadays Route configuration is sort of "deprecated". The newer version of MVC (.NET Core) does not support it. So better to get use to it :)

So I agree with all the answers which uses Attribute style routing. But I keep noticing that everyone repeated the base part of the route (api/...). It is better to apply a [RoutePrefix] attribute on top of the Controller class and don't repeat the same string over and over again.

[RoutePrefix("api/customers")]
public class MyController : Controller
{
 [HttpGet]
 public List<Customer> Get()
 {
   //gets all customer logic
 }

 [HttpGet]
 [Route("currentMonth")]
 public List<Customer> GetCustomerByCurrentMonth()
 {
     //gets some customer 
 }

 [HttpGet]
 [Route("{id}")]
 public Customer GetCustomerById(string id)
 {
  //gets a single customer by specified id
 }
 [HttpGet]
 [Route("customerByUsername/{username}")]
 public Customer GetCustomerByUsername(string username)
 {
    //gets customer by its username
 }
}

Returning a value from callback function in Node.js

I am facing small trouble in returning a value from callback function in Node.js

This is not a "small trouble", it is actually impossible to "return" a value in the traditional sense from an asynchronous function.

Since you cannot "return the value" you must call the function that will need the value once you have it. @display_name already answered your question, but I just wanted to point out that the return in doCall is not returning the value in the traditional way. You could write doCall as follow:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        // call the function that needs the value
        callback(finalData);
        // we are done
        return;
    });
}

Line callback(finalData); is what calls the function that needs the value that you got from the async function. But be aware that the return statement is used to indicate that the function ends here, but it does not mean that the value is returned to the caller (the caller already moved on.)

Iterate through a HashMap

for (Map.Entry<String, String> item : hashMap.entrySet()) {
    String key = item.getKey();
    String value = item.getValue();
}

Docker: Copying files from Docker container to host

I am posting this for anyone that is using Docker for Mac. This is what worked for me:

 $ mkdir mybackup # local directory on Mac

 $ docker run --rm --volumes-from <containerid> \
    -v `pwd`/mybackup:/backup \  
    busybox \                   
    cp /data/mydata.txt /backup 

Note that when I mount using -v that backup directory is automatically created.

I hope this is useful to someone someday. :)

How to debug a bash script?

I found shellcheck utility and may be some folks find it interesting https://github.com/koalaman/shellcheck

A little example:

$ cat test.sh 
ARRAY=("hello there" world)

for x in $ARRAY; do
  echo $x
done

$ shellcheck test.sh 

In test.sh line 3:
for x in $ARRAY; do
         ^-- SC2128: Expanding an array without an index only gives the first element.

fix the bug, first try...

$ cat test.sh       
ARRAY=("hello there" world)

for x in ${ARRAY[@]}; do
  echo $x
done

$ shellcheck test.sh

In test.sh line 3:
for x in ${ARRAY[@]}; do
         ^-- SC2068: Double quote array expansions, otherwise they're like $* and break on spaces.

Let's try again...

$ cat test.sh 
ARRAY=("hello there" world)

for x in "${ARRAY[@]}"; do
  echo $x
done

$ shellcheck test.sh

find now!

It's just a small example.

How to get the number of characters in a std::string?

It might be the easiest way to input a string and find its length.

// Finding length of a string in C++ 
#include<iostream>
#include<string>
using namespace std;

int count(string);

int main()
{
string str;
cout << "Enter a string: ";
getline(cin,str);
cout << "\nString: " << str << endl;
cout << count(str) << endl;

return 0;

}

int count(string s){
if(s == "")
  return 0;
if(s.length() == 1)
  return 1;
else
    return (s.length());

}

How do I create an average from a Ruby array?

You could try something like the following:

a = [1,2,3,4,5]
# => [1, 2, 3, 4, 5]
(a.sum/a.length).to_f
# => 3.0

Include CSS and Javascript in my django template

Refer django docs on static files.

In settings.py:

import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))

MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = 'static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
                    os.path.join(CURRENT_PATH, 'static'),
)

Then place your js and css files static folder in your project. Not in media folder.

In views.py:

from django.shortcuts import render_to_response, RequestContext

def view_name(request):
    #your stuff goes here
    return render_to_response('template.html', locals(), context_instance = RequestContext(request))

In template.html:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>

In urls.py:

from django.conf import settings
urlpatterns += patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

Project file structure can be found here in imgbin.

Check whether a value exists in JSON object

You could improve on the answer from Ponmudi VN:

  • Shorter Code
  • Look for a key and a value

See this fiddle: https://jsfiddle.net/solarbaypilot/sn3wtea2/

function _isContains(json, keyname, value) {

return Object.keys(json).some(key => {
        return typeof json[key] === 'object' ? 
        _isContains(json[key], keyname, value) : key === keyname && json[key] === value;
    });
}

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};


document.getElementById('dog').innerHTML = _isContains(JSONObject, "name", "dog");
document.getElementById('puppy').innerHTML = _isContains(JSONObject, "name", "puppy");

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

Onclick event to remove default value in a text input field

Use onclick="this.value=''":

<input name="Name" value="Enter Your Name" onclick="this.value=''">

Selected value for JSP drop down using JSTL

If you don't mind using jQuery you can use the code bellow:

    <script>
     $(document).ready(function(){
           $("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
     });
     </script>


    <select id="department" name="department">
      <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
      </c:forEach>
    </select>

In the your Servlet add the following:

        request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

for Android Studio 3.0.1, you can config GitHub path for following path:

  1. File > Setting > Version Control
  2. List item
  3. Click "+" on the top-right conor to open "Add VCS Directory Mapping"
  4. Click "Configure VCS" to open "Version Control Configurations"
  5. Click "Git" then you'll see Path to Git executable]
  6. Input : C:\Users[you user name]\AppData\Local\GitHub\PortableGit_d7effa1a4a322478cd29c826b52a0c118ad3db11\cmd\git.exe
  7. Test it

enter image description here

jQuery get content between <div> tags

use jquery for that:

$("#divId").html()

Wait 5 seconds before executing next line

Create new Js function

function sleep(delay) {
        var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
      }

Call the function when you want to delay execution. Use milliseconds in int for delay value.

####Some code
 sleep(1000);
####Next line

Which Android IDE is better - Android Studio or Eclipse?

From the Android Studio download page:

Caution: Android Studio is currently available as an early access preview. Several features are either incomplete or not yet implemented and you may encounter bugs. If you are not comfortable using an unfinished product, you may want to instead download (or continue to use) the ADT Bundle (Eclipse with the ADT Plugin).

Convert Select Columns in Pandas Dataframe to Numpy Array

Please use the Pandas to_numpy() method. Below is an example--

>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1, 2], "B":[3, 4], "C":[5, 6]})
>>> df 
    A  B  C
 0  1  3  5
 1  2  4  6
>>> s_array = df[["A", "B", "C"]].to_numpy()
>>> s_array

array([[1, 3, 5],
   [2, 4, 6]]) 

>>> t_array = df[["B", "C"]].to_numpy() 
>>> print (t_array)

[[3 5]
 [4 6]]

Hope this helps. You can select any number of columns using

columns = ['col1', 'col2', 'col3']
df1 = df[columns]

Then apply to_numpy() method.

c++ integer->std::string conversion. Simple function?

Now in c++11 we have

#include <string>
string s = std::to_string(123);

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

How to make a function wait until a callback has been called using node.js

Using async and await it is lot more easy.

router.post('/login',async (req, res, next) => {
i = await queries.checkUser(req.body);
console.log('i: '+JSON.stringify(i));
});

//User Available Check
async function checkUser(request) {
try {
    let response = await sql.query('select * from login where email = ?', 
    [request.email]);
    return response[0];

    } catch (err) {
    console.log(err);

  }

}

How to use: while not in

while not any( x in ('AND','OR','NOT') for x in list)

EDIT:

thank you for the upvotes , but etarion's solution is better since it tests if the words AND, OR, NOT are in the list, that is to say 3 tests.

Mine does as many tests as there are words in list.

EDIT2:

Also there is

while not ('AND' in list,'OR' in list,'NOT' in list)==(False,False,False)

Filtering a spark dataframe based on date

The following solutions are applicable since spark 1.5 :

For lower than :

// filter data where the date is lesser than 2015-03-14
data.filter(data("date").lt(lit("2015-03-14")))      

For greater than :

// filter data where the date is greater than 2015-03-14
data.filter(data("date").gt(lit("2015-03-14"))) 

For equality, you can use either equalTo or === :

data.filter(data("date") === lit("2015-03-14"))

If your DataFrame date column is of type StringType, you can convert it using the to_date function :

// filter data where the date is greater than 2015-03-14
data.filter(to_date(data("date")).gt(lit("2015-03-14"))) 

You can also filter according to a year using the year function :

// filter data where year is greater or equal to 2016
data.filter(year($"date").geq(lit(2016))) 

Can't run Curl command inside my Docker Container

If you are using an Alpine based image, you have to

RUN
... \
apk add --no-cache curl \
curl ...
...

How to clear gradle cache?

In android studio open View > Tool Windows > Terminal and execute the following commands

On Windows:

gradlew cleanBuildCache

On Mac or Linux:

./gradlew cleanBuildCache

if you want to disable the cache from your project add this into the gradle build properties

(Warning: this may slow your PC performance if there is no cache than same time will consume after every time during the run app)

android.enableBuildCache=false

How link to any local file with markdown syntax?

If the file is in the same directory as the one where the .md is, then just putting [Click here](MY-FILE.md) should work.

Otherwise, can create a path from the root directory of the project. So if the entire project/git-repo root directory is called 'my-app', and one wants to point to my-app/client/read-me.md, then try [My hyperlink](/client/read-me.md).

At least works from Chrome.

JPA Hibernate One-to-One relationship

I think you still need the primary key property in the OtherInfo class.

@Entity
public class OtherInfo {
    @Id
    public int id;

    @OneToOne(mappedBy="otherInfo")
    public Person person;

    rest of attributes ...
}

Also, you may need to add the @PrimaryKeyJoinColumn annotation to the other side of the mapping. I know that Hibernate uses this by default. But then I haven't used JPA annotations, which seem to require you to specify how the association wokrs.

Best C/C++ Network Library

Aggregated List of Libraries

Replace multiple strings with multiple other strings

<!DOCTYPE html>
<html>
<body>



<p id="demo">Mr Blue 
has a           blue house and a blue car.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/\n| |car/gi, function myFunction(x){

if(x=='\n'){return x='<br>';}
if(x==' '){return x='&nbsp';}
if(x=='car'){return x='BMW'}
else{return x;}//must need



});

    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

How to remove all CSS classes using jQuery/JavaScript?

try with removeClass

For instance:

_x000D_
_x000D_
var nameClass=document.getElementsByClassName("clase1");_x000D_
console.log("after", nameClass[0]);_x000D_
$(".clase1").removeClass();_x000D_
var nameClass=document.getElementsByClassName("clase1");_x000D_
console.log("before", nameClass[0]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="clase1">I am Div with class="clase1"</div>
_x000D_
_x000D_
_x000D_

jQuery if statement to check visibility

Yes you can use .is(':visible') in jquery. But while the code is running under the safari browser .is(':visible') is won't work.

So please use the below code

if( $(".example").offset().top > 0 )

The above line will work both IE as well as safari also.

react native get TextInput value

In React Native 0.43: (Maybe later than 0.43 is OK.)

_handlePress(event) {
    var username= this.refs.username._lastNativeText;

enter image description here

Asp.net Validation of viewstate MAC failed

This error message is normally displayed after you have published your website to the server.

The main problem lies in the Application Pool you use for your website.

Configure your website to use the proper .NET Framework version (i.e. v4.0) under the General section of the Application Pool related to your website.

Under the Process Model, set the Identity value to Network Service.

Close the dialog box and right-click your website and select Advanced Settings... from the Manage Website option of the content menu. In the dialog box, under General section, make sure you have selected the proper name of the Application Pool to be used.

Your website should now run without any problem.

Hope this helps you overcome this error.

What's a quick way to comment/uncomment lines in Vim?

mark a text area by mark command say ma and mb type command: :'a,'bg/(.*)/s////\1/

You can see an example of this kind of test manipulation at http://bknpk.ddns.net/my_web/VIM/vim_shell_cmd_on_block.html

maxlength ignored for input type="number" in Chrome

Change your input type to text and use "oninput" event to call function:

<input type="text" oninput="numberOnly(this.id);" class="test_css" maxlength="4" id="flight_number" name="number"/>

Now use Javascript Regex to filter user input and limit it to numbers only:

function numberOnly(id) {
    // Get element by id which passed as parameter within HTML element event
    var element = document.getElementById(id);
    // This removes any other character but numbers as entered by user
    element.value = element.value.replace(/[^0-9]/gi, "");
}

Demo: https://codepen.io/aslami/pen/GdPvRY

How to avoid "Permission denied" when using pip with virtualenv

I didn't create my virtualenv using sudo. So Sebastian's answer didn't apply to me. My project is called utils. I checked utils directory and saw this:

-rw-r--r--   1 macuser  staff   983  6 Jan 15:17 README.md
drwxr-xr-x   6 root     staff   204  6 Jan 14:36 utils.egg-info
-rw-r--r--   1 macuser  staff    31  6 Jan 15:09 requirements.txt

As you can see, utils.egg-info is owned by root not macuser. That is why it was giving me permission denied error. I also had to remove /Users/macuser/.virtualenvs/armoury/lib/python2.7/site-packages/utils.egg-link as it was created by root as well. I did pip install -e . again after removing those, and it worked.

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

Using return false; or e.stopPropogation(); will not allow further code to execute. It will stop flow at this point itself.

How can I render inline JavaScript with Jade / Pug?

script(nonce="some-nonce").
  console.log("test");

//- Workaround
<script nonce="some-nonce">console.log("test");</script>

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

How to read a file without newlines?

my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":
        print(line[:-1])
    else:
        print(line)
my_file.close() 

convert string to specific datetime format?

More formats:

 require 'date'

 date = "01/07/2016 09:17AM"
 DateTime.parse(date).strftime("%A, %b %d")
 #=> Friday, Jul 01

 DateTime.parse(date).strftime("%m/%d/%Y")
 #=> 07/01/2016

 DateTime.parse(date).strftime("%m-%e-%y %H:%M")
 #=> 07- 1-16 09:17

 DateTime.parse(date).strftime("%b %e")
 #=> Jul  1

 DateTime.parse(date).strftime("%l:%M %p")
 #=>  9:17 AM

 DateTime.parse(date).strftime("%B %Y")
 #=> July 2016
 DateTime.parse(date).strftime("%b %d, %Y")
 #=> Jul 01, 2016
 DateTime.parse(date).strftime("%a, %e %b %Y %H:%M:%S %z")
 #=> Fri,  1 Jul 2016 09:17:00 +0200
 DateTime.parse(date).strftime("%Y-%m-%dT%l:%M:%S%z")
 #=> 2016-07-01T 9:17:00+0200
 DateTime.parse(date).strftime("%I:%M:%S %p")
 #=> 09:17:00 AM
 DateTime.parse(date).strftime("%H:%M:%S")
 #=> 09:17:00
 DateTime.parse(date).strftime("%e %b %Y %H:%M:%S%p")
 #=>  1 Jul 2016 09:17:00AM
 DateTime.parse(date).strftime("%d.%m.%y")
 #=> 01.07.16
 DateTime.parse(date).strftime("%A, %d %b %Y %l:%M %p")
 #=> Friday, 01 Jul 2016  9:17 AM

IF/ELSE Stored Procedure

try

IF(@Trans_type = 'subscr_signup')    
BEGIN 
 set @tmpType = 'premium' 
 END
ELSE iF(@Trans_type = 'subscr_cancel')  
  begin
     set    @tmpType = 'basic'  
  END

What generates the "text file busy" message in Unix?

root@h1:bin[0]# mount h2:/ /x             
root@h1:bin[0]# cp /usr/bin/cat /x/usr/local/bin/
root@h1:bin[0]# umount /x
...
root@h2:~[0]# /usr/local/bin/cat 
-bash: /usr/local/bin/cat: Text file busy
root@h2:~[126]#

ubuntu 20.04, 5.4.0-40-generic
nfsd problem, after reboot ok

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

Vue is not defined

I needed to add the script below to index.html inside the HEAD tag.

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

But in your case, since you don't have index.html, just add it to your HEAD tag instead.

So it's like:

<!doctype html>
<html>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
...
</body>
</html>

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

If after following the steps as described by Surjeet you still can't connect, try turning your computer's Wi-Fi off and on again. This worked for me.

Also, be sure to trust the developer certificate on the iOS device (Settings - General - Profiles & Device Management - Developer App).

How can I get the client's IP address in ASP.NET MVC?

I had trouble using the above, and I needed the IP address from a controller. I used the following in the end:

System.Web.HttpContext.Current.Request.UserHostAddress

Mathematical functions in Swift

As other noted you have several options. If you want only mathematical functions. You can import only Darwin.

import Darwin

If you want mathematical functions and other standard classes and functions. You can import Foundation.

import Foundation

If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.

For OS X, you need import Cocoa.

import Cocoa

For iOS, you need import UIKit.

import UIKit

You can easily discover your playground platform by opening File Inspector (??1).

Playground Settings - Platform

a = open("file", "r"); a.readline() output without \n

A solution, can be:

with open("file", "r") as fd:
    lines = fd.read().splitlines()

You get the list of lines without "\r\n" or "\n".

Or, use the classic way:

with open("file", "r") as fd:
    for line in fd:
        line = line.strip()

You read the file, line by line and drop the spaces and newlines.

If you only want to drop the newlines:

with open("file", "r") as fd:
    for line in fd:
        line = line.replace("\r", "").replace("\n", "")

Et voilà.

Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open.

See the documentation of io.open.

So, you can use:

with io.open("file", "r", newline=None) as fd:
    for line in fd:
        line = line.replace("\n", "")

When the newline parameter is None: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

Define global variable with webpack

Use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

new webpack.DefinePlugin(definitions)

Example:

plugins: [
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true)
  })
  //...
]

Usage:

console.log(`Environment is in production: ${PRODUCTION}`);

How should I throw a divide by zero exception in Java without actually dividing by zero?

Something like:

if(divisor == 0) {
  throw new ArithmeticException("Division by zero!");
}

How do I create a constant in Python?

(This paragraph was meant to be a comment on those answers here and there, which mentioned namedtuple, but it is getting too long to be fit into a comment, so, here it goes.)

The namedtuple approach mentioned above is definitely innovative. For the sake of completeness, though, at the end of the NamedTuple section of its official documentation, it reads:

enumerated constants can be implemented with named tuples, but it is simpler and more efficient to use a simple class declaration:

class Status:
    open, pending, closed = range(3)

In other words, the official documentation kind of prefers to use a practical way, rather than actually implementing the read-only behavior. I guess it becomes yet another example of Zen of Python:

Simple is better than complex.

practicality beats purity.

Where can I find the error logs of nginx, using FastCGI and Django?

Logs location on Linux servers:

Apache – /var/log/httpd/

IIS – C:\inetpub\wwwroot\

Node.js – /var/log/nodejs/

nginx – /var/log/nginx/

Passenger – /var/app/support/logs/

Puma – /var/log/puma/

Python – /opt/python/log/

Tomcat – /var/log/tomcat8

Android get image from gallery into ImageView

Run the app in debug mode and set a breakpoint on if (requestCode == SELECT_PICTURE) and inspect each variable as you step through to ensure it is being set as expected. If you are getting a NPE on img.setImageURI(selectedImageUri); then either img or selectedImageUri are not set.

Android studio: emulator is running but not showing up in Run App "choose a running device"

in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done

Setting up a JavaScript variable from Spring model by using Thymeleaf

If you need to display your variable unescaped, use this format:

<script th:inline="javascript">
/*<![CDATA[*/

    var message = /*[(${message})]*/ 'default';

/*]]>*/
</script>

Note the [( brackets which wrap the variable.

How to compare strings in sql ignoring case?

To avoid string conversions comparisons, use COLLATE SQL_Latin1_General_CP1_CI_AS.

EXAMPLE:

SELECT UserName FROM Users
WHERE UserName **COLLATE SQL_Latin1_General_CP1_CI_AS** = 'Angel'

That will return any usernames, whether ANGEL, angel, or Angel, etc.

Move a view up only when the keyboard covers an input field

Your problem is well explained in this document by Apple. Example code on this page (at Listing 4-1) does exactly what you need, it will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew. The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:

Declare a variable

var activeField: UITextField?

then add these methods

 func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.scrollEnabled = true
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeFieldPresent = activeField
    {
        if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
        {
            self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
        }
    }


}


func keyboardWillBeHidden(notification: NSNotification)
{
    //Once keyboard disappears, restore original positions
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.scrollEnabled = false

}

func textFieldDidBeginEditing(textField: UITextField!)
{
    activeField = textField
}

func textFieldDidEndEditing(textField: UITextField!)
{
    activeField = nil
}

Be sure to declare your ViewController as UITextFieldDelegate and set correct delegates in your initialization methods: ex:

self.you_text_field.delegate = self

And remember to call registerForKeyboardNotifications on viewInit and deregisterFromKeyboardNotifications on exit.

Edit/Update: Swift 4.2 Syntax

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}

C# - Substring: index and length must refer to a location within the string

You need to check your statement like this :

string url = "www.example.com/aaa/bbb.jpg";
string lenght = url.Lenght-4;
if(url.Lenght > 15)//eg 15
{
 string newString = url.Substring(18, lenght);
}

Conversion of System.Array to List

I know two methods:

List<int> myList1 = new List<int>(myArray);

Or,

List<int> myList2 = myArray.ToList();

I'm assuming you know about data types and will change the types as you please.

Get Row Index on Asp.net Rowcommand event

If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:

int index = Convert.ToInt32(e.CommandArgument);

In a custom command, you can set the command argument to yourRow.RowIndex.ToString() and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Remove the space or empty line in server.xml or context.xml at the beginning of your code

Index (zero based) must be greater than or equal to zero

In this line:

Aboutme.Text = String.Format("{2}", reader.GetString(0));

The token {2} is invalid because you only have one item in the parms. Use this instead:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

How can a divider line be added in an Android RecyclerView?

If you want to have both horizontal and vertical dividers:

  1. Define horizontal & vertical divider drawables:

    horizontal_divider.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
      <size android:height="1dip" />
      <solid android:color="#22000000" />
    </shape>
    

    vertical_divider.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <size android:width="1dip" />
        <solid android:color="#22000000" />
    </shape>
    
  2. Add this code segment below:

    DividerItemDecoration verticalDecoration = new DividerItemDecoration(recyclerview.getContext(),
            DividerItemDecoration.HORIZONTAL);
    Drawable verticalDivider = ContextCompat.getDrawable(getActivity(), R.drawable.vertical_divider);
    verticalDecoration.setDrawable(verticalDivider);
    recyclerview.addItemDecoration(verticalDecoration);
    
    DividerItemDecoration horizontalDecoration = new DividerItemDecoration(recyclerview.getContext(),
            DividerItemDecoration.VERTICAL);
    Drawable horizontalDivider = ContextCompat.getDrawable(getActivity(), R.drawable.horizontal_divider);
    horizontalDecoration.setDrawable(horizontalDivider);
    recyclerview.addItemDecoration(horizontalDecoration);
    

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

you should use

getActivity.getSupportFragmentManager() like
//in my fragment 
SupportMapFragment fm = (SupportMapFragment)    
getActivity().getSupportFragmentManager().findFragmentById(R.id.map);

I have also this issues but resolved after adding getActivity() before getSupportFragmentManager.

What does "Object reference not set to an instance of an object" mean?

Not to be blunt but it means exactly what it says. One of your object references is NULL. You'll see this when you try and access the property or method of a NULL'd object.

How to install pywin32 module in windows 7

are you just trying to install it, or are you looking to build from source?

If you just need to install, the easiest way is to use the MSI installers provided here:

http://sourceforge.net/projects/pywin32/files/pywin32/ (for updated versions)

make sure you get the correct version (matches Python version, 32bit/64bit, etc)

How to determine if a String has non-alphanumeric characters?

One approach is to do that using the String class itself. Let's say that your string is something like that:

String s = "some text";
boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");

one other is to use an external library, such as Apache commons:

String s = "some text";
boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

check the code below this will be helpful for you:

<script type="text/javascript">
  window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>

Javascript string/integer comparisons

You can use Number() function also since it converts the object argument to a number that represents the object's value.

Eg: javascript:alert( Number("2") > Number("10"))

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Fastest way to set all values of an array?

You could use arraycopy but it depends on whether you can predefine the source array, - do you need a different character fill each time, or are you filling arrays repeatedly with the same char?

Clearly the length of the fill matters - either you need a source that is bigger than all possible destinations, or you need a loop to repeatedly arraycopy a chunk of data until the destination is full.

    char f = '+';
    char[] c = new char[50];
    for (int i = 0; i < c.length; i++)
    {
        c[i] = f;
    }

    char[] d = new char[50];
    System.arraycopy(c, 0, d, 0, d.length);

Change directory in PowerShell

To go directly to that folder, you can use the Set-Location cmdlet or cd alias:

Set-Location "Q:\My Test Folder"

Why do you create a View in a database?

It can function as a good "middle man" between your ORM and your tables.

Example:

We had a Person table that we needed to change the structure on it so the column SomeColumn was going to be moved to another table and would have a one to many relationship to.

However, the majority of the system, with regards to the Person, still used the SomeColumn as a single thing, not many things. We used a view to bring all of the SomeColumns together and put it in the view, which worked out nicely.

This worked because the data layer had changed, but the business requirement hadn't fundamentally changed, so the business objects didn't need to change. If the business objects had to change I don't think this would have been a viable solution, but views definitely function as a good mid point.

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

How to determine if a list of polygon points are in clockwise order?

A much computationally simpler method, if you already know a point inside the polygon:

  1. Choose any line segment from the original polygon, points and their coordinates in that order.

  2. Add a known "inside" point, and form a triangle.

  3. Calculate CW or CCW as suggested here with those three points.

Custom Listview Adapter with filter Android

you can find custom list adapter class with filterable using text change in edit text...

create custom list adapter class with implementation of Filterable:

private class CustomListAdapter extends BaseAdapter implements Filterable{

    private LayoutInflater inflater;
    private ViewHolder holder;
    private ItemFilter mFilter = new ItemFilter();

    public CustomListAdapter(List<YourCustomData> newlist) {
        filteredData = newlist;
    }

    @Override
    public int getCount() {
        return filteredData.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        holder = new ViewHolder();

        if(inflater==null)
            inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if(convertView == null){
            convertView = inflater.inflate(R.layout.row_listview_item, null);

            holder.mTextView = (TextView)convertView.findViewById(R.id.row_listview_member_tv);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }

        holder.mTextView.setText(""+filteredData.get(position).getYourdata());

        return convertView;
    }

    @Override
    public Filter getFilter() {
        return mFilter;
    }


}

class ViewHolder{
    TextView mTextView;
}

private class ItemFilter extends Filter {
    @SuppressLint("DefaultLocale")
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final List<YourCustomData> list = YourObject.getYourDataList();

        int count = list.size();
        final ArrayList<YourCustomData> nlist = new ArrayList<YourCustomData>(count);

        String filterableString ;

        for (int i = 0; i < count; i++) {
            filterableString = ""+list.get(i).getYourText();
            if (filterableString.toLowerCase().contains(filterString)) {
                YourCustomData mYourCustomData = list.get(i);
                nlist.add(mYourCustomData);
            }
        }

        results.values = nlist;
        results.count = nlist.size();

        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<YourCustomData>) results.values;
        mCustomListAdapter.notifyDataSetChanged();
    }

}

mEditTextSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(mCustomListAdapter!=null)
                mCustomListAdapter.getFilter().filter(s.toString());

        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void afterTextChanged(Editable s) {
        }
    });

An implementation of the fast Fourier transform (FFT) in C#

AForge.net is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/ComplexImage.cs for usage, Sources/Math/FourierTransform.cs for implemenation)

Automatically deleting related rows in Laravel (Eloquent ORM)

You can use this method as an alternative.

What will happen is that we take all the tables associated with the users table and delete the related data using looping

$tables = DB::select("
    SELECT
        TABLE_NAME,
        COLUMN_NAME,
        CONSTRAINT_NAME,
        REFERENCED_TABLE_NAME,
        REFERENCED_COLUMN_NAME
    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE REFERENCED_TABLE_NAME = 'users'
");

foreach($tables as $table){
    $table_name =  $table->TABLE_NAME;
    $column_name = $table->COLUMN_NAME;

    DB::delete("delete from $table_name where $column_name = ?", [$id]);
}

How to add spacing between UITableViewCell

add a inner view to the cell then add your own views to it.

What is the iBeacon Bluetooth Profile

Just to reconcile the difference between sandeepmistry's answer and davidgyoung's answer:

02 01 1a 1a ff 4C 00

Is part of the advertising data format specification [1]

  02 # length of following AD structure
  01 # <<Flags>> AD Structure [2]
  1a # read as b00011010. 
     # In this case, LE General Discoverable,
     # and simultaneous BR/EDR but this may vary by device!

  1a # length of following AD structure
  FF # Manufacturer specific data [3]
4C00 # Apple Inc [4]
0215 # ?? some 2-byte header

Missing from the AD is a Service [5] definition. I think the iBeacon protocol itself has no relationship to the GATT and standard service discovery. If you download RedBearLab's iBeacon program, you'll see that they happen to use the GATT for configuring the advertisement parameters, but this seems to be specific to their implementation, and not part of the spec. The AirLocate program doesn't seem to use the GATT for configuration, for instance, according to LightBlue and or other similar programs I tried.

References:

  1. Core Bluetooth Spec v4, Vol 3, Part C, 11
  2. Vol 3, Part C, 18.1
  3. Vol 3, Part C, 18.11
  4. https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
  5. Vol 3, Part C, 18.2

Excel SUMIF between dates

One more solution when you want to use data from any sell ( in the key C3)

=SUMIF(Sheet6!M:M;CONCATENATE("<";TEXT(C3;"dd.mm.yyyy"));Sheet6!L:L)

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

I wrote this answer about four years ago and my opinion hasn't changed. But since then there have been significant developments on the micro-services front. I added micro-services specific notes at the end...

I'll weigh in against the idea, with real-world experience to back up my vote.

I was brought on to a large application that had five contexts for a single database. In the end, we ended up removing all of the contexts except for one - reverting back to a single context.

At first the idea of multiple contexts seems like a good idea. We can separate our data access into domains and provide several clean lightweight contexts. Sounds like DDD, right? This would simplify our data access. Another argument is for performance in that we only access the context that we need.

But in practice, as our application grew, many of our tables shared relationships across our various contexts. For example, queries to table A in context 1 also required joining table B in context 2.

This left us with a couple poor choices. We could duplicate the tables in the various contexts. We tried this. This created several mapping problems including an EF constraint that requires each entity to have a unique name. So we ended up with entities named Person1 and Person2 in the different contexts. One could argue this was poor design on our part, but despite our best efforts, this is how our application actually grew in the real world.

We also tried querying both contexts to get the data we needed. For example, our business logic would query half of what it needed from context 1 and the other half from context 2. This had some major issues. Instead of performing one query against a single context, we had to perform multiple queries across different contexts. This has a real performance penalty.

In the end, the good news is that it was easy to strip out the multiple contexts. The context is intended to be a lightweight object. So I don't think performance is a good argument for multiple contexts. In almost all cases, I believe a single context is simpler, less complex, and will likely perform better, and you won't have to implement a bunch of work-arounds to get it to work.

I thought of one situation where multiple contexts could be useful. A separate context could be used to fix a physical issue with the database in which it actually contains more than one domain. Ideally, a context would be one-to-one to a domain, which would be one-to-one to a database. In other words, if a set of tables are in no way related to the other tables in a given database, they should probably be pulled out into a separate database. I realize this isn't always practical. But if a set of tables are so different that you would feel comfortable separating them into a separate database (but you choose not to) then I could see the case for using a separate context, but only because there are actually two separate domains.

Regarding micro-services, one single context still makes sense. However, for micro-services, each service would have its own context which includes only the database tables relevant to that service. In other words, if service x accesses tables 1 and 2, and service y accesses tables 3 and 4, each service would have its own unique context which includes tables specific to that service.

I'm interested in your thoughts.

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

How to merge two sorted arrays into a sorted array?

Here's a shortened form written in javascript:

function sort( a1, a2 ) {

    var i = 0
        , j = 0
        , l1 = a1.length
        , l2 = a2.length
        , a = [];

    while( i < l1 && j < l2 ) {

        a1[i] < a2[j] ? (a.push(a1[i]), i++) : (a.push( a2[j]), j++);
    }

    i < l1 && ( a = a.concat( a1.splice(i) ));
    j < l2 && ( a = a.concat( a2.splice(j) ));

    return a;
}

IIS Express Windows Authentication

In IIS Manager click on your site. You need to be "in feature view" (rather than "content view")

In the IIS section of "feature view" choose the so-called feature "authentication" and doulbe click it. Here you can enable Windows Authentication. This is also possible (by i think in one of the suggestions in the thread) by a setting in the web.config ( ...)

But maybe you have a web.config you do not want to scrue too much around with. Then this thread wouldnt be too much help, which is why i added this answer.

adb connection over tcp not working now

Just a tiny update with built-in wireless debugging in Android 11:

  • Go to Developer options > Wireless debugging
  • Enable > allow
  • Pair device with pairing code, a new port and pairing code generated and shown
  • adb pair [IP_ADDRESS]:[PORT] and type pairing code.
  • done

Disable developer mode extensions pop up in Chrome

For anyone using WebdriverIO, you can disable extensions by creating your client like this:

var driver = require('webdriverio');
var client = driver.remote({
    desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions: {
            args: [
                'disable-extensions'
            ]
        }
    }
});

parsing a tab-separated file in Python

I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)

Anyway, here's my take:

Say these are the tab-separated values in your input file:

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20

then this:

with open("tab-separated-values.txt") as inp:
    print( list(zip(*(line.strip().split('\t') for line in inp))) )

would produce the following:

[('1', '6', '11', '16'), 
 ('2', '7', '12', '17'), 
 ('3', '8', '13', '18'), 
 ('4', '9', '14', '19'), 
 ('5', '10', '15', '20')]

As you can see, it put the k-th element of each row into the k-th array.

if statements matching multiple values

An extensionmethod like this would do it...

public static bool In<T>(this T item, params T[] items)
{
    return items.Contains(item);
}

Use it like this:

Console.WriteLine(1.In(1,2,3));
Console.WriteLine("a".In("a", "b"));

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

If you can decode JWT, how are they secure?

I would suggest in taking a look into JWE using special algorithms which is not present in jwt.io to decrypt

Reference link: https://www.npmjs.com/package/node-webtokens

jwt.generate('PBES2-HS512+A256KW', 'A256GCM', payload, pwd, (error, token) => {
  jwt.parse(token).verify(pwd, (error, parsedToken) => {
    // other statements
  });
});

This answer may be too late or you might have already found out the way, but still, I felt it would be helpful for you and others as well.

A simple example which I have created: https://github.com/hansiemithun/jwe-example

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

Git removing upstream from local repository

In git version 2.14.3,

You can remove upstream using

git branch --unset-upstream

The above command will also remove the tracking stream branch, hence if you want to rebase from repository you have use

git rebase origin master 

instead of git pull --rebase

How to extract the decision rules from scikit-learn decision-tree?

Just because everyone was so helpful I'll just add a modification to Zelazny7 and Daniele's beautiful solutions. This one is for python 2.7, with tabs to make it more readable:

def get_code(tree, feature_names, tabdepth=0):
    left      = tree.tree_.children_left
    right     = tree.tree_.children_right
    threshold = tree.tree_.threshold
    features  = [feature_names[i] for i in tree.tree_.feature]
    value = tree.tree_.value

    def recurse(left, right, threshold, features, node, tabdepth=0):
            if (threshold[node] != -2):
                    print '\t' * tabdepth,
                    print "if ( " + features[node] + " <= " + str(threshold[node]) + " ) {"
                    if left[node] != -1:
                            recurse (left, right, threshold, features,left[node], tabdepth+1)
                    print '\t' * tabdepth,
                    print "} else {"
                    if right[node] != -1:
                            recurse (left, right, threshold, features,right[node], tabdepth+1)
                    print '\t' * tabdepth,
                    print "}"
            else:
                    print '\t' * tabdepth,
                    print "return " + str(value[node])

    recurse(left, right, threshold, features, 0)

How do I add a new class to an element dynamically?

CSS really doesn't have the ability to modify an object in the same manner as JavaScript, so in short - no.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How to get the day name from a selected date?

You're looking for the DayOfWeek property.

Here's the msdn article.

How can I remove a child node in HTML using JavaScript?

If you want to clear the div and remove all child nodes, you could put:

var mydiv = document.getElementById('FirstDiv');
while(mydiv.firstChild) {
  mydiv.removeChild(mydiv.firstChild);
}

LINQ Aggregate algorithm explained

Super short Aggregate works like fold in Haskell/ML/F#.

Slightly longer .Max(), .Min(), .Sum(), .Average() all iterates over the elements in a sequence and aggregates them using the respective aggregate function. .Aggregate () is generalized aggregator in that it allows the developer to specify the start state (aka seed) and the aggregate function.

I know you asked for a short explaination but I figured as others gave a couple of short answers I figured you would perhaps be interested in a slightly longer one

Long version with code One way to illustrate what does it could be show how you implement Sample Standard Deviation once using foreach and once using .Aggregate. Note: I haven't prioritized performance here so I iterate several times over the colleciton unnecessarily

First a helper function used to create a sum of quadratic distances:

static double SumOfQuadraticDistance (double average, int value, double state)
{
    var diff = (value - average);
    return state + diff * diff;
}

Then Sample Standard Deviation using ForEach:

static double SampleStandardDeviation_ForEach (
    this IEnumerable<int> ints)
{
    var length = ints.Count ();
    if (length < 2)
    {
        return 0.0;
    }

    const double seed = 0.0;
    var average = ints.Average ();

    var state = seed;
    foreach (var value in ints)
    {
        state = SumOfQuadraticDistance (average, value, state);
    }
    var sumOfQuadraticDistance = state;

    return Math.Sqrt (sumOfQuadraticDistance / (length - 1));
}

Then once using .Aggregate:

static double SampleStandardDeviation_Aggregate (
    this IEnumerable<int> ints)
{
    var length = ints.Count ();
    if (length < 2)
    {
        return 0.0;
    }

    const double seed = 0.0;
    var average = ints.Average ();

    var sumOfQuadraticDistance = ints
        .Aggregate (
            seed,
            (state, value) => SumOfQuadraticDistance (average, value, state)
            );

    return Math.Sqrt (sumOfQuadraticDistance / (length - 1));
}

Note that these functions are identical except for how sumOfQuadraticDistance is calculated:

var state = seed;
foreach (var value in ints)
{
    state = SumOfQuadraticDistance (average, value, state);
}
var sumOfQuadraticDistance = state;

Versus:

var sumOfQuadraticDistance = ints
    .Aggregate (
        seed,
        (state, value) => SumOfQuadraticDistance (average, value, state)
        );

So what .Aggregate does is that it encapsulates this aggregator pattern and I expect that the implementation of .Aggregate would look something like this:

public static TAggregate Aggregate<TAggregate, TValue> (
    this IEnumerable<TValue> values,
    TAggregate seed,
    Func<TAggregate, TValue, TAggregate> aggregator
    )
{
    var state = seed;

    foreach (var value in values)
    {
        state = aggregator (state, value);
    }

    return state;
}

Using the Standard deviation functions would look something like this:

var ints = new[] {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
var average = ints.Average ();
var sampleStandardDeviation = ints.SampleStandardDeviation_Aggregate ();
var sampleStandardDeviation2 = ints.SampleStandardDeviation_ForEach ();

Console.WriteLine (average);
Console.WriteLine (sampleStandardDeviation);
Console.WriteLine (sampleStandardDeviation2);

IMHO

So does .Aggregate help readability? In general I love LINQ because I think .Where, .Select, .OrderBy and so on greatly helps readability (if you avoid inlined hierarhical .Selects). Aggregate has to be in Linq for completeness reasons but personally I am not so convinced that .Aggregate adds readability compared to a well written foreach.

Open soft keyboard programmatically

This works:

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

And you call this method like this:

showKeyboard(NameOfActivity.this);

How can I lookup a Java enum from its String value?

Use the valueOf method which is automatically created for each Enum.

Verbosity.valueOf("BRIEF") == Verbosity.BRIEF

For arbitrary values start with:

public static Verbosity findByAbbr(String abbr){
    for(Verbosity v : values()){
        if( v.abbr().equals(abbr)){
            return v;
        }
    }
    return null;
}

Only move on later to Map implementation if your profiler tells you to.

I know it's iterating over all the values, but with only 3 enum values it's hardly worth any other effort, in fact unless you have a lot of values I wouldn't bother with a Map it'll be fast enough.

Could not find default endpoint element

In my case, I was referring to this service from a library project, not a startup Project. Once I copied <system.serviceModel> section to the configuration of the main startup project, The issue got resolved.

During running stage of any application, the configuration will be read from the startup/parent project instead of reading its own configurations mentioned in separate subprojects.

Get MAC address using shell script

oh, if you want only the mac ether mac address, you can use that:

ifconfig | grep "ether*" | tr -d ' ' | tr -d '\t' | cut -c 6-42

(work on macintosh)

  • ifconfig -- get all info
  • grep -- keep the line with address
  • tr -- clean all
  • cut -- remove the "ether" to have only the address

Retrieving an element from array list in Android?

I have a list of positions of array to retrieve ,This worked for me.

  public void create_list_to_add_group(ArrayList<Integer> arrayList_loc) {
     //In my case arraylist_loc is the list of positions to retrive from 
    // contact_names 
    //arraylist and phone_number arraylist

    ArrayList<String> group_members_list = new ArrayList<>();
    ArrayList<String> group_members_phone_list = new ArrayList<>();

    int size = arrayList_loc.size();

    for (int i = 0; i < size; i++) {

        try {

            int loc = arrayList_loc.get(i);
            group_members_list.add(contact_names_list.get(loc));
            group_members_phone_list.add(phone_num_list.get(loc));


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    Log.e("Group memnbers list", " " + group_members_list);
    Log.e("Group memnbers num list", " " + group_members_phone_list);

}

Which to use <div class="name"> or <div id="name">?

Classes should be used when you have multiple similar elements.

Ex: Many div's displaying song lyrics, you could assign them a class of lyrics since they are all similar.

ID's must be unique! They are used to target specific elements

Ex: An input for a users email could have the ID txtEmail -- No other element should have this ID.

How to change port for jenkins window service when 8080 is being used

For jenkins in a docker container you can use port publish option in docker run command to map jenkins port in container to different outside port.

e.g. map docker container internal jenkins GUI port 8080 to port 9090 external

docker run -it -d --name jenkins42 --restart always \
   -p <ip>:9090:8080 <image>

How can I nullify css property?

You have to reset each individual property back to its default value. It's not great, but it's the only way, given the information you've given us.

In your example, you would do:

.c1 {
    height: auto;
}

You should search for each property here:

https://developer.mozilla.org/en-US/docs/Web/CSS/Reference

For example, height:

Initial value : auto

Another example, max-height:

Initial value : none


In 2017, there is now another way, the unset keyword:

.c1 {
    height: unset;
}

Some documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/unset

The unset CSS keyword is the combination of the initial and inherit keywords. Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not. In other words, it behaves like the inherit keyword in the first case and like the initial keyword in the second case.

Browser support is good: http://caniuse.com/css-unset-value

Why am I getting a "401 Unauthorized" error in Maven?

Failed to transfer file:
http://mcpappxxxp.dev.chx.s.com:18080/artifactory/mcprepo-release-local/Shop/loyalty-telluride/01.16.03/loyalty-tell-01.16.03.jar.
Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]

Solution:

In this case you need to change the version in the pom file, and try to use a new version.

Here 01.16.03 already exist so it was failing and when i have tried with the 01.16.04 version the job went successful.

Docker: How to use bash with an Alpine based docker image?

Alpine docker image doesn't have bash installed by default. You will need to add following commands to get bash:

RUN apk update && apk add bash

If youre using Alpine 3.3+ then you can just do

RUN apk add --no-cache bash

to keep docker image size small. (Thanks to comment from @sprkysnrky)

CSS3 transition on click using pure CSS

Voila!

_x000D_
_x000D_
div {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  font-weight: bold;_x000D_
  width: 48px;_x000D_
  height: 48px;  _x000D_
  transform: rotate(360deg);_x000D_
  transition: transform 0.5s;_x000D_
}_x000D_
_x000D_
div:active {_x000D_
  transform: rotate(0deg);_x000D_
  transition:  0s;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Android basics: running code in the UI thread

If you need to use in Fragment you should use

private Context context;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }


    ((MainActivity)context).runOnUiThread(new Runnable() {
        public void run() {
            Log.d("UI thread", "I am the UI thread");
        }
    });

instead of

getActivity().runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
    }
});

Because There will be null pointer exception in some situation like pager fragment

In Perl, how can I read an entire file into a string?

Another possible way:

open my $fh, '<', "filename";
read $fh, my $string, -s $fh;
close $fh;

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

I have polished this missing subclass of QLabel. It is awesome and works well.

aspectratiopixmaplabel.h

#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H

#include <QLabel>
#include <QPixmap>
#include <QResizeEvent>

class AspectRatioPixmapLabel : public QLabel
{
    Q_OBJECT
public:
    explicit AspectRatioPixmapLabel(QWidget *parent = 0);
    virtual int heightForWidth( int width ) const;
    virtual QSize sizeHint() const;
    QPixmap scaledPixmap() const;
public slots:
    void setPixmap ( const QPixmap & );
    void resizeEvent(QResizeEvent *);
private:
    QPixmap pix;
};

#endif // ASPECTRATIOPIXMAPLABEL_H

aspectratiopixmaplabel.cpp

#include "aspectratiopixmaplabel.h"
//#include <QDebug>

AspectRatioPixmapLabel::AspectRatioPixmapLabel(QWidget *parent) :
    QLabel(parent)
{
    this->setMinimumSize(1,1);
    setScaledContents(false);
}

void AspectRatioPixmapLabel::setPixmap ( const QPixmap & p)
{
    pix = p;
    QLabel::setPixmap(scaledPixmap());
}

int AspectRatioPixmapLabel::heightForWidth( int width ) const
{
    return pix.isNull() ? this->height() : ((qreal)pix.height()*width)/pix.width();
}

QSize AspectRatioPixmapLabel::sizeHint() const
{
    int w = this->width();
    return QSize( w, heightForWidth(w) );
}

QPixmap AspectRatioPixmapLabel::scaledPixmap() const
{
    return pix.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}

void AspectRatioPixmapLabel::resizeEvent(QResizeEvent * e)
{
    if(!pix.isNull())
        QLabel::setPixmap(scaledPixmap());
}

Hope that helps! (Updated resizeEvent, per @dmzl's answer)

Using pip behind a proxy with CNTLM

Using pip behind a work proxy with authentification, note that quotation is required for some OSes when specifing the proxy url with user and password:

pip install <module> --proxy 'http://<proxy_user>:<proxy_password>@<proxy_ip>:<proxy_port>'

Documentation: https://pip.pypa.io/en/stable/user_guide/#using-a-proxy-server

Example:

pip3 install -r requirements.txt --proxy 'http://user:[email protected]:1234'

Example:

pip install flask --proxy 'http://user:[email protected]:1234'

Proxy can also be configured manually in pip.ini. Example:

[global]
proxy = http://user:[email protected]:1234 

Documentation: https://pip.pypa.io/en/stable/user_guide/#config-file

What is the difference between a mutable and immutable string in C#?

String in C# is immutable. If you concatenate it with any string, you are actually making a new string, that is new string object ! But StringBuilder creates mutable string.

Spring RestTemplate timeout

For Spring Boot >= 1.4

@Configuration
public class AppConfig
{
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) 
    {
        return restTemplateBuilder
           .setConnectTimeout(...)
           .setReadTimeout(...)
           .build();
    }
}

For Spring Boot <= 1.3

@Configuration
public class AppConfig
{
    @Bean
    @ConfigurationProperties(prefix = "custom.rest.connection")
    public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() 
    {
        return new HttpComponentsClientHttpRequestFactory();
    }

    @Bean
    public RestTemplate customRestTemplate()
    {
        return new RestTemplate(customHttpRequestFactory());
    }
}

then in your application.properties

custom.rest.connection.connection-request-timeout=...
custom.rest.connection.connect-timeout=...
custom.rest.connection.read-timeout=...

This works because HttpComponentsClientHttpRequestFactory has public setters connectionRequestTimeout, connectTimeout, and readTimeout and @ConfigurationProperties sets them for you.


For Spring 4.1 or Spring 5 without Spring Boot using @Configuration instead of XML

@Configuration
public class AppConfig
{
    @Bean
    public RestTemplate customRestTemplate()
    {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(...);
        httpRequestFactory.setConnectTimeout(...);
        httpRequestFactory.setReadTimeout(...);

        return new RestTemplate(httpRequestFactory);
    }
}

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Check the target definition if you are working with an RCP-SWT project.

Open the target editor of and navigate to the environent definition. There you can set the architecture. The idea is that by starting up your RCP application then only the 32 bit SWT libraries/bundles will be loaded. If you have already a runtime configuration it is advisable to create a new one as well.

Target Editor in Eclipse

How do I prevent an Android device from going to sleep programmatically?

what @eldarerathis said is correct in all aspects, the wake lock is the right way of keeping the device from going to sleep.

I don't know waht you app needs to do but it is really important that you think on how architect your app so that you don't force the phone to stay awake for more that you need, or the battery life will suffer enormously.

I would point you to this really good example on how to use AlarmManager to fire events and wake up the phone and (your app) to perform what you need to do and then go to sleep again: Alarm Manager (source: commonsware.com)

How to hide iOS status bar

To hide status bar in iOS7 you need 2 lines of code

  1. in application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions write

     [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
  2. in info.plist add this

     View-Controller Based Status Bar Appearance = NO
    

How to automatically insert a blank row after a group of data

Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.

Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.

What is __gxx_personality_v0 for?

Exception handling is included in free standing implementations.

The reason of this is that you possibly use gcc to compile your code. If you compile with the option -### you will notice it is missing the linker-option -lstdc++ when it invokes the linker process . Compiling with g++ will include that library, and thus the symbols defined in it.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Simply check how many CPUs you are allocating. With one CPU you do not need to play with your bios.

How to read integer values from text file

I would use nearly the same way but with list as buffer for read integers:

static Object[] readFile(String fileName) {
    Scanner scanner = new Scanner(new File(fileName));
    List<Integer> tall = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {
        tall.add(scanner.nextInt());
    }

    return tall.toArray();
}

How to get char from string by index?

In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45

Now, For positive index ranges for x is from 0 to 44 (i.e. length - 1)

In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

/home/<ipython console> in <module>()

IndexError: string index out of range

In [5]: x[44]
Out[5]: 's'

For Negative index, index ranges from -1 to -45

In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a

For negative index, negative [length -1] i.e. the last valid value of positive index will give second list element as the list is read in reverse order,

In [8]: x[-44]
Out[8]: 'n'

Other, index's examples,

In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'

React: how to update state.item[1] in state using setState?

How about creating another component(for object that needs to go into the array) and pass the following as props?

  1. component index - index will be used to create/update in array.
  2. set function - This function put data into the array based on the component index.
<SubObjectForm setData={this.setSubObjectData}                                                            objectIndex={index}/>

Here {index} can be passed in based on position where this SubObjectForm is used.

and setSubObjectData can be something like this.

 setSubObjectData: function(index, data){
      var arrayFromParentObject= <retrieve from props or state>;
      var objectInArray= arrayFromParentObject.array[index];
      arrayFromParentObject.array[index] = Object.assign(objectInArray, data);
 }

In SubObjectForm, this.props.setData can be called on data change as given below.

<input type="text" name="name" onChange={(e) => this.props.setData(this.props.objectIndex,{name: e.target.value})}/>

Border Radius of Table is not working

border-collapse: separate !important; worked.

Thanks.

HTML

<table class="bordered">
    <thead>
        <tr>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>                            
        </tr>
    </tbody>                    
</table>

CSS

table {
    border-collapse: separate !important;
    border-spacing: 0;
    width: 600px;
    margin: 30px;
}
.bordered {
    border: solid #ccc 1px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    -webkit-box-shadow: 0 1px 1px #ccc;
    -moz-box-shadow: 0 1px 1px #ccc;
    box-shadow: 0 1px 1px #ccc;
}
.bordered tr:hover {
    background: #ECECEC;    
    -webkit-transition: all 0.1s ease-in-out;
    -moz-transition: all 0.1s ease-in-out;
    transition: all 0.1s ease-in-out;
}
.bordered td, .bordered th {
    border-left: 1px solid #ccc;
    border-top: 1px solid #ccc;
    padding: 10px;
    text-align: left;
}
.bordered th {
    background-color: #ECECEC;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#F8F8F8), to(#ECECEC));
    background-image: -webkit-linear-gradient(top, #F8F8F8, #ECECEC);
    background-image: -moz-linear-gradient(top, #F8F8F8, #ECECEC);    
    background-image: linear-gradient(top, #F8F8F8, #ECECEC);
    -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    -moz-box-shadow:0 1px 0 rgba(255,255,255,.8) inset;
    box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    border-top: none;
    text-shadow: 0 1px 0 rgba(255,255,255,.5);
}
.bordered td:first-child, .bordered th:first-child {
    border-left: none;
}
.bordered th:first-child {
    -moz-border-radius: 6px 0 0 0;
    -webkit-border-radius: 6px 0 0 0;
    border-radius: 6px 0 0 0;
}
.bordered th:last-child {
    -moz-border-radius: 0 6px 0 0;
    -webkit-border-radius: 0 6px 0 0;
    border-radius: 0 6px 0 0;
}
.bordered th:only-child{
    -moz-border-radius: 6px 6px 0 0;
    -webkit-border-radius: 6px 6px 0 0;
    border-radius: 6px 6px 0 0;
}
.bordered tr:last-child td:first-child {
    -moz-border-radius: 0 0 0 6px;
    -webkit-border-radius: 0 0 0 6px;
    border-radius: 0 0 0 6px;
}
.bordered tr:last-child td:last-child {
    -moz-border-radius: 0 0 6px 0;
    -webkit-border-radius: 0 0 6px 0;
    border-radius: 0 0 6px 0;
} 

jsFiddle

The Network Adapter could not establish the connection when connecting with Oracle DB

I had similar problem before. But this was resolved when I started using hostname instead of IP address in my connection string.

How to write a foreach in SQL Server?

I came up with a very effective, (I think) readable way to do this.

    1. create a temp table and put the records you want to iterate in there
    2. use WHILE @@ROWCOUNT <> 0 to do the iterating
    3. to get one row at a time do, SELECT TOP 1 <fieldnames>
        b. save the unique ID for that row in a variable
    4. Do Stuff, then delete the row from the temp table based on the ID saved at step 3b.

Here's the code. Sorry, its using my variable names instead of the ones in the question.

            declare @tempPFRunStops TABLE (ProformaRunStopsID int,ProformaRunMasterID int, CompanyLocationID int, StopSequence int );    

        INSERT @tempPFRunStops (ProformaRunStopsID,ProformaRunMasterID, CompanyLocationID, StopSequence) 
        SELECT ProformaRunStopsID, ProformaRunMasterID, CompanyLocationID, StopSequence from ProformaRunStops 
        WHERE ProformaRunMasterID IN ( SELECT ProformaRunMasterID FROM ProformaRunMaster WHERE ProformaId = 15 )

    -- SELECT * FROM @tempPFRunStops

    WHILE @@ROWCOUNT <> 0  -- << I dont know how this works
        BEGIN
            SELECT TOP 1 * FROM @tempPFRunStops
            -- I could have put the unique ID into a variable here
            SELECT 'Ha'  -- Do Stuff
            DELETE @tempPFRunStops WHERE ProformaRunStopsID = (SELECT TOP 1 ProformaRunStopsID FROM @tempPFRunStops)
        END

Factorial in numpy and scipy

enter image description here

after running different aforementioned functions for factorial, by different people, turns out that math.factorial is the fastest to calculate the factorial.

find running times for different functions in the attached image

The type is defined in an assembly that is not referenced, how to find the cause?

It didn't work for me when I've tried to add the reference from the .NET Assemblies tab. It worked, though, when I've added the reference with BROWSE to C:\Windows\Microsoft.NET\Framework\v4.0.30319

Difference between uint32 and uint32_t

uint32_t is standard, uint32 is not. That is, if you include <inttypes.h> or <stdint.h>, you will get a definition of uint32_t. uint32 is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.

UIImageView - How to get the file name of the image assigned?

Nope. You can't do that.

The reason is that a UIImageView instance does not store an image file. It stores a displays a UIImage instance. When you make an image from a file, you do something like this:

UIImage *picture = [UIImage imageNamed:@"myFile.png"];

Once this is done, there is no longer any reference to the filename. The UIImage instance contains the data, regardless of where it got it. Thus, the UIImageView couldn't possibly know the filename.

Also, even if you could, you would never get filename info from a view. That breaks MVC.

How can I find out which server hosts LDAP on my windows domain?

If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Spring Boot Rest Controller how to return different HTTP status codes?

A nice way is to use Spring's ResponseStatusException

Rather than returning a ResponseEntityor similar you simply throw the ResponseStatusException from the controller with an HttpStatus and cause, for example:

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cause description here");

or:

throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Cause description here");

This results in a response to the client containing the HTTP status (e.g. 400 Bad request) with a body like:

{
  "timestamp": "2020-07-09T04:43:04.695+0000",
  "status": 400,
  "error": "Bad Request",
  "message": "Cause description here",
  "path": "/test-api/v1/search"
}

SQL Server: Make all UPPER case to Proper Case/Title Case

Here's a UDF that will do the trick...

create function ProperCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
  declare @Reset bit;
  declare @Ret varchar(8000);
  declare @i int;
  declare @c char(1);

  if @Text is null
    return null;

  select @Reset = 1, @i = 1, @Ret = '';

  while (@i <= len(@Text))
    select @c = substring(@Text, @i, 1),
      @Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,
      @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
      @i = @i + 1
  return @Ret
end

You will still have to use it to update your data though.

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

Remove 'b' character do in front of a string literal in Python 3

This should do the trick:

pw_bytes.decode("utf-8")

How do I add indices to MySQL tables?

You say you have an index, the explain says otherwise. However, if you really do, this is how to continue:

If you have an index on the column, and MySQL decides not to use it, it may by because:

  1. There's another index in the query MySQL deems more appropriate to use, and it can use only one. The solution is usually an index spanning multiple columns if their normal method of retrieval is by value of more then one column.
  2. MySQL decides there are to many matching rows, and thinks a tablescan is probably faster. If that isn't the case, sometimes an ANALYZE TABLE helps.
  3. In more complex queries, it decides not to use it based on extremely intelligent thought-out voodoo in the query-plan that for some reason just not fits your current requirements.

In the case of (2) or (3), you could coax MySQL into using the index by index hint sytax, but if you do, be sure run some tests to determine whether it actually improves performance to use the index as you hint it.

Where to get this Java.exe file for a SQL Developer installation

I encountered the following message repeatedly when trying to start SQL Developer from my installation of Oracle Database 11g Enterprise: Enter the full pathname for java.exe.

No matter how many times I browsed to the correct path, I kept being presented with the exact same dialog box. This was in Windows 7, and the solution was to right-click on the SQL Developer icon and select "Run as administrator". I then used this path: C:\app\shellperson\product\11.1.0\db_1\jdk\jre\bin\java.exe

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

How to access private data members outside the class without making "friend"s?

Bad idea, don't do it ever - but here it is how it can be done:

int main()
{
   A aObj;
   int* ptr;

   ptr = (int*)&aObj;

   // MODIFY!
   *ptr = 100;
}

How to use multiple databases in Laravel

Also you can use postgres fdw system

https://www.postgresql.org/docs/9.5/postgres-fdw.html

You will be able to connect different db in postgres. After that, in one query, you can access tables that are in different databases.

Check if a variable is null in plsql

In PL/SQL you can't use operators such as '=' or '<>' to test for NULL because all comparisons to NULL return NULL. To compare something against NULL you need to use the special operators IS NULL or IS NOT NULL which are there for precisely this purpose. Thus, instead of writing

IF var = NULL THEN...

you should write

IF VAR IS NULL THEN...

In the case you've given you also have the option of using the NVL built-in function. NVL takes two arguments, the first being a variable and the second being a value (constant or computed). NVL looks at its first argument and, if it finds that the first argument is NULL, returns the second argument. If the first argument to NVL is not NULL, the first argument is returned. So you could rewrite

IF var IS NULL THEN
  var := 5;
END IF;

as

var := NVL(var, 5);

I hope this helps.

EDIT

And because it's nearly ten years since I wrote this answer, let's celebrate by expanding it just a bit.

The COALESCE function is the ANSI equivalent of Oracle's NVL. It differs from NVL in a couple of IMO good ways:

  1. It takes any number of arguments, and returns the first one which is not NULL. If all the arguments passed to COALESCE are NULL, it returns NULL.

  2. In contrast to NVL, COALESCE only evaluates arguments if it must, while NVL evaluates both of its arguments and then determines if the first one is NULL, etc. So COALESCE can be more efficient, because it doesn't spend time evaluating things which won't be used (and which can potentially cause unwanted side effects), but it also means that COALESCE is not a 100% straightforward drop-in replacement for NVL.

Load jQuery with Javascript and use jQuery

HTML:

<html>
  <head>

  </head>
  <body>

    <div id='status'>jQuery is not loaded yet.</div>
    <input type='button' value='Click here to load it.' onclick='load()' />

  </body>
</html>   

Script:

   <script>

        load = function() {
          load.getScript("jquery-1.7.2.js");
          load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
        }

        // dynamically load any javascript file.
        load.getScript = function(filename) {
          var script = document.createElement('script')
          script.setAttribute("type","text/javascript")
          script.setAttribute("src", filename)
          if (typeof script!="undefined")
          document.getElementsByTagName("head")[0].appendChild(script)
        }

        </script>

Using SELECT result in another SELECT

You are missing table NewScores, so it can't be found. Just join this table.

If you really want to avoid joining it directly you can replace NewScores.NetScore with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}

Decimal or numeric values in regular expression validation

I had the same problem, but I also wanted ".25" to be a valid decimal number. Here is my solution using JavaScript:

function isNumber(v) {
  // [0-9]* Zero or more digits between 0 and 9  (This allows .25 to be considered valid.)
  // ()? Matches 0 or 1 things in the parentheses.  (Allows for an optional decimal point)
  // Decimal point escaped with \.
  // If a decimal point does exist, it must be followed by 1 or more digits [0-9]
  // \d and [0-9] are equivalent 
  // ^ and $ anchor the endpoints so tthe whole string must match.
  return v.trim().length > 0 && v.trim().match(/^[0-9]*(\.[0-9]+)?$/);
}

Where my trim() method is

String.prototype.trim = function() {
  return this.replace(/(^\s*|\s*$)/g, "");
};

Matthew DesVoigne

Operator overloading on class templates

This way works:

class A
{
    struct Wrap
    {
        A& a;
        Wrap(A& aa) aa(a) {}
        operator int() { return a.value; }
        operator std::string() { stringstream ss; ss << a.value; return ss.str(); } 
    }
    Wrap operator*() { return Wrap(*this); }
};

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

With the release of Java 5, the product version was made distinct from the developer version as described here

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See: