Programs & Examples On #Igrouping

How to get values from IGrouping

From definition of IGrouping :

IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable

you can just iterate through elements like this:

IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}

How to move all HTML element children to another parent using JavaScript?

DEMO

Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.

var newParent = document.getElementById('new-parent');
var oldParent = document.getElementById('old-parent');

while (oldParent.childNodes.length > 0) {
    newParent.appendChild(oldParent.childNodes[0]);
}

Array to Collection: Optimized code

What about :

List myList = new ArrayList(); 
String[] myStringArray = new String[] {"Java", "is", "Cool"}; 

Collections.addAll(myList, myStringArray); 

How do you wait for input on the same Console.WriteLine() line?

Use Console.Write instead, so there's no newline written:

Console.Write("What is your name? ");
var name = Console.ReadLine();

Is the size of C "int" 2 bytes or 4 bytes?

Is the size of C “int” 2 bytes or 4 bytes?

Does an Integer variable in C occupy 2 bytes or 4 bytes?

C allows "bytes" to be something other than 8 bits per "byte".

CHAR_BIT number of bits for smallest object that is not a bit-field (byte) C11dr §5.2.4.2.1 1

A value of something than 8 is increasingly uncommon. For maximum portability, use CHAR_BIT rather than 8. The size of an int in bits in C is sizeof(int) * CHAR_BIT.

#include <limits.h>
printf("(int) Bit size %zu\n", sizeof(int) * CHAR_BIT);

What are the factors that it depends on?

The int bit size is commonly 32 or 16 bits. C specified minimum ranges:

minimum value for an object of type int INT_MIN -32767
maximum value for an object of type int INT_MAX +32767
C11dr §5.2.4.2.1 1

The minimum range for int forces the bit size to be at least 16 - even if the processor was "8-bit". A size like 64 bits is seen in specialized processors. Other values like 18, 24, 36, etc. have occurred on historic platforms or are at least theoretically possible. Modern coding rarely worries about non-power-of-2 int bit sizes.

The computer's processor and architecture drive the int bit size selection.

Yet even with 64-bit processors, the compiler's int size may be 32-bit for compatibility reasons as large code bases depend on int being 32-bit (or 32/16).

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

How to parse JSON without JSON.NET library?

You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly

The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");

If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:

using System.Json;


JsonObject result = value as JsonObject;

Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);

The classes are quite similar to those found in the System.Xml.Linq Namespace.

Command prompt won't change directory to another drive

You can change directory using this command like : currently if you current working directoris c:\ drive the if you want to go to your D:\ drive then type this command

cd /d D:\

now your current working directory is D:\ drive so you want go to Java directory under Docs so type below command :

cd Docs\Java

note : d stands for drive

auto refresh for every 5 mins

Page should be refresh auto using meta tag

<meta http-equiv="Refresh" content="60"> 

content value in seconds.after one minute page should be refresh

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

The way I solved this issue was quite simple, I checked my chrome version and I had an older chromedriver in my PATH variable, so I downloaded the chromedriver version that matched my browser and replaced the old one in the PATH, so when the webdriver module looked for a chromedriver in my PATH, it would find the matching version

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

Java math function to convert positive int to negative and negative to positive?

original *= -1;

Simple line of code, original is any int you want it to be.

ORA-00060: deadlock detected while waiting for resource

You can get deadlocks on more than just row locks, e.g. see this. The scripts may be competing for other resources, such as index blocks.

I've gotten around this in the past by engineering the parallelism in such a way that different instances are working on portions of the workload that are less likely to affect blocks that are close to each other; for example, for an update of a large table, instead of setting up the parallel slaves using something like MOD(n,10), I'd use TRUNC(n/10) which mean that each slave worked on a contiguous set of data.

There are, of course, much better ways of splitting up a job for parallelism, e.g. DBMS_PARALLEL_EXECUTE.

Not sure why you're getting "PL/SQL successfully completed", perhaps your scripts are handling the exception?

The performance impact of using instanceof in Java

Modern JVM/JIT compilers have removed the performance hit of most of the traditionally "slow" operations, including instanceof, exception handling, reflection, etc.

As Donald Knuth wrote, "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." The performance of instanceof probably won't be an issue, so don't waste your time coming up with exotic workarounds until you're sure that's the problem.

How can I remove a substring from a given String?

private static void replaceChar() {
    String str = "hello world";
    final String[] res = Arrays.stream(str.split(""))
            .filter(s -> !s.equalsIgnoreCase("o"))
            .toArray(String[]::new);
    System.out.println(String.join("", res));
}

In case you have some complicated logic to filter the char, just another way instead of replace().

Why split the <script> tag when writing it with document.write()?

The </script> inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (see example on JSFiddle).

To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (see example in JSFiddle):

<script type="text/javascript">
    <!--
    if (jQuery === undefined) {
        document.write('<script type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></script>');
    }
    // -->
</script>

...but to be honest, using document.write is not something I would consider best practice. Why not manipulating the DOM directly?

<script type="text/javascript">
    <!--
    if (jQuery === undefined) {
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');
        document.body.appendChild(script);
    }
    // -->
</script>

What does Include() do in LINQ?

Let's say for instance you want to get a list of all your customers:

var customers = context.Customers.ToList();

And let's assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product.

As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include() allows you to indicate which related entities should be read from the database as part of the same query.

Using the same example, this might bring in all of the related order headers, but none of the other records:

var customersWithOrderDetail = context.Customers.Include("Orders").ToList();

As a final point since you asked for SQL, the first statement without Include() could generate a simple statement:

SELECT * FROM Customers;

The final statement which calls Include("Orders") may look like this:

SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;

Format number to always show 2 decimal places

I do like:

var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75

Round the number with 2 decimal points, then make sure to parse it with parseFloat() to return Number, not String unless you don't care if it is String or Number.

jQuery Array of all selected checkboxes (by class)

var matches = [];
$(".className:checked").each(function() {
    matches.push(this.value);
});

How to hash a password

  1. Create a salt,
  2. Create a hash password with salt
  3. Save both hash and salt
  4. decrypt with password and salt... so developers cant decrypt password
public class CryptographyProcessor
{
    public string CreateSalt(int size)
    {
        //Generate a cryptographic random number.
          RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
         byte[] buff = new byte[size];
         rng.GetBytes(buff);
         return Convert.ToBase64String(buff);
    }


      public string GenerateHash(string input, string salt)
      { 
         byte[] bytes = Encoding.UTF8.GetBytes(input + salt);
         SHA256Managed sHA256ManagedString = new SHA256Managed();
         byte[] hash = sHA256ManagedString.ComputeHash(bytes);
         return Convert.ToBase64String(hash);
      }

      public bool AreEqual(string plainTextInput, string hashedInput, string salt)
      {
           string newHashedPin = GenerateHash(plainTextInput, salt);
           return newHashedPin.Equals(hashedInput); 
      }
 }

Delete all duplicate rows Excel vba

There's a RemoveDuplicates method that you could use:

Sub DeleteRows()

    With ActiveSheet
        Set Rng = Range("A1", Range("B1").End(xlDown))
        Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
    End With

End Sub

Linq: GroupBy, Sum and Count

I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany to look at each item in each group.

I think you just want:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

The use of First() here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.

I'd also suggest that you should change the Quantity and Price properties to be int and decimal types respectively - why use a string property for data which is clearly not textual?

How to download all files (but not HTML) from a website using wget?

To filter for specific file extensions:

wget -A pdf,jpg -m -p -E -k -K -np http://site/path/

Or, if you prefer long option names:

wget --accept pdf,jpg --mirror --page-requisites --adjust-extension --convert-links --backup-converted --no-parent http://site/path/

This will mirror the site, but the files without jpg or pdf extension will be automatically removed.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Perhaps something like this for the first problem, you can simply access the columns by their names:

>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
          b         e
1  0.071146  0.132145
2  0.495152  0.420219

For the second problem:

>>> df[df['c']>.5][['b','e']].values
array([[ 0.07114556,  0.13214495],
       [ 0.49515157,  0.42021946]])

Uncaught ReferenceError: $ is not defined error in jQuery

Change the order you're including your scripts (jQuery first):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
    src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>

Meaning of *& and **& in C++

*& signifies the receiving the pointer by reference. It means it is an alias for the passing parameter. So, it affects the passing parameter.

#include <iostream>
using namespace std;

void foo(int *ptr)
{
    ptr = new int(50);    // Modifying the pointer to point to a different location
    cout << "In foo:\t" << *ptr << "\n"; 
    delete ptr ;
}

void bar(int *& ptr)
{
    ptr = new int(80);    // Modifying the pointer to point to a different location
    cout << "In bar:\t" << *ptr << "\n"; 
    // Deleting the pointer will result the actual passed parameter dangling
}
int main()
{
    int temp = 100 ;
    int *p = &temp ;

    cout << "Before foo:\t" << *p << "\n";
    foo(p) ;
    cout << "After foo:\t" << *p << "\n";

    cout << "Before bar:\t" << *p << "\n";
    bar(p) ;
    cout << "After bar:\t" << *p << "\n";

    delete p;

    return 0;
}

Output:

Before foo: 100
In foo: 50
After foo:  100
Before bar: 100
In bar: 80
After bar:  80

How to remove from a map while iterating it?

I personally prefer this pattern which is slightly clearer and simpler, at the expense of an extra variable:

for (auto it = m.cbegin(), next_it = it; it != m.cend(); it = next_it)
{
  ++next_it;
  if (must_delete)
  {
    m.erase(it);
  }
}

Advantages of this approach:

  • the for loop incrementor makes sense as an incrementor;
  • the erase operation is a simple erase, rather than being mixed in with increment logic;
  • after the first line of the loop body, the meaning of it and next_it remain fixed throughout the iteration, allowing you to easily add additional statements referring to them without headscratching over whether they will work as intended (except of course that you cannot use it after erasing it).

Android fastboot waiting for devices

try to use compiler generated fastboot when this happes. the file path is out/host/linux(or other)/bin/fastboot and sudo is also needed. it works in most of the time.

Can I use a binary literal in C or C++?

Just use the standard library in C++:

#include <bitset>

You need a variable of type std::bitset:

std::bitset<8ul> x;
x = std::bitset<8>(10);
for (int i = x.size() - 1; i >= 0; i--) {
      std::cout << x[i];
}

In this example, I stored the binary form of 10 in x.

8ul defines the size of your bits, so 7ul means seven bits and so on.

Truncate with condition

You can simply export the table with a query clause using datapump and import it back with table_exists_action=replace clause. Its will drop and recreate your table and take very less time. Please read about it before implementing.

Swift how to sort array of custom objects by property value

Swift 3

people = people.sorted(by: { $0.email > $1.email })

customize Android Facebook Login button

  1. Create custom facebook button and change visability on native facebook button:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    
        <Button
                android:id="@+id/facebookView"
                android:layout_width="300dp"
                android:layout_height="48dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="12dp"
                android:background="@drawable/btn_frame"
                android:gravity="center"
                android:text="@string/Sign_in_facebook_button"
                android:textColor="@color/colorAccent" />
    
        <com.facebook.login.widget.LoginButton
                android:id="@+id/facebookButton"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="invisible"
                android:layout_marginBottom="12dp" />
    
     </LinearLayout>
    
  2. Add listener to your fake button and simulate click:

    facebookView.setOnClickListener(this);
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.facebookView){
           facebookButton.performClick();
        }
    }
    

Initializing a dictionary in python with a key value and no corresponding values

Use the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don't have a default value in mind.

empty_dict = dict.fromkeys(['apple','ball'])

this will initialize empty_dict as:

empty_dict = {'apple': None, 'ball': None}

As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:

default_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)

How can I rename column in laravel using migration?

Follow these steps, respectively for rename column migration file.

1- Is there Doctrine/dbal library in your project. If you don't have run the command first

composer require doctrine/dbal

2- create update migration file for update old migration file. Warning (need to have the same name)

php artisan make:migration update_oldFileName_table

for example my old migration file name: create_users_table update file name should : update_users_table

3- update_oldNameFile_table.php

Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});

'from' my old column name and 'to' my new column name

4- Finally run the migrate command

php artisan migrate

Source link: laravel document

How do you normalize a file path in Bash?

if you're wanting to chomp part of a filename from the path, "dirname" and "basename" are your friends, and "realpath" is handy too.

dirname /foo/bar/baz 
# /foo/bar 
basename /foo/bar/baz
# baz
dirname $( dirname  /foo/bar/baz  ) 
# /foo 
realpath ../foo
# ../foo: No such file or directory
realpath /tmp/../tmp/../tmp
# /tmp

realpath alternatives

If realpath is not supported by your shell, you can try

readlink -f /path/here/.. 

Also

readlink -m /path/there/../../ 

Works the same as

realpath -s /path/here/../../

in that the path doesn't need to exist to be normalized.

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

Tool to convert java to c# code

Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.

creating an array of structs in c++

You can't use an initialization-list for a struct after it's been initialized. You've already default-initialized the two Customer structs when you declared the array customerRecords. Therefore you're going to have either use member-access syntax to set the value of the non-static data members, initialize the structs using a list of initialization lists when you declare the array itself, or you can create a constructor for your struct and use the default operator= member function to initialize the array members.

So either of the following could work:

Customer customerRecords[2];
customerRecords[0].uid = 25;
customerRecords[0].name = "Bob Jones";
customerRecords[1].uid = 25;
customerRecords[1].namem = "Jim Smith";

Or if you defined a constructor for your struct like:

Customer::Customer(int id, string input_name): uid(id), name(input_name) {}

You could then do:

Customer customerRecords[2];
customerRecords[0] = Customer(25, "Bob Jones");
customerRecords[1] = Customer(26, "Jim Smith");

Or you could do the sequence of initialization lists that Tuomas used in his answer. The reason his initialization-list syntax works is because you're actually initializing the Customer structs at the time of the declaration of the array, rather than allowing the structs to be default-initialized which takes place whenever you declare an aggregate data-structure like an array.

How can I reverse the order of lines in a file?

sort -r < filename

or

rev < filename

Table column sizing

As of Alpha 6 you can create the following sass file:

@each $breakpoint in map-keys($grid-breakpoints) {
  $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

  col, td, th {
    @for $i from 1 through $grid-columns {
        &.col#{$infix}-#{$i} {
          flex: none;
          position: initial;
        }
    }

    @include media-breakpoint-up($breakpoint, $grid-breakpoints) {
      @for $i from 1 through $grid-columns {
        &.col#{$infix}-#{$i} {
          width: 100% / $grid-columns * $i;
        }
      }
    }
  }
}

How to align the text middle of BUTTON

This is more predictable then "line-height"

_x000D_
_x000D_
.loginBtn {_x000D_
    background:url(images/loginBtn-center.jpg) repeat-x;_x000D_
    width:175px;_x000D_
    height:65px;_x000D_
    margin:20px auto;_x000D_
    border-radius:10px;_x000D_
    -webkit-border-radius:10px;_x000D_
    box-shadow:0 1px 2px #5e5d5b;_x000D_
}_x000D_
_x000D_
.loginBtn span {_x000D_
    display: block;_x000D_
    padding-top: 22px;_x000D_
    text-align: center;_x000D_
    line-height: 1em;_x000D_
}
_x000D_
<div id="loginBtn" class="loginBtn"><span>Log in</span></div>
_x000D_
_x000D_
_x000D_

EDIT (2018): use flexbox

.loginBtn {
    display: flex;
    align-items: center;
    justify-content: center;
}

Moving Git repository content to another repository preserving history

I think the commands you are looking for are:

cd repo2
git checkout master
git remote add r1remote **url-of-repo1**
git fetch r1remote
git merge r1remote/master --allow-unrelated-histories
git remote rm r1remote

After that repo2/master will contain everything from repo2/master and repo1/master, and will also have the history of both of them.

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

Vertical align in bootstrap table

SCSS

.table-vcenter {
    td,
    th {
        vertical-align: middle;
    }
}

use

<table class="table table-vcenter">
</table>

How to force 'cp' to overwrite directory instead of creating another one inside?

Very similar to @Jonathan Wheeler:

If you do not want to remember, but not rewrite bar:

rm -r bar/
cp -r foo/ !$

!$ displays the last argument of your previous command.

How to display a list inline using Twitter's Bootstrap

I couldn't find anything specific within the bootstrap.css file. So, I added the css to a custom css file.

.inline li {
    display: inline;
}

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

The query either returned no rows or is erroneus, thus FALSE is returned. Change it to

if (!$dbc || mysqli_num_rows($dbc) == 0)

mysqli_num_rows:

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

Convert .pfx to .cer

PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).

If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.

openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts

The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.

You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:

openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

How to filter empty or NULL names in a QuerySet?

You could do this:

Name.objects.exclude(alias__isnull=True)

If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')

Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias is either null or an empty string, so you get all Name objects that have a not-null, not-empty alias field. The generated SQL would look something like:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

You can also pass multiple arguments to a single call to exclude, which would ensure that only objects that meet every condition get excluded:

Name.objects.exclude(some_field=True, other_field=True)

Here, rows in which some_field and other_field are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

Alternatively, if your logic is more complex than that, you could use Django's Q objects:

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

For more info see this page and this page in the Django docs.

As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.

Excel VBA Password via Hex Editor

New version, now you also have the GC= try to replace both DPB and GC with those

DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"

password will be "test"

Excel compare two columns and highlight duplicates

The easiest way to do it, at least for me, is:

Conditional format-> Add new rule->Set your own formula:

=ISNA(MATCH(A2;$B:$B;0))

Where A2 is the first element in column A to be compared and B is the column where A's element will be searched.

Once you have set the formula and picked the format, apply this rule to all elements in the column.

Hope this helps

Connecting to TCP Socket from browser using javascript

See jsocket. Haven't used it myself. Been more than 3 years since last update (as of 26/6/2014).

* Uses flash :(

From the documentation:

<script type='text/javascript'>
    // Host we are connecting to
    var host = 'localhost'; 
    // Port we are connecting on
    var port = 3000;

    var socket = new jSocket();

    // When the socket is added the to document 
    socket.onReady = function(){
            socket.connect(host, port);             
    }

    // Connection attempt finished
    socket.onConnect = function(success, msg){
            if(success){
                    // Send something to the socket
                    socket.write('Hello world');            
            }else{
                    alert('Connection to the server could not be estabilished: ' + msg);            
            }       
    }
    socket.onData = function(data){
            alert('Received from socket: '+data);   
    }

    // Setup our socket in the div with the id="socket"
    socket.setup('mySocket');       
</script>

Android: how to refresh ListView contents?

Another easy way:

//In your ListViewActivity:
public void refreshListView() {
    listAdapter = new ListAdapter(this);
    setListAdapter(listAdapter);
}

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

Rails select helper - Default selected value, how?

I've found solution and I found that I'm pretty unexperienced in RoR.

Inside the controller that manages view described above add this:

@work.project_id = params[:pid] unless params[:pid].nil?

Testing two JSON objects for equality ignoring child order in Java

You can use zjsonpatch library, which presents the diff information in accordance with RFC 6902 (JSON Patch). Its very easy to use. Please visit its description page for its usage

Drop all data in a pandas dataframe

This code make clean dataframe:

df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
#clean
df = pd.DataFrame()

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

git still shows files as modified after adding to .gitignore

Simply add git rm -r --cached <folder_name/file_name>

Sometimes, you update the .gitignore file after the commit command of files. So, the files get cached in the memory. To remove the cached files, use the above command.

Pushing empty commits to remote

Is there any disadvantages/consequences of pushing empty commits?

Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.

You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f back to remote.

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

Test if something is not undefined in JavaScript

You must first check whether response[0] is undefined, and only if it's not, check for the rest. That means that in your case, response[0] is undefined.

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

How to programmatically set the Image source

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

URL string format for connecting to Oracle database with JDBC

if you are using oracle 10g expree Edition then:
1. for loading class use DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); 2. for connecting to database use Connection conn = DriverManager.getConnection("jdbc:oracle:thin:username/password@localhost:1521:xe");

Oracle SQL, concatenate multiple columns + add text

Below query works for me @Oracle 10G ----

select PHONE, CONTACT, (ADDR1 ||  '-' || ADDR2 || '-' || ADDR3) as Address
from CUSTOMER_DETAILS
where Code='341'; 

O/P -

1111 [email protected] 4th street-capetown-sa

How to get value in the session in jQuery

Assuming you are using this plugin, you are misusing the .set method. .set must be passed the name of the key as a string as well as the value. I suppose you meant to write:

$.session.set("userName", $("#uname").val());

This sets the userName key in session storage to the value of the input, and allows you to retrieve it using:

$.session.get('userName');

How to check currently internet connection is available or not in android

package com.base64;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import android.widget.Toast;

import com.androidquery.AQuery;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(isConnectingToInternet(MainActivity.this))
        {
            Toast.makeText(getApplicationContext(),"internet is available",Toast.LENGTH_LONG).show();
        }
        else {
            System.out.print("internet is not available");
        }
    }

    public static boolean isConnectingToInternet(Context context)
    {
        ConnectivityManager connectivity =
                (ConnectivityManager) context.getSystemService(
                        Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
        }
        return false;
    }
}

/*  manifest */

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.base64">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Iterating over all the keys of a map

Is there a way to get a list of all the keys in a Go language map?

ks := reflect.ValueOf(m).MapKeys()

how do I iterate over all the keys?

Use the accepted answer:

for k, _ := range m { ... }

Copy mysql database from remote server to local computer

C:\Users\>mysqldump -u root -p -h ip address --databases database_name -r sql_file.sql
Enter password: your_password

rebase in progress. Cannot commit. How to proceed or stop (abort)?

Another option to ABORT / SKIP / CONTINUE from IDE

VCS > Git > Abort Rebasing

enter image description here

How to fix committing to the wrong Git branch?

To elaborate on this answer, in case you have multiple commits to move from, e.g. develop to new_branch:

git checkout develop # You're probably there already
git reflog # Find LAST_GOOD, FIRST_NEW, LAST_NEW hashes
git checkout new_branch
git cherry-pick FIRST_NEW^..LAST_NEW # ^.. includes FIRST_NEW
git reflog # Confirm that your commits are safely home in their new branch!
git checkout develop
git reset --hard LAST_GOOD # develop is now back where it started

How to remove package using Angular CLI?

It's an open issue #900 on GitHub, unfortunately at this point of time it looks that in Angular CLI there's nothing like ng remove/rm/..., only using npm uninstall DEPENDENCY is the current workaround.

Can I convert a C# string value to an escaped string literal

public static class StringHelpers
{
    private static Dictionary<string, string> escapeMapping = new Dictionary<string, string>()
    {
        {"\"", @"\\\"""},
        {"\\\\", @"\\"},
        {"\a", @"\a"},
        {"\b", @"\b"},
        {"\f", @"\f"},
        {"\n", @"\n"},
        {"\r", @"\r"},
        {"\t", @"\t"},
        {"\v", @"\v"},
        {"\0", @"\0"},
    };

    private static Regex escapeRegex = new Regex(string.Join("|", escapeMapping.Keys.ToArray()));

    public static string Escape(this string s)
    {
        return escapeRegex.Replace(s, EscapeMatchEval);
    }

    private static string EscapeMatchEval(Match m)
    {
        if (escapeMapping.ContainsKey(m.Value))
        {
            return escapeMapping[m.Value];
        }
        return escapeMapping[Regex.Escape(m.Value)];
    }
}

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

You might be able to get them like this:

def thr = Thread.currentThread()
def build = thr?.executable
def envVarsMap = build.parent.builds[0].properties.get("envVars")

How can you have SharePoint Link Lists default to opening in a new window?

The same instance for SP2010; the Links List webpart will not automatically open in a new window, rather user must manually rt click Link object and select Open in New Window.

The add/ insert Link option withkin SP2010 will allow a user to manually configure the link to open in a new window.

Maybe SP2012 release will adrress this...

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

As @borayeris said,

yum install glibc.i686

But if you cannot find glibc.i686 or libstdc++ package, try -

sudo yum search glibc
sudo yum search libstd

and then,

sudo yum install {package}

How to create helper file full of functions in react native?

i prefer to create folder his name is Utils and inside create page index that contain what that think you helper by

const findByAttr = (component,attr) => {
    const wrapper=component.find(`[data-test='${attr}']`);
    return wrapper;
}

const FUNCTION_NAME = (component,attr) => {
    const wrapper=component.find(`[data-test='${attr}']`);
    return wrapper;
}

export {findByAttr, FUNCTION_NAME}

When you need to use this it should be imported as use "{}" because you did not use the default keyword look

 import {FUNCTION_NAME,findByAttr} from'.whare file is store/utils/index'

Elasticsearch difference between MUST and SHOULD bool query

Since this is a popular question, I would like to add that in Elasticsearch version 2 things changed a bit.

Instead of filtered query, one should use bool query in the top level.

If you don't care about the score of must parts, then put those parts into filter key. No scoring means faster search. Also, Elasticsearch will automatically figure out, whether to cache them, etc. must_not is equally valid for caching.

Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

Also, mind that "gte": "now" cannot be cached, because of millisecond granularity. Use two ranges in a must clause: one with now/1h and another with now so that the first can be cached for a while and the second for precise filtering accelerated on a smaller result set.

Client to send SOAP request and receive response

As an alternative, and pretty close to debiasej approach. Since a SOAP request is just a HTTP request, you can simply perform a GET or POST using with HTTP client, but it's not mandatory to build SOAP envelope.

Something like this:

using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace HGF.Infraestructure.Communications
{
    public class SOAPSample
    {
        private readonly IHttpClientFactory _clientFactory;
        private readonly ILogger<DocumentProvider> _logger;

        public SOAPSample(ILogger<DocumentProvider> logger,
                          IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
            _logger = logger;
        }

        public async Task<string> UsingGet(int value1, int value2)
        {
            try
            {
                var client = _clientFactory.CreateClient();
                var response = await client.GetAsync($"https://hostname.com/webservice.asmx/SampleMethod?value1={value1}&value2={value2}", HttpCompletionOption.ResponseHeadersRead);

                //NULL check, HTTP Status Check....

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Oops! Something went wrong");
                return ex.Message;
            }
        }


        public async Task<string> UsingPost(int value1, int value2)
        {
            try
            {
                var content = new StringContent($"value1={value1}&value2={value2}", Encoding.UTF8, "application/x-www-form-urlencoded");

                var client = _clientFactory.CreateClient();
                var response = await client.PostAsync("https://hostname.com/webservice.asmx/SampleMethod", content);

                //NULL check, HTTP Status Check....

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Oops! Something went wrong");
                return ex.Message;
            }
        }
    }
}

Of course, it depends on your scenario. If the payload is too complex, then this won't work

Force overwrite of local file with what's in origin repo?

Simplest version, assuming you're working on the same branch that the file you want is on:

git checkout path/to/file.

I do this so often that I've got an alias set to gc='git checkout'.

Current date and time as string

Since C++11 you could use std::put_time from iomanip header:

#include <iostream>
#include <iomanip>
#include <ctime>

int main()
{
    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);
    std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}

std::put_time is a stream manipulator, therefore it could be used together with std::ostringstream in order to convert the date to a string:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>

int main()
{
    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);

    std::ostringstream oss;
    oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S");
    auto str = oss.str();

    std::cout << str << std::endl;
}

How to upload and parse a CSV file in php

You want the handling file uploads section of the PHP manual, and you would also do well to look at fgetcsv() and explode().

Replace non-numeric with empty string

Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:

phoneNumber  = Regex.Replace(phoneNumber, "\\D", String.Empty);

Making a POST call instead of GET using urllib2

Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age'  : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()

As suggested by @Michael Kent do consider requests, it's great.

EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.

How can I view live MySQL queries?

Even though an answer has already been accepted, I would like to present what might even be the simplest option:

$ mysqladmin -u bob -p -i 1 processlist

This will print the current queries on your screen every second.

  • -u The mysql user you want to execute the command as
  • -p Prompt for your password (so you don't have to save it in a file or have the command appear in your command history)
  • i The interval in seconds.
  • Use the --verbose flag to show the full process list, displaying the entire query for each process. (Thanks, nmat)

There is a possible downside: fast queries might not show up if they run between the interval that you set up. IE: My interval is set at one second and if there is a query that takes .02 seconds to run and is ran between intervals, you won't see it.

Use this option preferably when you quickly want to check on running queries without having to set up a listener or anything else.

How to check if mysql database exists

A simple way to check if a database exists is:

SHOW DATABASES LIKE 'dbname';

If database with the name 'dbname' doesn't exist, you get an empty set. If it does exist, you get one row.

Java: Static vs inner class

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

How to set specific Java version to Maven

I've used the base idea from @Jonathan. I've set the windows with: set JAVA_HOME=C:\Program Files\java\AdoptOpenJDK-11.0.8+10 call mvn clean package -DskipTests

Calculating bits required to store decimal number

Ok to generalize the technique of how many bits you need to represent a number is done this way. You have R symbols for a representation and you want to know how many bits, solve this equation R=2^n or log2(R)=n. Where n is the numbers of bits and R is the number of symbols for the representation.

For the decimal number system R=9 so we solve 9=2^n, the answer is 3.17 bits per decimal digit. Thus a 3 digit number will need 9.51 bits or 10. A 1000 digit number needs 3170 bits

Ubuntu: Using curl to download an image

For ones who got permission denied for saving operation, here is the command that worked for me:

$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png --output py.png

Switch: Multiple values in one case?

You can use ifelse instead.but if you want to know how to use switch in this case.here is an example.

int age = Convert.ToInt32(txtBoxAge.Text);`
int flag;
if(age >= 1 && age <= 8) {
flag = 1;
} else if (age >= 9 && age <= 15) {
 flag = 2;
} else if (age >= 16 && age <= 100) {
 flag = 3;
} else {
 flag = 4;   
}
switch (flag) 

{
 case 1:
  MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 2:
  MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
case 3:
  MessageBox.Show("You are " + age + " years old\n Perfect.");
break;
default:
  MessageBox.Show("You an old person.");
break;
}

hope that helps ! :)

Switching from zsh to bash on OSX, and back again?

zsh has a builtin command emulate which can emulate different shells by setting the appropriate options, although csh will never be fully emulated.

emulate bash
perform commands
emulate -R zsh

The -R flag restores all the options to their default values for that shell.

See: zsh manual

How can I load webpage content into a div on page load?

Take a look into jQuery's .load() function:

<script>
    $(function(){
        $('#siteloader').load('http://www.somesitehere.com');
    });
</script>

However, this only works on the same domain of the JS file.

Remove trailing spaces automatically or with a shortcut

Visual Studio Code, menu FilePreferenceSettings → search for "trim":

Visual Studio Code screenshot

R dates "origin" must be supplied

My R use 1970-01-01:

>as.Date(15103, origin="1970-01-01")
[1] "2011-05-09"

and this matches the calculation from

>as.numeric(as.Date(15103, origin="1970-01-01"))

Get checkbox value in jQuery

The best way of retrieving a checkbox's value is as following

if ( elem.checked ) 
if ( $( elem ).prop( "checked" ) ) 
if ( $( elem ).is( ":checked" ) ) 

as explained in the official documentations in jQuery's website. The rest of the methods has nothing to do with the property of the checkbox, they are checking the attribute which means they are testing the initial state of the checkbox when it was loaded. So in short:

  • When you have the element and you know it is a checkbox you can simply read its property and you won't need jQuery for that (i.e. elem.checked) or you can use $(elem).prop("checked") if you want to rely on jQuery.
  • If you need to know (or compare) the value when the element was first loaded (i.e. the default value) the correct way to do it is elem.getAttribute("checked") or elem.prop("defaultChecked").

Please note that elem.attr("checked") is modified only after version 1.6.1+ of jQuery to return the same result as elem.prop("checked").

Some answers are misleading or imprecise, Please check below yourself:

http://api.jquery.com/prop/

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

I have changed the length of value from varchar(255) to varchar(25) to all varchar columns and i get the solution.

Remove new lines from string and replace with one empty space

This one also removes tabs

$string = preg_replace('~[\r\n\t]+~', '', $text);

How to get all selected values of a multiple select box?

suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:

//show all selected options in the console:

for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
  console.log( multiSelect.selectedOptions[i].value);
}

Update index after sorting data-frame

You can reset the index using reset_index to get back a default index of 0, 1, 2, ..., n-1 (and use drop=True to indicate you want to drop the existing index instead of adding it as an additional column to your dataframe):

In [19]: df2 = df2.reset_index(drop=True)

In [20]: df2
Out[20]:
   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

How to manually include external aar package using new Gradle Android Build System

If you use Gradle Kotlin DSL, you need to add a file in your module directory.

For example: libs/someAndroidArchive.aar

After just write this in your module build.gradle.kts in the dependency block:

implementation(files("libs/someAndroidArchive.aar"))

How to parse a CSV in a Bash script?

See this youtube video: BASH scripting lesson 10 working with CSV files

CSV file:

Bob Brown;Manager;16581;Main
Sally Seaforth;Director;4678;HOME

Bash script:

#!/bin/bash
OLDIFS=$IFS
IFS=";"
while read user job uid location
 do

    echo -e "$user \
    ======================\n\
    Role :\t $job\n\
    ID :\t $uid\n\
    SITE :\t $location\n"
 done < $1
 IFS=$OLDIFS

Output:

Bob Brown     ======================
    Role :   Manager
    ID :     16581
    SITE :   Main

Sally Seaforth     ======================
    Role :   Director
    ID :     4678
    SITE :   HOME

Image, saved to sdcard, doesn't appear in Android's Gallery app

You can also add an Image to the Media Gallery by intent, have a look at the example code to see how it is done:

ContentValues image = new ContentValues();

image.put(Images.Media.TITLE, imageTitle);
image.put(Images.Media.DISPLAY_NAME, imageDisplayName);
image.put(Images.Media.DESCRIPTION, imageDescription);
image.put(Images.Media.DATE_ADDED, dateTaken);
image.put(Images.Media.DATE_TAKEN, dateTaken);
image.put(Images.Media.DATE_MODIFIED, dateTaken);
image.put(Images.Media.MIME_TYPE, "image/png");
image.put(Images.Media.ORIENTATION, 0);

 File parent = imageFile.getParentFile();
 String path = parent.toString().toLowerCase();
 String name = parent.getName().toLowerCase();
 image.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
 image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
 image.put(Images.Media.SIZE, imageFile.length());

 image.put(Images.Media.DATA, imageFile.getAbsolutePath());

 Uri result = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Best way to check for nullable bool in a condition expression (if ...)

If you want to treat a null as false, then I would say that the most succinct way to do that is to use the null coalesce operator (??), as you describe:

if (nullableBool ?? false) { ... }

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

Laravel Eloquent - distinct() and count() not working properly together

I came across the same problem.

If you install laravel debug bar you can see the queries and often see the problem

$ad->getcodes()->groupby('pid')->distinct()->count()

change to

$ad->getcodes()->distinct()->select('pid')->count()

You need to set the values to return as distinct. If you don't set the select fields it will return all the columns in the database and all will be unique. So set the query to distinct and only select the columns that make up your 'distinct' value you might want to add more. ->select('pid','date') to get all the unique values for a user in a day

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

This usually happens to me when I forget to change the company to match mine.

  1. Select the target under Groups & Files
  2. Click the Get Info button
  3. Choose the Properties tab
  4. Under Identifier, make sure it says com.YOURREALCOMPANYNAME.APPNAME

When you create a new app, it usually says, "com.yourcompany". Change it to whatever you registered with, in my case com.DavidKanarek

Display label text with line breaks in c#

You can use <br /> for Line Breaks, and &nbsp; for white space.

string s = "First line <br /> Second line";

Output:

First line
Second line

For more info refer to this: Line break in Label

How to determine when Fragment becomes visible in ViewPager

I support SectionsPagerAdapter with child fragments so after a lot of headache I finally got working version based on solutions from this topic:

public abstract class BaseFragment extends Fragment {

    private boolean visible;
    private boolean visibilityHintChanged;

    /**
     * Called when the visibility of the fragment changed
     */
    protected void onVisibilityChanged(View view, boolean visible) {

    }

    private void triggerVisibilityChangedIfNeeded(boolean visible) {
        if (this.visible == visible || getActivity() == null || getView() == null) {
            return;
        }
        this.visible = visible;
        onVisibilityChanged(getView(), visible);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!visibilityHintChanged) {
            setUserVisibleHint(false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint() && !isHidden()) {
            triggerVisibilityChangedIfNeeded(true);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        triggerVisibilityChangedIfNeeded(!hidden);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        visibilityHintChanged = true;
        if (isVisibleToUser && isResumed() && !isHidden()) {
            triggerVisibilityChangedIfNeeded(true);
        } else if (!isVisibleToUser) {
            triggerVisibilityChangedIfNeeded(false);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        triggerVisibilityChangedIfNeeded(false);
    }

    @Override
    public void onStop() {
        super.onStop();
        triggerVisibilityChangedIfNeeded(false);
    }

    protected boolean isReallyVisible() {
        return visible;
    }
}

How do I wait until Task is finished in C#?

async Task<int> AccessTheWebAsync()  
{   
    // You need to add a reference to System.Net.Http to declare client.  
    HttpClient client = new HttpClient();  

    // GetStringAsync returns a Task<string>. That means that when you await the  
    // task you'll get a string (urlContents).  
    Task<string> getStringTask = 

    client.GetStringAsync("http://msdn.microsoft.com");  

    // You can do work here that doesn't rely on the string from GetStringAsync.  
    DoIndependentWork();  

    // The await operator suspends AccessTheWebAsync.  
    //  - AccessTheWebAsync can't continue until getStringTask is complete.  
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.  
    //  - Control resumes here when getStringTask is complete.   
    //  - The await operator then retrieves the string result from 
    getStringTask.  
    string urlContents = await getStringTask;  

    // The return statement specifies an integer result.  
    // Any methods that are awaiting AccessTheWebenter code hereAsync retrieve the length 
    value.  
    return urlContents.Length;  
}  

Change the encoding of a file in Visual Studio Code

Apart from the settings explained in the answer by @DarkNeuron:

"files.encoding": "any encoding"

you can also specify settings for a specific language like so:

"[language id]": {
  "files.encoding": "any encoding"
}

For example, I use this when I need to edit PowerShell files previously created with ISE (which are created in ANSI format):

"[powershell]": {
    "files.encoding": "windows1252"
}

You can get a list of identifiers of well-known languages here.

What is (x & 1) and (x >>= 1)?

It is similar to x = (x >> 1).

(operand1)(operator)=(operand2)  implies(=>)  (operand1)=(operand1)(operator)(operand2) 

It shifts the binary value of x by one to the right.

E.g.

int x=3;    // binary form (011) 
x = x >> 1; // zero shifted in from the left, 1 shifted out to the right:
            // x=1, binary form (001)

Returning unique_ptr from functions

This is in no way specific to std::unique_ptr, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.

If you had a function that accepts std::unique_ptr as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar().

void bar(std::unique_ptr<int> p)
{
    // ...
}

int main()
{
    unique_ptr<int> p = foo();
    bar(p); // error, can't implicitly invoke move constructor on lvalue
    bar(std::move(p)); // OK but don't use p afterwards
    return 0;
}

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

It's in the app.config file.

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceDebug includeExceptionDetailInFaults="true"/>

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

Make a phone call programmatically

To go back to original app you can use telprompt:// instead of tel:// - The tell prompt will prompt the user first, but when the call is finished it will go back to your app:

NSString *phoneNumber = [@"telprompt://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];

How to search and replace text in a file?

As pointed out by michaelb958, you cannot replace in place with data of a different length because this will put the rest of the sections out of place. I disagree with the other posters suggesting you read from one file and write to another. Instead, I would read the file into memory, fix the data up, and then write it out to the same file in a separate step.

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

Unless you've got a massive file to work with which is too big to load into memory in one go, or you are concerned about potential data loss if the process is interrupted during the second step in which you write data to the file.

How to completely uninstall python 2.7.13 on Ubuntu 16.04

Sometimes you need to first update the apt repo list.

sudo apt-get update
sudo apt purge python2.7-minimal

Parsing time string in Python

In [117]: datetime.datetime.strptime?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in method strptime of type object at 0x9a2520>
Namespace:      Interactive
Docstring:
    string, format -> new datetime parsed from a string (like time.strptime()).

How to use C++ in Go

The problem here is that a compliant implementation does not need to put your classes in a compile .cpp file. If the compiler can optimize out the existence of a class, so long as the program behaves the same way without it, then it can be omitted from the output executable.

C has a standardized binary interface. Therefore you'll be able to know that your functions are exported. But C++ has no such standard behind it.

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

Motivation

If you want to solve the general-case problem, and you can store and edit the array, then Caf's solution is by far the most efficient. If you can't store the array (streaming version), then sdcvvc's answer is the only type of solution currently suggested.

The solution I propose is the most efficient answer (so far on this thread) if you can store the problem but can't edit it, and I got the idea from Svalorzen's solution, which solves for 1 or 2 missing items. This solution takes T(k*n) time and O(k) and O(log(k)) space - with a possibility that it might actually be O(min(k,log(n))) space. It also works well with parallelism.

Concept

The idea is that if you use the original approach of comparing sums:
int sum = SumOf(1,n) - SumOf(array)

... then you take the average of the missing numbers:
average = sum/array_size

... which provides a boundary: Of the missing numbers, there's guaranteed to be at least one number less-or-equal to average, and at least one number greater than average. This means that we can split into sub problems that each scan the array [O(n)] and are only concerned with their respective sub-arrays.

Code

C-style solution (don't judge me for the global variables, I'm just trying to make the code readable for non-c folks):

#include "stdio.h"

// Example problem:
const int array [] = {0, 7, 3, 1, 5};
const int N = 8; // size of original array
const int array_size = 5;

int SumOneTo (int n)
{
    return n*(n-1)/2; // non-inclusive
}

int MissingItems (const int begin, const int end, int & average)
{
    // We consider only sub-array where elements, e:
    // begin <= e < end
    
    // Initialise info about missing elements.
    // First assume all are missing:
    int n = end - begin;
    int sum = SumOneTo(end) - SumOneTo(begin);

    // Minus everything that we see (ie not missing):
    for (int i = 0; i < array_size; ++i)
    {
        if ((begin <= array[i]) && (array[i] < end))
        {
            n -= 1;
            sum -= array[i];
        }
    }
    
    // used by caller:
    average = sum/n;
    return n;
}

void Find (const int begin, const int end)
{
    int average;

    if (MissingItems(begin, end, average) == 1)
    {
        printf(" %d", average); // average(n) is same as n
        return;
    }
    
    Find(begin, average + 1); // at least one missing here
    Find(average + 1, end); // at least one here also
}

int main ()
{   
    printf("Missing items:");
    
    Find(0, N);
    
    printf("\n");
}

Analysis

Ignoring recursion for a moment, each function call clearly takes O(n) time and O(1) space. Note that sum can equal as much as n(n-1)/2, so requires double the amount of bits needed to store n-1. At most this means than we effectively need two extra elements worth of space, regardless of the size of the array or k, hence it's still O(1) space under the normal conventions.

It's not so obvious how many function calls there are for k missing elements, so I'll provide a visual. Your original sub-array (connected array) is the full array, which has all k missing elements in it. We'll imagine them in increasing order, where -- represent connections (part of same sub-array):

m1 -- m2 -- m3 -- m4 -- (...) -- mk-1 -- mk

The effect of the Find function is to disconnect the missing elements into different non-overlapping sub-arrays. It guarantees that there's at least one missing element in each sub-array, which means breaking exactly one connection.

What this means is that regardless of how the splits occur, it will always take k-1 Find function calls to do the work of finding the sub-arrays that have only one missing element in it.

So the time complexity is T((k-1 + k) * n) = T(k*n).

For the space complexity, if we divide proportionally each time then we get O(log(k)) space complexity, but if we only separate one at a time it gives us O(k).

Discussion

I actually suspect we the space complexity is a smaller O(min(k,log(n))), but it's harder to prove. My intuition: Where the average performs badly at separation is when there's an outlier, but because of this the separation then removes that outlier. In normal arrays, elements could all be exponentially different, but in this case they're all bound by n.

Why can't I see the "Report Data" window when creating reports?

please go to

View > Toolbars > Customize

then select "Data" categories then click "Show data source" in command panel

"Data" menu will be seen in menu panel. click to get the website data source

jquery $('.class').each() how many items?

If you're using chained syntax:

$(".class").each(function() {
    // ...
});

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

Usage:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

Google Apps Script to open a URL

Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.

It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers

Deprecated. The UI service was deprecated on December 11, 2014. To create user interfaces, use the HTML service instead.

The example in the HTML Service linked page is pretty simple,

Code.gs

// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Dialog')
      .addItem('Open', 'openDialog')
      .addToUi();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, 'Dialog title');
}

A customized version of index.html to show two hyperlinks

<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>

Difference between return and exit in Bash functions

  • exit terminates the current process; with or without an exit code, consider this a system more than a program function. Note that when sourcing, exit will end the shell. However, when running, it will just exit the script.

  • return from a function go back to the instruction after the call, with or without a return code. return is optional and it's implicit at the end of the function. return can only be used inside a function.

I want to add that while being sourced, it's not easy to exit the script from within a function without killing the shell. I think, an example is better on a 'test' script:

#!/bin/bash
function die(){
   echo ${1:=Something terrible wrong happen}
   #... clean your trash
   exit 1
}

[ -f /whatever/ ] || die "whatever is not available"
# Now we can proceed
echo "continue"

doing the following:

user$ ./test
Whatever is not available
user$

test -and- the shell will close.

user$ . ./test
Whatever is not available

Only test will finish and the prompt will show.

The solution is to enclose the potentially procedure in ( and ):

#!/bin/bash
function die(){
   echo $(1:=Something terrible wrong happen)
   #... Clean your trash
   exit 1
}

( # Added        
    [ -f /whatever/ ] || die "whatever is not available"
    # Now we can proceed
    echo "continue"
) # Added

Now, in both cases only test will exit.

How to select rows that have current day's timestamp?

If you want an index to be used and the query not to do a table scan:

WHERE timestamp >= CURDATE()
  AND timestamp < CURDATE() + INTERVAL 1 DAY

To show the difference that this makes on the actual execution plans, we'll test with an SQL-Fiddle (an extremely helpful site):

CREATE TABLE test                            --- simple table
    ( id INT NOT NULL AUTO_INCREMENT
    ,`timestamp` datetime                    --- index timestamp
    , data VARCHAR(100) NOT NULL 
          DEFAULT 'Sample data'
    , PRIMARY KEY (id)
    , INDEX t_IX (`timestamp`, id)
    ) ;

INSERT INTO test
    (`timestamp`)
VALUES
    ('2013-02-08 00:01:12'),
    ---                                      --- insert about 7k rows
    ('2013-02-08 20:01:12') ;

Lets try the 2 versions now.


Version 1 with DATE(timestamp) = ?

EXPLAIN
SELECT * FROM test 
WHERE DATE(timestamp) = CURDATE()            ---  using DATE(timestamp)
ORDER BY timestamp ;

Explain:

ID  SELECT_TYPE  TABLE  TYPE  POSSIBLE_KEYS  KEY  KEY_LEN  REF 
1   SIMPLE       test   ALL

ROWS  FILTERED  EXTRA
6671  100       Using where; Using filesort

It filters all (6671) rows and then does a filesort (that's not a problem as the returned rows are few)


Version 2 with timestamp <= ? AND timestamp < ?

EXPLAIN
SELECT * FROM test 
WHERE timestamp >= CURDATE()
  AND timestamp < CURDATE() + INTERVAL 1 DAY
ORDER BY timestamp ;

Explain:

ID  SELECT_TYPE  TABLE  TYPE  POSSIBLE_KEYS  KEY  KEY_LEN  REF 
1   SIMPLE       test   range t_IX           t_IX    9 

ROWS  FILTERED  EXTRA
2     100       Using where

It uses a range scan on the index, and then reads only the corresponding rows from the table.

Getting last month's date in php

$time = mktime(0, 0, 0, date("m"),date("d")-date("t"), date("Y"));
$lastMonth = date("d-m-Y", $time);

OR

$lastMonth = date("m-Y", mktime() - 31*3600*24);

works on 30.03.2012

For loop in Objective-C

You mean fast enumeration? You question is very unclear.

A normal for loop would look a bit like this:

unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{ 
   // do loop stuff
   id someObject = [someArray objectAtIndex:i];
}

And a loop with fast enumeration, which is optimized by the compiler, would look like this:

for(id someObject in someArray)
{
   // do stuff with object
}

Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I had this problem because I had a typo in my template near [(ngModel)]]. Extra bracket. Example:

<input id="descr" name="descr" type="text" required class="form-control width-half"
      [ngClass]="{'is-invalid': descr.dirty && !descr.valid}" maxlength="16" [(ngModel)]]="category.descr"
      [disabled]="isDescrReadOnly" #descr="ngModel">

Darkening an image with CSS (In any shape)

if you want only the background-image to be affected, you can use a linear gradient to do that, just like this:

  background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(IMAGE_URL);

If you want it darker, make the alpha value higher, else you want it lighter, make alpha lower

Counting lines, words, and characters within a text file using Python

One of the way I like is this one , but may be good for small files

with open(fileName,'r') as content_file:
    content = content_file.read()
    lineCount = len(re.split("\n",content))
    words = re.split("\W+",content.lower())

To count words, there is two way, if you don't care about repetition you can just do

words_count = len(words)

if you want the counts of each word you can just do

import collections
words_count = collections.Counter(words) #Count the occurrence of each word

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Use strftime in the standard POSIX module. The arguments to strftime in Perl’s binding were designed to align with the return values from localtime and gmtime. Compare

strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)

with

my          ($sec,$min,$hour,$mday,$mon,$year,$wday,     $yday,     $isdst) = gmtime(time);

Example command-line use is

$ perl -MPOSIX -le 'print strftime "%F %T", localtime $^T'

or from a source file as in

use POSIX;

print strftime "%F %T", localtime time;

Some systems do not support the %F and %T shorthands, so you will have to be explicit with

print strftime "%Y-%m-%d %H:%M:%S", localtime time;

or

print strftime "%Y-%m-%d %H:%M:%S", gmtime time;

Note that time returns the current time when called whereas $^T is fixed to the time when your program started. With gmtime, the return value is the current time in GMT. Retrieve time in your local timezone with localtime.

Add a custom attribute to a Laravel / Eloquent model on load?

In my subscription model, I need to know the subscription is paused or not. here is how I did it

public function getIsPausedAttribute() {
    $isPaused = false;
    if (!$this->is_active) {
        $isPaused = true;
    }
}

then in the view template,I can use $subscription->is_paused to get the result.

The getIsPausedAttribute is the format to set a custom attribute,

and uses is_paused to get or use the attribute in your view.

How can I submit a POST form using the <a href="..."> tag?

I use a jQuery script to create "shadow" forms for my POSTable links.

Instead of <a href="/some/action?foo=bar">, I write <a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">. The script makes a hidden form with hidden inputs, and submits it when the link is clicked.

_x000D_
_x000D_
$("a[data-post]")
    .each(function() {
        let href = $(this).data("post"); if (!href) return;
        let $form = $("<form></form>").attr({ method:"POST",action:href }).css("display","none")
        let data = $(this).data()
        for (let dat in data) {
            if (dat.startsWith("postVar")) {
                let varname = dat.substring(7).toLowerCase()  // postVarId -> id
                let varval = data[dat]
                $form.append($("<input/>").attr({ type:"hidden",name:varname,value:varval }))
            }
        }
        $("body").append($form)
        $(this).data("postform",$form)
    })
    .click(function(ev) {
        ev.preventDefault()
        if ($(this).data("postform")) $(this).data("postform").submit(); else console.error("No .postform set in <a data-post>")
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">click me</a>
_x000D_
_x000D_
_x000D_

How to get a view table query (code) in SQL Server 2008 Management Studio

Additionally, if you have restricted access to the database (IE: Can't use "Script Function as > CREATE To"), there is another option to get this query.

Find your View > right click > "Design".

This will give you the query you are looking for.

How to run a program automatically as admin on Windows 7 at startup?

I think the task scheduler would be overkill (imho). There is a startup folder for win7.

C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Just create a shortcut for your autostart Applicaton, edit the properties of the shortcut and have it always run as administrator.

Your kids could close it of course, but if they are tech-savvy they always find a way to keep you out. I know i did when i was younger.

Good luck!

Fill background color left to right CSS

The thing you will need to do here is use a linear gradient as background and animate the background position. In code:

Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.

background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;

On hover, change the background position to right bottom and with transition:all 2s ease;, the position will change gradually (it's nicer with linear tough) background-position:right bottom;

http://jsfiddle.net/75Umu/3/

As for the -vendor-prefix'es, see the comments to your question

extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).

background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;

Demo:

_x000D_
_x000D_
div {
    font: 22px Arial;
    display: inline-block;
    padding: 1em 2em;
    text-align: center;
    color: white;
    background: red; /* default color */

    /* "to left" / "to right" - affects initial color */
    background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
    background-size: 200%;
    transition: .5s ease-out;
}
div:hover {
    background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
_x000D_
_x000D_

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.

Which tool to build a simple web front-end to my database

The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.

PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.

Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.

How to drop rows from pandas data frame that contains a particular string in a particular column?

pandas has vectorized string operations, so you can just filter out the rows that contain the string you don't want:

In [91]: df = pd.DataFrame(dict(A=[5,3,5,6], C=["foo","bar","fooXYZbar", "bat"]))

In [92]: df
Out[92]:
   A          C
0  5        foo
1  3        bar
2  5  fooXYZbar
3  6        bat

In [93]: df[~df.C.str.contains("XYZ")]
Out[93]:
   A    C
0  5  foo
1  3  bar
3  6  bat

Confused about __str__ on list in Python

The thing about classes, and setting unencumbered global variables equal to some value within the class, is that what your global variable stores is actually the reference to the memory location the value is actually stored.

What you're seeing in your output is indicative of this.

Where you might be able to see the value and use print without issue on the initial global variables you used because of the str method and how print works, you won't be able to do this with lists, because what is stored in the elements within that list is just a reference to the memory location of the value -- read up on aliases, if you'd like to know more.

Additionally, when using lists and losing track of what is an alias and what is not, you might find you're changing the value of the original list element, if you change it in an alias list -- because again, when you set a list element equal to a list or element within a list, the new list only stores the reference to the memory location (it doesn't actually create new memory space specific to that new variable). This is where deepcopy comes in handy!

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Performance wise substring(0, 1) is better as found by following:

    String example = "something";
    String firstLetter  = "";

    long l=System.nanoTime();
    firstLetter = String.valueOf(example.charAt(0));
    System.out.println("String.valueOf: "+ (System.nanoTime()-l));

    l=System.nanoTime();
    firstLetter = Character.toString(example.charAt(0));
    System.out.println("Character.toString: "+ (System.nanoTime()-l));

    l=System.nanoTime();
    firstLetter = example.substring(0, 1);
    System.out.println("substring: "+ (System.nanoTime()-l));

Output:

String.valueOf: 38553
Character.toString: 30451
substring: 8660

Formatting Decimal places in R

if you just want to round a number or a list, simply use

round(data, 2)

Then, data will be round to 2 decimal place.

Check whether a string matches a regex in JS

Use test() method :

var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
    console.log("Valid");
} else {
    console.log("Invalid");
}

SQL Server 2005 How Create a Unique Constraint?

Warning: Only one null row can be in the column you've set to be unique.

You can do this with a filtered index in SQL 2008:

CREATE UNIQUE NONCLUSTERED INDEX idx_col1
ON dbo.MyTable(col1)
WHERE col1 IS NOT NULL;

See Field value must be unique unless it is NULL for a range of answers.

Assert equals between 2 Lists in Junit

I don't this the all the above answers are giving the exact solution for comparing two lists of Objects. Most of above approaches can be helpful in following limit of comparisons only - Size comparison - Reference comparison

But if we have same sized lists of objects and different data on the objects level then this comparison approaches won't help.

I think the following approach will work perfectly with overriding equals and hashcode method on the user-defined object.

I used Xstream lib for override equals and hashcode but we can override equals and hashcode by out won logics/comparison too.

Here is the example for your reference

    import com.thoughtworks.xstream.XStream;

    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.List;

    class TestClass {
      private String name;
      private String id;

      public void setName(String value) {
        this.name = value;
      }

      public String getName() {
        return this.name;
      }

      public String getId() {
        return id;
      }

      public void setId(String id) {
        this.id = id;
      }

      /**
       * @see java.lang.Object#equals(java.lang.Object)
       */
      @Override
      public boolean equals(Object o) {
        XStream xstream = new XStream();
        String oxml = xstream.toXML(o);
        String myxml = xstream.toXML(this);

        return myxml.equals(oxml);
      }

      /**
       * @see java.lang.Object#hashCode()
       */
      @Override
      public int hashCode() {
        XStream xstream = new XStream();
        String myxml = xstream.toXML(this);
        return myxml.hashCode();
      }
    }

    public class XstreamCompareTest {
      public static void main(String[] args) throws ParseException {
      checkObjectEquals();
}

      private static void checkObjectEquals() {
        List<TestClass> testList1 = new ArrayList<TestClass>();
        TestClass tObj1 = new TestClass();
        tObj1.setId("test3");
        tObj1.setName("testname3");
        testList1.add(tObj1);

        TestClass tObj2 = new TestClass();
        tObj2.setId("test2");
        tObj2.setName("testname2");
        testList1.add(tObj2);

        testList1.sort((TestClass t1, TestClass t2) -> t1.getId().compareTo(t2.getId()));

        List<TestClass> testList2 = new ArrayList<TestClass>();
        TestClass tObj3 = new TestClass();
        tObj3.setId("test3");
        tObj3.setName("testname3");
        testList2.add(tObj3);

        TestClass tObj4 = new TestClass();
        tObj4.setId("test2");
        tObj4.setName("testname2");
        testList2.add(tObj4);

        testList2.sort((TestClass t1, TestClass t2) -> t1.getId().compareTo(t2.getId()));

        if (isNotMatch(testList1, testList2)) {
          System.out.println("The list are not matched");
        } else {
          System.out.println("The list are matched");
        }

      }

      private static boolean isNotMatch(List<TestClass> clist1, List<TestClass> clist2) {
        return clist1.size() != clist2.size() || !clist1.equals(clist2);
      }
    }

The most important thing is that you can ignore the fields by Annotation (@XStreamOmitField) if you don't want to include any fields on the equal check of Objects. There are many Annotations like this to configure so have a look deep about the annotations of this lib.

I am sure this answer will save your time to identify the correct approach for comparing two lists of objects :). Please comment if you see any issues on this.

Javascript to convert UTC to local time

Try:

var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();

How can I use external JARs in an Android project?

in android studio if using gradle

add this to build.gradle

compile fileTree(dir: 'libs', include: ['*.jar'])

and add the jar file to libs folder

Import Script from a Parent Directory

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

Remove all constraints affecting a UIView

There are two ways of on how to achieve that according to Apple Developer Documentation

1. NSLayoutConstraint.deactivateConstraints

This is a convenience method that provides an easy way to deactivate a set of constraints with one call. The effect of this method is the same as setting the isActive property of each constraint to false. Typically, using this method is more efficient than deactivating each constraint individually.

// Declaration
class func deactivate(_ constraints: [NSLayoutConstraint])

// Usage
NSLayoutConstraint.deactivate(yourView.constraints)

2. UIView.removeConstraints (Deprecated for >= iOS 8.0)

When developing for iOS 8.0 or later, use the NSLayoutConstraint class’s deactivateConstraints: method instead of calling the removeConstraints: method directly. The deactivateConstraints: method automatically removes the constraints from the correct views.

// Declaration
func removeConstraints(_ constraints: [NSLayoutConstraint])`

// Usage
yourView.removeConstraints(yourView.constraints)

Tips

Using Storyboards or XIBs can be such a pain at configuring the constraints as mentioned on your scenario, you have to create IBOutlets for each ones you want to remove. Even so, most of the time Interface Builder creates more trouble than it solves.

Therefore when having very dynamic content and different states of the view, I would suggest:

  1. Creating your views programmatically
  2. Layout them and using NSLayoutAnchor
  3. Append each constraint that might get removed later to an array
  4. Clear them every time before applying the new state

Simple Code

private var customConstraints = [NSLayoutConstraint]()

private func activate(constraints: [NSLayoutConstraint]) {
    customConstraints.append(contentsOf: constraints)
    customConstraints.forEach { $0.isActive = true }
}

private func clearConstraints() {
    customConstraints.forEach { $0.isActive = false }
    customConstraints.removeAll()
}

private func updateViewState() {
    clearConstraints()

    let constraints = [
        view.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
        view.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
        view.topAnchor.constraint(equalTo: parentView.topAnchor),
        view.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
    ]

    activate(constraints: constraints)

    view.layoutIfNeeded()
}

References

  1. NSLayoutConstraint
  2. UIView

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

Merging dictionaries in C#

How about adding a params overload?

Also, you should type them as IDictionary for maximum flexibility.

public static IDictionary<TKey, TValue> Merge<TKey, TValue>(IEnumerable<IDictionary<TKey, TValue>> dictionaries)
{
    // ...
}

public static IDictionary<TKey, TValue> Merge<TKey, TValue>(params IDictionary<TKey, TValue>[] dictionaries)
{
    return Merge((IEnumerable<TKey, TValue>) dictionaries);
}

Create a Date with a set timezone without using a string representation

This may help someone, put UTC at the end of what you pass in to the new constructor

At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")

How do I generate a random number between two variables that I have stored?

To generate a random number between min and max, use:

int randNum = rand()%(max-min + 1) + min;

(Includes max and min)

JavaScript or jQuery browser back button click detector

In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.

if(performance.navigation.type == 2) {
    //Do your code here
}

Docker container not starting (docker start)

You are trying to run bash, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d, but you can do this by adding -it to the command line, which ensures that the container has a valid tty associated with it and that stdin remains connected:

docker run -it -d -p 52022:22 basickarl/docker-git-test

You would more commonly run some sort of long-lived non-interactive process (like sshd, or a web server, or a database server, or a process manager like systemd or supervisor) when starting detached containers.

If you are trying to run a service like sshd, you cannot simply run service ssh start. This will -- depending on the distribution you're running inside your container -- do one of two things:

  • It will try to contact a process manager like systemd or upstart to start the service. Because there is no service manager running, this will fail.

  • It will actually start sshd, but it will be started in the background. This means that (a) the service sshd start command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.

If you want to run just ssh in a container, consider an example like this.

If you want to run sshd and other processes inside the container, you will need to investigate some sort of process supervisor.

How can I programmatically check whether a keyboard is present in iOS app?

Try this function

BOOL UIKeyboardIsVisible(){

BOOL keyboardVisible=NO;
// Locate non-UIWindow.
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
    if (![[testWindow class] isEqual:[UIWindow class]]) {
        keyboardWindow = testWindow;
        break;
    }
}
// Locate UIKeyboard.
for (UIView *possibleKeyboard in [keyboardWindow subviews]) {
    // iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.
    if ([[possibleKeyboard description] hasPrefix:@"<UIPeripheralHostView"]) {
        keyboardVisible=YES;
    }
    if ([[possibleKeyboard description] hasPrefix:@"<UIKeyboard"]) {
        keyboardVisible=YES;
        break;
    }
}
return keyboardVisible;

}

from: iOS: How to access the `UIKeyboard`?

Cannot overwrite model once compiled Mongoose

I just have a mistake copy pasting. In one line I had same name that in other model (Ad model):

const Admin = mongoose.model('Ad', adminSchema);

Correct is:

const Admin = mongoose.model('Admin', adminSchema);

By the way, if someone have "auto-save", and use index for queries like:

**adSchema**.index({title:"text", description:"text", phone:"text", reference:"text"})

It has to delete index, and rewrite for correct model:

**adminSchema**.index({title:"text", description:"text", phone:"text", reference:"text"})

c++ exception : throwing std::string

It works, but I wouldn't do it if I were you. You don't seem to be deleting that heap data when you're done, which means that you've created a memory leak. The C++ compiler takes care of ensuring that exception data is kept alive even as the stack is popped, so don't feel that you need to use the heap.

Incidentally, throwing a std::string isn't the best approach to begin with. You'll have a lot more flexibility down the road if you use a simple wrapper object. It may just encapsulate a string for now, but maybe in future you will want to include other information, like some data which caused the exception or maybe a line number (very common, that). You don't want to change all of your exception handling in every spot in your code-base, so take the high road now and don't throw raw objects.

Shortcut to create properties in Visual Studio?

ReSharper offers property generation in its extensive feature set. (It's not cheap though, unless you're working on an open-source project.)

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

Cannot add or update a child row: a foreign key constraint fails

If you use mysql index or relation between tables, firstly you delete the colums(for example:city_id) and create new colums with same name(for example:city_id).Then try again...

How to compare character ignoring case in primitive types

You have to consider the Turkish I problem when comparing characters/ lowercasing / uppercasing:

I suggest to convert to String and use toLowerCase with invariant culture (in most cases at least).

public final static Locale InvariantLocale = new Locale(Empty, Empty, Empty); str.toLowerCase(InvariantLocale)

See similar C# string.ToLower() and string.ToLowerInvariant()

Note: Don't use String.equalsIgnoreCase http://nikolajlindberg.blogspot.co.il/2008/03/beware-of-java-comparing-turkish.html

How to build an android library with Android Studio and gradle?

Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

Making Enter key on an HTML form submit instead of activating button

I just gave this a whirl in both Chrome and Firefox and IE10.

As mentioned above - make sure that you have marked up with type = "button", "reset", "submit" etc to ensure that it correctly cascades and chooses the correct button.

Perhaps also setting all of them to have the same form (ie all as that worked for me)

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

constructor(private activatedRoute: ActivatedRoute) {

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

This works for me!

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

How to check whether an object is a date?

This is a pretty simple approach and doesn't experience a lot of the edge cases in the existing answers.

// Invalid Date.getTime() will produce NaN
if (date instanceof Date && date.getTime()) {
    console.log("is date!");
}

It won't fire with other objects like numbers, makes sure the value is actually a Date (rather than an object that looks like one), and it avoids Invalid Dates.

form confirm before submit

$('.testform').submit(function() {
  if ($(this).data('first-submit')) {
    return true;
  } else {
    $(this).find('.submitbtn').val('Confirm').data('first-submit', true);
    return false;
  }
});

How can I regenerate ios folder in React Native project?

The process you need to follow is so similar to renaming a react native app. Basically you just need to run react-native upgrade in your root project directory. For further info you can check another question here. The instructions below explains how to create another react native project based on a copied one with a new name.

  • First copy the directory which your to-be-name-changed application exists. And go to your newly cloned directory.
  • Change the name at index.ios/android.js file which is given as a parameter to AppRegistry.
  • Change the name and version accordingly on package.json
  • Delete /ios and /android folders which are remaining from your older app.
  • Run $react-native upgrade to generate /ios and /android folders again.
  • Run $react-native link for any native dependency.
  • Finally run $react-native run-ios or anything you want.

How to find the index of an element in an array in Java?

For primitive arrays

Starting with Java 8, the general purpose solution for a primitive array arr, and a value to search val, is:

public static int indexOf(char[] arr, char val) {
    return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}

This code creates a stream over the indexes of the array with IntStream.range, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst. findFirst returns an OptionalInt, as it is possible that no matching indexes were found. So we invoke orElse(-1) to either return the value found or -1 if none were found.

Overloads can be added for int[], long[], etc. The body of the method will remain the same.

For Object arrays

For object arrays, like String[], we could use the same idea and have the filtering step using the equals method, or Objects.equals to consider two null elements equal, instead of ==.

But we can do it in a simpler manner with:

public static <T> int indexOf(T[] arr, T val) {
    return Arrays.asList(arr).indexOf(val);
}

This creates a list wrapper for the input array using Arrays.asList and searches the index of the element with indexOf.

This solution does not work for primitive arrays, as shown here: a primitive array like int[] is not an Object[] but an Object; as such, invoking asList on it creates a list of a single element, which is the given array, not a list of the elements of the array.

Assign an initial value to radio button as checked

I've put this answer on a similar question that was marked as a duplicate of this question. The answer has helped a decent amount of people so I thought I'd add it here too in just in case.

This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).

Your html will look pretty similar to the normal radio button:

<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second

In your controller you'll have declared the mValue that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope variable associated with the group to the desired input's value:

$scope.mValue="second"

This makes the "second" radio button selected on loading the page.

Highlight all occurrence of a selected word?

  1. Add those lines in your ~/.vimrc file

" highlight the searched items set hlsearch " F8 search for word under the cursor recursively , :copen , to close -> :ccl nnoremap <F8> :grep! "\<<cword>\>" . -r<CR>:copen 33<CR>

  1. Reload the settings with :so%
  2. In normal model go over the word.

  3. Press * Press F8 to search recursively bellow your whole project over the word

How do I get elapsed time in milliseconds in Ruby?

Time.now.to_f can help you but it returns seconds.

In general, when working with benchmarks I:

  • put in variable the current time;
  • insert the block to test;
  • put in a variable the current time, subtracting the preceding current-time value;

It's a very simple process, so I'm not sure you were really asking this...

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

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

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

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

PuTTY Line discipline options

Explanation:

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

4.3.8 ‘Local echo’

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

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

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

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

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

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

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

dplyr change many data types

From the bottom of the ?mutate_each (at least in dplyr 0.5) it looks like that function, as in @docendo discimus's answer, will be deprecated and replaced with more flexible alternatives mutate_if, mutate_all, and mutate_at. The one most similar to what @hadley mentions in his comment is probably using mutate_at. Note the order of the arguments is reversed, compared to mutate_each, and vars() uses select() like semantics, which I interpret to mean the ?select_helpers functions.

dat %>% mutate_at(vars(starts_with("fac")),funs(factor)) %>%   
  mutate_at(vars(starts_with("dbl")),funs(as.numeric))

But mutate_at can take column numbers instead of a vars() argument, and after reading through this page, and looking at the alternatives, I ended up using mutate_at but with grep to capture many different kinds of column names at once (unless you always have such obvious column names!)

dat %>% mutate_at(grep("^(fac|fctr|fckr)",colnames(.)),funs(factor)) %>%
  mutate_at(grep("^(dbl|num|qty)",colnames(.)),funs(as.numeric))

I was pretty excited about figuring out mutate_at + grep, because now one line can work on lots of columns.

EDIT - now I see matches() in among the select_helpers, which handles regex, so now I like this.

dat %>% mutate_at(vars(matches("fac|fctr|fckr")),funs(factor)) %>%
  mutate_at(vars(matches("dbl|num|qty")),funs(as.numeric))

Another generally-related comment - if you have all your date columns with matchable names, and consistent formats, this is powerful. In my case, this turns all my YYYYMMDD columns, which were read as numbers, into dates.

  mutate_at(vars(matches("_DT$")),funs(as.Date(as.character(.),format="%Y%m%d")))

Converting an integer to a hexadecimal string in Ruby

How about using %/sprintf:

i = 20
"%x" % i  #=> "14"

UEFA/FIFA scores API

UEFA internally provides their own LIVEX Api for their Broadcasting Partners. That one is perfect enough to develop the Applications by their partners for themselves.

C# - How to get Program Files (x86) on Windows 64 bit

C# Code:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)

Output:

C:\Program Files (x86)

Note:

We need to tell the compiler to not prefer a particular build platform.

Go to Visual Studio > Project Properties > Build > Uncheck "Prefer 32 bit"

Reason:

By default for most .NET Projects is "Any CPU 32-bit preferred"

When you uncheck 32 bit assembly will:

JIT to 32-bit code on 32 bit process

JIT to 32-bit code on 64 bit process

Angular 2 change event on every keypress

Use ngModelChange by breaking up the [(x)] syntax into its two pieces, i.e., property databinding and event binding:

<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
  mymodel = newValue;
  console.log(newValue)
}

It works for the backspace key too.

How do I call a SQL Server stored procedure from PowerShell?

This answer was pulled from http://www.databasejournal.com/features/mssql/article.php/3683181

This same example can be used for any adhoc queries. Let us execute the stored procedure “sp_helpdb” as shown below.

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

What's in an Eclipse .classpath/.project file?

.project

When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.

.classpath

Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.

How do I install Java on Mac OSX allowing version switching?

This answer extends on Jayson's excellent answer with some more opinionated guidance on the best approach for your use case:

  • SDKMAN is the best solution for most users. It's easy to use, doesn't have any weird configuration, and makes managing multiple versions for lots of other Java ecosystem projects easy as well.
  • Downloading Java versions via Homebrew and switching versions via jenv is a good option, but requires more work. For example, the Homebrew commands in this highly upvoted answer don't work anymore. jenv is slightly harder to setup, the plugins aren't well documented, and the README says the project is looking for a new maintainer. jenv is still a great project, solves the job, and the community should be thankful for the wonderful contribution. SDKMAN is just the better option cause it's so great.
  • Jabba is written is a multi-platform solution that provides the same interface on Mac, Windows, and PC (it's written in Go and that's what allows it to be multiplatform). If you care about a multiplatform solution, this is a huge selling point. If you only care about running multiple versions on your Mac, then you don't need a multiplatform solution. SDKMAN's support for tens of popular SDKs is what you're missing out on if you go with Jabba.

Managing versions manually is probably the worst option. If you decide to manually switch versions, you can use this Bash code instead of Jayson's verbose code (code snippet from the homebrew-openjdk README:

jdk() {
        version=$1
        export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
        java -version
 }

Jayson's answer provides the basic commands for SDKMAN and jenv. Here's more info on SDKMAN and more info on jenv if you'd like more background on these tools.

Python: split a list based on a condition?

def partition(pred, seq):
  return reduce( lambda (yes, no), x: (yes+[x], no) if pred(x) else (yes, no+[x]), seq, ([], []) )

Boolean Field in Oracle

Oracle itself uses Y/N for Boolean values. For completeness it should be noted that pl/sql has a boolean type, it is only tables that do not.

If you are using the field to indicate whether the record needs to be processed or not you might consider using Y and NULL as the values. This makes for a very small (read fast) index that takes very little space.

NOT IN vs NOT EXISTS

I always default to NOT EXISTS.

The execution plans may be the same at the moment but if either column is altered in the future to allow NULLs the NOT IN version will need to do more work (even if no NULLs are actually present in the data) and the semantics of NOT IN if NULLs are present are unlikely to be the ones you want anyway.

When neither Products.ProductID or [Order Details].ProductID allow NULLs the NOT IN will be treated identically to the following query.

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId) 

The exact plan may vary but for my example data I get the following.

Neither NULL

A reasonably common misconception seems to be that correlated sub queries are always "bad" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.

/*Not valid syntax but better reflects the plan*/ 
SELECT p.ProductID,
       p.ProductName
FROM   Products p
       LEFT ANTI SEMI JOIN [Order Details] od
         ON p.ProductId = od.ProductId 

If [Order Details].ProductID is NULL-able the query then becomes

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId)
       AND NOT EXISTS (SELECT *
                       FROM   [Order Details]
                       WHERE  ProductId IS NULL) 

The reason for this is that the correct semantics if [Order Details] contains any NULL ProductIds is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.

One NULL

If Products.ProductID is also changed to become NULL-able the query then becomes

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId)
       AND NOT EXISTS (SELECT *
                       FROM   [Order Details]
                       WHERE  ProductId IS NULL)
       AND NOT EXISTS (SELECT *
                       FROM   (SELECT TOP 1 *
                               FROM   [Order Details]) S
                       WHERE  p.ProductID IS NULL) 

The reason for that one is because a NULL Products.ProductId should not be returned in the results except if the NOT IN sub query were to return no results at all (i.e. the [Order Details] table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.

Both NULL

The effect of this is shown in the blog post already linked by Buckley. In the example there the number of logical reads increase from around 400 to 500,000.

Additionally the fact that a single NULL can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no NULL rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, with inappropriate nested loops causing repeated execution of an expensive sub tree for example.

This is not the only possible execution plan for a NOT IN on a NULL-able column however. This article shows another one for a query against the AdventureWorks2008 database.

For the NOT IN on a NOT NULL column or the NOT EXISTS against either a nullable or non nullable column it gives the following plan.

Not EXists

When the column changes to NULL-able the NOT IN plan now looks like

Not In - Null

It adds an extra inner join operator to the plan. This apparatus is explained here. It is all there to convert the previous single correlated index seek on Sales.SalesOrderDetail.ProductID = <correlated_product_id> to two seeks per outer row. The additional one is on WHERE Sales.SalesOrderDetail.ProductID IS NULL.

As this is under an anti semi join if that one returns any rows the second seek will not occur. However if Sales.SalesOrderDetail does not contain any NULL ProductIDs it will double the number of seek operations required.

MySQL Error 1264: out of range value for column

You are exceeding the length of int datatype. You can use UNSIGNED attribute to support that value.

SIGNED INT can support till 2147483647 and with UNSIGNED INT allows double than this. After this you still want to save data than use CHAR or VARCHAR with length 10

Is it possible to read the value of a annotation in java?

I've never done it, but it looks like Reflection provides this. Field is an AnnotatedElement and so it has getAnnotation. This page has an example (copied below); quite straightforward if you know the class of the annotation and if the annotation policy retains the annotation at runtime. Naturally if the retention policy doesn't keep the annotation at runtime, you won't be able to query it at runtime.

An answer that's since been deleted (?) provided a useful link to an annotations tutorial that you may find helpful; I've copied the link here so people can use it.

Example from this page:

import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

class Meta {
  @MyAnno(str = "Two Parameters", val = 19)
  public static void myMeth(String str, int i) {
    Meta ob = new Meta();

    try {
      Class c = ob.getClass();

      Method m = c.getMethod("myMeth", String.class, int.class);

      MyAnno anno = m.getAnnotation(MyAnno.class);

      System.out.println(anno.str() + " " + anno.val());
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMeth("test", 10);
  }
}

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

According to this page https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html it is only available if (Enabled only in a UIWebView with the allowsInlineMediaPlayback property set to YES.) I understand in Mobile Safari this is YES on iPad and NO on iPhone and iPod Touch.

Python: Select subset from list based on index set

I see 2 options.

  1. Using numpy:

    property_a = numpy.array([545., 656., 5.4, 33.])
    property_b = numpy.array([ 1.2,  1.3, 2.3, 0.3])
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = property_a[good_objects]
    property_bsel = property_b[good_indices]
    
  2. Using a list comprehension and zip it:

    property_a = [545., 656., 5.4, 33.]
    property_b = [ 1.2,  1.3, 2.3, 0.3]
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = [x for x, y in zip(property_a, good_objects) if y]
    property_bsel = [property_b[i] for i in good_indices]
    

How to configure log4j.properties for SpringJUnit4ClassRunner?

I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.

Insert Unicode character into JavaScript

One option is to put the character literally in your script, e.g.:

const omega = 'O';

This requires that you let the browser know the correct source encoding, see Unicode in JavaScript

However, if you can't or don't want to do this (e.g. because the character is too exotic and can't be expected to be available in the code editor font), the safest option may be to use new-style string escape or String.fromCodePoint:

const omega = '\u{3a9}';

// or:

const omega = String.fromCodePoint(0x3a9);

This is not restricted to UTF-16 but works for all unicode code points. In comparison, the other approaches mentioned here have the following downsides:

  • HTML escapes (const omega = '&#937';): only work when rendered unescaped in an HTML element
  • old style string escapes (const omega = '\u03A9';): restricted to UTF-16
  • String.fromCharCode: restricted to UTF-16