Programs & Examples On #Zend gdata

The Zend_Gdata component is a PHP 5 interface for accessing Google Data from PHP. The Zend_Gdata component also supports accessing other services implementing the Atom Publishing Protocol.

How to check if a char is equal to an empty space?

The code you needs depends on what you mean by "an empty space".

  • If you mean the ASCII / Latin-1 / Unicode space character (0x20) aka SP, then:

    if (ch == ' ') {
        // ...
    }
    
  • If you mean any of the traditional ASCII whitespace characters (SP, HT, VT, CR, NL), then:

    if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\x0b') {
        // ...
    }
    
  • If you mean any Unicode whitespace character, then:

    if (Character.isWhitespace(ch)) {
        // ...
    }
    

Note that there are Unicode whitespace includes additional ASCII control codes, and some other Unicode characters in higher code planes; see the javadoc for Character.isWhitespace(char).


What you wrote was this:

    if (Equals(ch, " ")) {
        // ...
    }

This is wrong on a number of levels. Firstly, the way that the Java compiler tries to interpret that is as a call to a method with a signature of boolean Equals(char, String).

  • This is wrong because no method exists, as the compiler reported in the error message.
  • Equals wouldn't normally be the name of a method anyway. The Java convention is that method names start with a lower case letter.
  • Your code (as written) was trying to compare a character and a String, but char and String are not comparable and cannot be cast to a common base type.

There is such a thing as a Comparator in Java, but it is an interface not a method, and it is declared like this:

    public interface Comparator<T> {
        public int compare(T v1, T v2);
    }

In other words, the method name is compare (not Equals), it returns an integer (not a boolean), and it compares two values that can be promoted to the type given by the type parameter.


Someone (in a deleted Answer!) said they tried this:

    if (c == " ")

That fails for two reasons:

  • " " is a String literal and not a character literal, and Java does not allow direct comparison of String and char values.

  • You should NEVER compare Strings or String literals using ==. The == operator on a reference type compares object identity, not object value. In the case of String it is common to have different objects with different identity and the same value. An == test will often give the wrong answer ... from the perspective of what you are trying to do here.

How to downgrade or install an older version of Cocoapods

to remove your current version you could just run:

sudo gem uninstall cocoapods

you can install a specific version of cocoa pods via the following command:

sudo gem install cocoapods -v 0.25.0

You can use older installed versions with following command:

pod _0.25.0_ setup

Check to see if python script is running

A simple example if you only are looking for a process name exist or not:

import os

def pname_exists(inp):
    os.system('ps -ef > /tmp/psef')
    lines=open('/tmp/psef', 'r').read().split('\n')
    res=[i for i in lines if inp in i]
    return True if res else False

Result:
In [21]: pname_exists('syslog')
Out[21]: True

In [22]: pname_exists('syslog_')
Out[22]: False

What is PECS (Producer Extends Consumer Super)?

(adding an answer because never enough examples with Generics wildcards)

       // Source 
       List<Integer> intList = Arrays.asList(1,2,3);
       List<Double> doubleList = Arrays.asList(2.78,3.14);
       List<Number> numList = Arrays.asList(1,2,2.78,3.14,5);

       // Destination
       List<Integer> intList2 = new ArrayList<>();
       List<Double> doublesList2 = new ArrayList<>();
       List<Number> numList2 = new ArrayList<>();

        // Works
        copyElements1(intList,intList2);         // from int to int
        copyElements1(doubleList,doublesList2);  // from double to double


     static <T> void copyElements1(Collection<T> src, Collection<T> dest) {
        for(T n : src){
            dest.add(n);
         }
      }


     // Let's try to copy intList to its supertype
     copyElements1(intList,numList2); // error, method signature just says "T"
                                      // and here the compiler is given 
                                      // two types: Integer and Number, 
                                      // so which one shall it be?

     // PECS to the rescue!
     copyElements2(intList,numList2);  // possible



    // copy Integer (? extends T) to its supertype (Number is super of Integer)
    private static <T> void copyElements2(Collection<? extends T> src, 
                                          Collection<? super T> dest) {
        for(T n : src){
            dest.add(n);
        }
    }

Spring Boot - Loading Initial Data

If I just want to insert simple test data I often implement a ApplicationRunner. Implementations of this interface are run at application startup and can use e.g. a autowired repository to insert some test data.

I think such an implementation would be slightly more explicit than yours because the interface implies that your implementation contains something you would like to do directly after your application is ready.

Your implementation would look sth. like this:

@Component
public class DataLoader implements ApplicationRunner {

    private UserRepository userRepository;

    @Autowired
    public DataLoader(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void run(ApplicationArguments args) {
        userRepository.save(new User("lala", "lala", "lala"));
    }
}

Getting the WordPress Post ID of current post

you can use $post->ID for current id.

How do I look inside a Python object?

In Python 3.8, you can print out the contents of an object by using the __dict__. For example,

class Person():
   pass

person = Person()

## set attributes
person.first = 'Oyinda'
person.last = 'David'

## to see the content of the object
print(person.__dict__)  

{"first": "Oyinda", "last": "David"}

How to change UINavigationBar background color from the AppDelegate

You can easily do this with Xcode 6.3.1. Select your NavigationBar in the Document outline. Select the Attributes Inspector. Uncheck Translucent. Set Bar Tint to your desired color. Done!

html <input type="text" /> onchange event not working

onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

Read more about the change event here

Read more about the input event here

Getting the parameters of a running JVM

JConsole can do it. Also you can use a powerful jvisualVM tool, which also is included in JDK since 1.6.0.8.

MVC Razor Hidden input and passing values

As you may have already figured, Asp.Net MVC is a different paradigm than Asp.Net (webforms). Accessing form elements between the server and client take a different approach in Asp.Net MVC.

You can google more reading material on this on the web. For now, I would suggest using Ajax to get or post data to the server. You can still employ input type="hidden", but initialize it with a value from the ViewData or for Razor, ViewBag.

For example, your controller may look like this:

public ActionResult Index()
{
     ViewBag.MyInitialValue = true;
     return View();
} 

In your view, you can have an input elemet that is initialized by the value in your ViewBag:

<input type="hidden" name="myHiddenInput" id="myHiddenInput" value="@ViewBag.MyInitialValue" />

Then you can pass data between the client and server via ajax. For example, using jQuery:

$.get('GetMyNewValue?oldValue=' + $('#myHiddenInput').val(), function (e) {
   // blah
});

You can alternatively use $.ajax, $.getJSON, $.post depending on your requirement.

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

           @Html.RadioButton("Insured.GenderType", 1, (Model.Insured.GenderType == 1 ))
           @Web.Mvc.Claims.Resources.PartyResource.MaleLabel
           @Html.RadioButton("Insured.GenderType", 2, Model.Insured.GenderType == 2)
           @Web.Mvc.Claims.Resources.PartyResource.FemaleLabel

Animate change of view background color on Android

best way is to use ValueAnimator and ColorUtils.blendARGB

 ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
 valueAnimator.setDuration(325);
 valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {

              float fractionAnim = (float) valueAnimator.getAnimatedValue();

              view.setBackgroundColor(ColorUtils.blendARGB(Color.parseColor("#FFFFFF")
                                    , Color.parseColor("#000000")
                                    , fractionAnim));
        }
});
valueAnimator.start();

An item with the same key has already been added

I had 2 model properties like this

public int LinkId {get;set;}
public int LinkID {get;set;}

it is strange that it threw this error for these 2 haha..

Permanently Set Postgresql Schema Path

You can set the default search_path at the database level:

ALTER DATABASE <database_name> SET search_path TO schema1,schema2;

Or at the user or role level:

ALTER ROLE <role_name> SET search_path TO schema1,schema2;

Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.

When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name> to create your databases.

How to keep a VMWare VM's clock in sync?

The CPU speed varies due to power saving. I originally noticed this because VMware gave me a helpful tip on my laptop, but this page mentions the same thing:

Quote from : VMWare tips and tricks Power saving (SpeedStep, C-states, P-States,...)

Your power saving settings may interfere significantly with vmware's performance. There are several levels of power saving.

CPU frequency

This should not lead to performance degradation, outside of having the obvious lower performance when running the CPU at a lower frequency (either manually of via governors like "ondemand" or "conservative"). The only problem with varying the CPU speed while vmware is running is that the Windows clock will gain of lose time. To prevent this, specify your full CPU speed in kHz in /etc/vmware/config

host.cpukHz = 2167000

Plotting lines connecting points

I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')

Plot of two pairs of points, each connected by a separate line

Error sending json in POST to web API service

another tip...where to add "content-type: application/json"...to the textbox field on the Composer/Parsed tab. There are 3 lines already filled in there, so I added this Content-type as the 4th line. That made the Post work.

Add attribute 'checked' on click jquery

$( this ).attr( 'checked', 'checked' )

just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />

Edit:

Based on comments, a more appropriate manipulation would be:

$( this ).attr( 'checked', true )

And a straight javascript method, more appropriate and efficient:

this.checked = true;

Thanks @Andy E for that.

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

First of all, if you are trying to encode apostophes for querystrings, they need to be URLEncoded, not escaped with a leading backslash. For that use URLEncoder.encode(String, String) (BTW: the second argument should always be "UTF-8"). Secondly, if you want to replace all instances of apostophe with backslash apostrophe, you must escape the backslash in your string expression with a leading backslash. Like this:

"This is' it".replace("'", "\\'");

Edit:

I see now that you are probably trying to dynamically build a SQL statement. Do not do it this way. Your code will be susceptible to SQL injection attacks. Instead use a PreparedStatement.

How to find Port number of IP address?

If it is a normal then the port number is always 80 and may be written as http://www.somewhere.com:80 Though you don't need to specify it as :80 is the default of every web browser.

If the site chose to use something else then they are intending to hide from anything not sent by a "friendly" or linked to. Those ones usually show with https and their port number is unknown and decided by their admin.

If you choose to runn a port scanner trying every number nn from say 10000 to 30000 in https://something.somewhere.com:nn Then your isp or their antivirus will probably notice and disconnect you.

Right way to split an std::string into a vector<string>

vector<string> split(string str, string token){
    vector<string>result;
    while(str.size()){
        int index = str.find(token);
        if(index!=string::npos){
            result.push_back(str.substr(0,index));
            str = str.substr(index+token.size());
            if(str.size()==0)result.push_back(str);
        }else{
            result.push_back(str);
            str = "";
        }
    }
    return result;
}

split("1,2,3",",") ==> ["1","2","3"]

split("1,2,",",") ==> ["1","2",""]

split("1token2token3","token") ==> ["1","2","3"]

How to place the "table" at the middle of the webpage?

The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.

That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!

<style>
  html, body {
    height: 100%;
  }
  #tableContainer-1 {
    height: 100%;
    width: 100%;
    display: table;
  }
  #tableContainer-2 {
    vertical-align: middle;
    display: table-cell;
    height: 100%;
  }
  #myTable {
    margin: 0 auto;
  }
</style>
<div id="tableContainer-1">
  <div id="tableContainer-2">
    <table id="myTable" border>
      <tr><td>Name</td><td>J W BUSH</td></tr>
      <tr><td>Proficiency</td><td>PHP</td></tr>
      <tr><td>Company</td><td>BLAH BLAH</td></tr>
    </table>
  </div>
</div>

Is it possible to set UIView border properties from interface builder?

For Swift 3 and 4, if you're willing to use IBInspectables, there's this:

@IBDesignable extension UIView {
    @IBInspectable var borderColor:UIColor? {
        set {
            layer.borderColor = newValue!.cgColor
        }
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            else {
                return nil
            }
        }
    }
    @IBInspectable var borderWidth:CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    @IBInspectable var cornerRadius:CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

Querying Datatable with where condition

something like this ? :

DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"

Is it what you are searching for?

Ctrl+click doesn't work in Eclipse Juno

Go to

Window -> Preferences -> General -> Editors -> Text Editors -> Hyperlinking

and be sure that

Enable on demand hyperlink style navigation

is checked.

How do I include a JavaScript file in another JavaScript file?

Or rather than including at run time, use a script to concatenate prior to upload.

I use Sprockets (I don't know if there are others). You build your JavaScript code in separate files and include comments that are processed by the Sprockets engine as includes. For development you can include files sequentially, then for production to merge them...

See also:

Angular 2: Get Values of Multiple Checked Checkboxes

Here's a solution without map, 'checked' properties and FormControl.

app.component.html:

<div *ngFor="let item of options">
  <input type="checkbox" 
  (change)="onChange($event.target.checked, item)"
  [checked]="checked(item)"
>
  {{item}}
</div>

app.component.ts:

  options = ["1", "2", "3", "4", "5"]
  selected = ["1", "2", "5"]

  // check if the item are selected
  checked(item){
    if(this.selected.indexOf(item) != -1){
      return true;
    }
  }

  // when checkbox change, add/remove the item from the array
  onChange(checked, item){
    if(checked){
    this.selected.push(item);
    } else {
      this.selected.splice(this.selected.indexOf(item), 1)
    }
  }

DEMO

TypeScript sorting an array

The easiest way seems to be subtracting the second number from the first:

var numericArray:Array<number> = [2,3,4,1,5,8,11];

var sorrtedArray:Array<number> = numericArray.sort((n1,n2) => n1 - n2);

https://alligator.io/js/array-sort-numbers/

How to generate JAXB classes from XSD?

In intellij click .xsd file -> WebServices ->Generate Java code from Xml Schema JAXB then give package path and package name ->ok

Encrypt Password in Configuration Files?

The big point, and the elephant in the room and all that, is that if your application can get hold of the password, then a hacker with access to the box can get hold of it too!

The only way somewhat around this, is that the application asks for the "master password" on the console using Standard Input, and then uses this to decrypt the passwords stored on file. Of course, this completely makes is impossible to have the application start up unattended along with the OS when it boots.

However, even with this level of annoyance, if a hacker manages to get root access (or even just access as the user running your application), he could dump the memory and find the password there.

The thing to ensure, is to not let the entire company have access to the production server (and thereby to the passwords), and make sure that it is impossible to crack this box!

Script to Change Row Color when a cell changes text

//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();
    if (status == 'Completed') {
      rowRange.setBackgroundColor("#99CC99");
    } else if (status == 'In Progress') {
      rowRange.setBackgroundColor("#FFDD88");    
    } else if (status == 'Not Started') {
      rowRange.setBackgroundColor("#CC6666");          
    }
  }
}

//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

Checking for installed php modules and packages

In addition to running

php -m

to get the list of installed php modules, you will probably find it helpful to get the list of the currently installed php packages in Ubuntu:

sudo dpkg --get-selections | grep -v deinstall | grep php

This is helpful since Ubuntu makes php modules available via packages.

You can then install the needed modules by selecting from the available Ubuntu php packages, which you can view by running:

sudo apt-cache search php | grep "^php5-"

Or, for Ubuntu 16.04 and higher:

sudo apt-cache search php | grep "^php7"

As you have mentioned, there is plenty of information available on the actual installation of the packages that you might require, so I won't go into detail about that here.

Related: Enabling / disabling installed php modules

It is possible that an installed module has been disabled. In that case, it won't show up when running php -m, but it will show up in the list of installed Ubuntu packages.

Modules can be enabled/disabled via the php5enmod tool (phpenmod on later distros) which is part of the php-common package.

Ubuntu 12.04:

Enabled modules are symlinked in /etc/php5/conf.d

Ubuntu 12.04: (with PHP 5.4+)

To enable an installed module:

php5enmod <modulename>

To disable an installed module:

php5dismod <modulename>

Ubuntu 16.04 (php7) and higher:

To enable an installed module:

phpenmod <modulename>

To disable an installed module:

phpdismod <modulename>

Reload Apache

Remember to reload Apache2 after enabling/disabling:

service apache2 reload

How to set a Javascript object values dynamically?

You can get the property the same way as you set it.

foo = {
 bar: "value"
}

You set the value foo["bar"] = "baz";

To get the value foo["bar"]

will return "baz".

Undefined reference to 'vtable for xxx'

GNU linker, in my case companion of GCC 8.1.0, well detects not re-declared pure virtual methods, but above certain complexity of class design it fails to identify missing implementation of methods and answers with a flat "V-Table Missing",

or even tends to report missing implementation, in spite it is there.

The only solution then is to verify consistency of declaration of implementation manually, method by method.

Ubuntu - Run command on start-up with "sudo"

You can add the command in the /etc/rc.local script that is executed at the end of startup.

Write the command before exit 0. Anything written after exit 0 will never be executed.

Ruby replace string with captured regex pattern

$ variables are only set to matches into the block:

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/) { "#{ $1.strip }" }

This is also the only way to call a method on the match. This will not change the match, only strip "\1" (leaving it unchanged):

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1".strip)

typedef fixed length array

Building off the accepted answer, a multi-dimensional array type, that is a fixed-length array of fixed-length arrays, can't be declared with

typedef char[M] T[N];  // wrong!

instead, the intermediate 1D array type can be declared and used as in the accepted answer:

typedef char T_t[M];
typedef T_t T[N];

or, T can be declared in a single (arguably confusing) statement:

typedef char T[N][M];

which defines a type of N arrays of M chars (be careful about the order, here).

Show how many characters remaining in a HTML text box using JavaScript

Dynamic HTML element functionThe code in here with a little bit of modification and simplification:

<input disabled  maxlength="3" size="3" value="10" id="counter">
<textarea onkeyup="textCounter(this,'counter',10);" id="message">
</textarea>
<script>
function textCounter(field,field2,maxlimit)
{
 var countfield = document.getElementById(field2);
 if ( field.value.length > maxlimit ) {
  field.value = field.value.substring( 0, maxlimit );
  return false;
 } else {
  countfield.value = maxlimit - field.value.length;
 }
}
</script>

Hope this helps!

tip:

When merging the codes with your page, make sure the HTML elements(textarea, input) are loaded first before the scripts (Javascript functions)

How to select Python version in PyCharm?

File -> Settings

Preferences->Project Interpreter->Python Interpreters

If it's not listed add it.

enter image description here

How to install wget in macOS?

For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.

  1. Install Xcode

  2. Build OpenSSL

    Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.

    Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".

  3. Build wget

    Go to wget directory, configure:

    ./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
    

    wget should configure and found OpenSSL, then make:

    make
    

    wget made out. Install wget:

    make install
    

    Or just copy wget to where you want.

  4. Configure cert

    You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:

    New way:

    If you machine doesn't have "/usr/local/ssl/" dir, first make it.

    ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
    

    Old way:

    security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
    security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
    

    Then put cert.pem to: "/usr/local/ssl/cert.pem"

    DONE: It should be all right now.

Set EditText cursor color

editcolor.xml

android:textCursorDrawable="@drawable/editcolor"

In xml file set color code of edittext background color

How do I find out what version of Sybase is running

Try running below command (Works on both windows and linux)

isql -v

CardView not showing Shadow in Android L

I think if you check your manifest first if you wrote android:hardwareAccelerated="false" you should make it true to having shadow for the card Like this answer here

'foo' was not declared in this scope c++

In C++ you are supposed to declare functions before you can use them. In your code integrate is not declared before the point of the first call to integrate. The same applies to sum. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.

Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable, getSkewNormal, integrate etc. have no business being in header file.

Also SkewNormalEvalutatable e(); declaration in C++ declares a function e, not an object e as you seem to assume. The simple SkewNormalEvalutatable e; will declare an object initialized by default constructor.

Also, you receive the last parameter of integrate (and of sum) by value as an object of Evaluatable type. That means that attempting to pass SkewNormalEvalutatable as last argument of integrate will result in SkewNormalEvalutatable getting sliced to Evaluatable. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.

How to enable CORS in ASP.net Core WebAPI

To expand on user8266077's answer, I found that I still needed to supply OPTIONS response for preflight requests in .NET Core 2.1-preview for my use case:

// https://stackoverflow.com/a/45844400
public class CorsMiddleware
{
  private readonly RequestDelegate _next;

  public CorsMiddleware(RequestDelegate next)
  {
    _next = next;
  }

  public async Task Invoke(HttpContext context)
  {
    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
    // Added "Accept-Encoding" to this list
    context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Accept-Encoding, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
    context.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
    // New Code Starts here
    if (context.Request.Method == "OPTIONS")
    {
      context.Response.StatusCode = (int)HttpStatusCode.OK;
      await context.Response.WriteAsync(string.Empty);
    }
    // New Code Ends here

    await _next(context);
  }
}

and then enabled the middleware like so in Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.UseMiddleware(typeof(CorsMiddleware));
  // ... other middleware inclusion such as ErrorHandling, Caching, etc
  app.UseMvc();
}

What is a JavaBean exactly?

They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name "Bean" was given to encompass this standard, which aims to create reusable software components for Java. According to Wikipedia.

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. According to Spring IoC.

Python date string to date object

You can use strptime in the datetime package of Python:

>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)

Finding first blank row, then writing to it

I would have done it like this. Short and sweet :)

Sub test()
Dim rngToSearch As Range
Dim FirstBlankCell As Range
Dim firstEmptyRow As Long

Set rngToSearch = Sheet1.Range("A:A")
    'Check first cell isn't empty
    If IsEmpty(rngToSearch.Cells(1, 1)) Then
        firstEmptyRow = rngToSearch.Cells(1, 1).Row
    Else
        Set FirstBlankCell = rngToSearch.FindNext(After:=rngToSearch.Cells(1, 1))
        If Not FirstBlankCell Is Nothing Then
            firstEmptyRow = FirstBlankCell.Row
        Else
            'no empty cell in range searched
        End If
    End If
End Sub

Updated to check if first row is empty.

Edit: Update to include check if entire row is empty

Option Explicit

Sub test()
Dim rngToSearch As Range
Dim firstblankrownumber As Long

    Set rngToSearch = Sheet1.Range("A1:C200")
    firstblankrownumber = FirstBlankRow(rngToSearch)
    Debug.Print firstblankrownumber

End Sub

Function FirstBlankRow(ByVal rngToSearch As Range, Optional activeCell As Range) As Long
Dim FirstBlankCell As Range

    If activeCell Is Nothing Then Set activeCell = rngToSearch.Cells(1, 1)
    'Check first cell isn't empty
    If WorksheetFunction.CountA(rngToSearch.Cells(1, 1).EntireRow) = 0 Then
        FirstBlankRow = rngToSearch.Cells(1, 1).Row
    Else

        Set FirstBlankCell = rngToSearch.FindNext(After:=activeCell)
        If Not FirstBlankCell Is Nothing Then

            If WorksheetFunction.CountA(FirstBlankCell.EntireRow) = 0 Then
                FirstBlankRow = FirstBlankCell.Row
            Else
                Set activeCell = FirstBlankCell
                FirstBlankRow = FirstBlankRow(rngToSearch, activeCell)

            End If
        Else
            'no empty cell in range searched
        End If
    End If
End Function

Meaning of delta or epsilon argument of assertEquals for double values

Floating point calculations are not exact - there is often round-off errors, and errors due to representation. (For example, 0.1 cannot be exactly represented in binary floating point.)

Because of this, directly comparing two floating point values for equality is usually not a good idea, because they can be different by a small amount, depending upon how they were computed.

The "delta", as it's called in the JUnit javadocs, describes the amount of difference you can tolerate in the values for them to be still considered equal. The size of this value is entirely dependent upon the values you're comparing. When comparing doubles, I typically use the expected value divided by 10^6.

How to split a string literal across multiple lines in C / Objective-C?

There's a trick you can do with the pre-processor.
It has the potential down sides that it will collapse white-space, and could be confusing for people reading the code.
But, it has the up side that you don't need to escape quote characters inside it.

#define QUOTE(...) #__VA_ARGS__
const char *sql_query = QUOTE(
    SELECT word_id
    FROM table1, table2
    WHERE table2.word_id = table1.word_id
    ORDER BY table1.word ASC
);

the preprocessor turns this into:

const char *sql_query = "SELECT word_id FROM table1, table2 WHERE table2.word_id = table1.word_id ORDER BY table1.word ASC";

I've used this trick when I was writing some unit tests that had large literal strings containing JSON. It meant that I didn't have to escape every quote character \".

SFTP in Python? (platform independent)

If you want easy and simple, you might also want to look at Fabric. It's an automated deployment tool like Ruby's Capistrano, but simpler and of course for Python. It's build on top of Paramiko.

You might not want to do 'automated deployment' but Fabric would suit your use case perfectly none the less. To show you how simple Fabric is: the fab file and command for your script would look like this (not tested, but 99% sure it will work):

fab_putfile.py:

from fabric.api import *

env.hosts = ['THEHOST.com']
env.user = 'THEUSER'
env.password = 'THEPASSWORD'

def put_file(file):
    put(file, './THETARGETDIRECTORY/') # it's copied into the target directory

Then run the file with the fab command:

fab -f fab_putfile.py put_file:file=./path/to/my/file

And you're done! :)

Converting a value to 2 decimal places within jQuery

Try to use this

parseFloat().toFixed(2)

How to use Simple Ajax Beginform in Asp.net MVC 4?

Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

How to convert a factor to integer\numeric without loss of information?

R has a number of (undocumented) convenience functions for converting factors:

  • as.character.factor
  • as.data.frame.factor
  • as.Date.factor
  • as.list.factor
  • as.vector.factor
  • ...

But annoyingly, there is nothing to handle the factor -> numeric conversion. As an extension of Joshua Ulrich's answer, I would suggest to overcome this omission with the definition of your own idiomatic function:

as.numeric.factor <- function(x) {as.numeric(levels(x))[x]}

that you can store at the beginning of your script, or even better in your .Rprofile file.

How to convert buffered image to image and vice-versa?

Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:

Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);     

BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);

bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);

Convert binary to ASCII and vice versa

This is a spruced up version of J.F. Sebastian's. Thanks for the snippets though J.F. Sebastian.

import binascii, sys
def goodbye():
    sys.exit("\n"+"*"*43+"\n\nGood Bye! Come use again!\n\n"+"*"*43+"")
while __name__=='__main__':
    print "[A]scii to Binary, [B]inary to Ascii, or [E]xit:"
    var1=raw_input('>>> ')
    if var1=='a':
        string=raw_input('String to convert:\n>>> ')
        convert=bin(int(binascii.hexlify(string), 16))
        i=2
        truebin=[]
        while i!=len(convert):
            truebin.append(convert[i])
            i=i+1
        convert=''.join(truebin)
        print '\n'+'*'*84+'\n\n'+convert+'\n\n'+'*'*84+'\n'
    if var1=='b':
        binary=raw_input('Binary to convert:\n>>> ')
        n = int(binary, 2)
        done=binascii.unhexlify('%x' % n)
        print '\n'+'*'*84+'\n\n'+done+'\n\n'+'*'*84+'\n'
    if var1=='e':
        aus=raw_input('Are you sure? (y/n)\n>>> ')
        if aus=='y':
            goodbye()

Maven is not working in Java 8 when Javadoc tags are incomplete

As of maven-javadoc-plugin 3.0.0 you should have been using additionalJOption to set an additional Javadoc option, so if you would like Javadoc to disable doclint, you should add the following property.

<properties>
    ...
    <additionalJOption>-Xdoclint:none</additionalJOption>
    ...
<properties>

You should also mention the version of maven-javadoc-plugin as 3.0.0 or higher.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.0.0</version>    
</plugin>

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

This saved my life,

mysqld --tc-heuristic-recover=ROLLBACK

Read more

angularjs: ng-src equivalent for background-image:url(...)

ngSrc is a native directive, so it seems you want a similar directive that modifies your div's background-image style.

You could write your own directive that does exactly what you want. For example

app.directive('backImg', function(){
    return function(scope, element, attrs){
        var url = attrs.backImg;
        element.css({
            'background-image': 'url(' + url +')',
            'background-size' : 'cover'
        });
    };
});?

Which you would invoke like this

<div back-img="<some-image-url>" ></div>

JSFiddle with cute cats as a bonus: http://jsfiddle.net/jaimem/aSjwk/1/

Scroll to bottom of div?

small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):

var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);                   

// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!

// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

How to get the command line args passed to a running process on unix/linux systems?

On Linux, with bash, to output as quoted args so you can edit the command and rerun it

</proc/"${pid}"/cmdline xargs --no-run-if-empty -0 -n1 \
    bash -c 'printf "%q " "${1}"' /dev/null; echo

On Solaris, with bash (tested with 3.2.51(1)-release) and without gnu userland:

IFS=$'\002' tmpargs=( $( pargs "${pid}" \
    | /usr/bin/sed -n 's/^argv\[[0-9]\{1,\}\]: //gp' \
    | tr '\n' '\002' ) )
for tmparg in "${tmpargs[@]}"; do
    printf "%q " "$( echo -e "${tmparg}" )"
done; echo

Linux bash Example (paste in terminal):

{
## setup intial args
argv=( /bin/bash -c '{ /usr/bin/sleep 10; echo; }' /dev/null 'BEGIN {system("sleep 2")}' "this is" \
    "some" "args "$'\n'" that" $'\000' $'\002' "need" "quot"$'\t'"ing" )

## run in background
"${argv[@]}" &

## recover into eval string that assigns it to argv_recovered
eval_me=$(
    printf "argv_recovered=( "
    </proc/"${!}"/cmdline xargs --no-run-if-empty -0 -n1 \
        bash -c 'printf "%q " "${1}"' /dev/null
    printf " )\n"
)

## do eval
eval "${eval_me}"

## verify match
if [ "$( declare -p argv )" == "$( declare -p argv_recovered | sed 's/argv_recovered/argv/' )" ];
then
    echo MATCH
else
    echo NO MATCH
fi
}

Output:

MATCH

Solaris Bash Example:

{
## setup intial args
argv=( /bin/bash -c '{ /usr/bin/sleep 10; echo; }' /dev/null 'BEGIN {system("sleep 2")}' "this is" \
    "some" "args "$'\n'" that" $'\000' $'\002' "need" "quot"$'\t'"ing" )

## run in background
"${argv[@]}" &
pargs "${!}"
ps -fp "${!}"

declare -p tmpargs
eval_me=$(
    printf "argv_recovered=( "
    IFS=$'\002' tmpargs=( $( pargs "${!}" \
        | /usr/bin/sed -n 's/^argv\[[0-9]\{1,\}\]: //gp' \
        | tr '\n' '\002' ) )
    for tmparg in "${tmpargs[@]}"; do
        printf "%q " "$( echo -e "${tmparg}" )"
    done; echo
    printf " )\n"
)

## do eval
eval "${eval_me}"


## verify match
if [ "$( declare -p argv )" == "$( declare -p argv_recovered | sed 's/argv_recovered/argv/' )" ];
then
    echo MATCH
else
    echo NO MATCH
fi
}

Output:

MATCH

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

Unescape HTML entities in Javascript?

EDIT: You should use the DOMParser API as Wladimir suggests, I edited my previous answer since the function posted introduced a security vulnerability.

The following snippet is the old answer's code with a small modification: using a textarea instead of a div reduces the XSS vulnerability, but it is still problematic in IE9 and Firefox.

function htmlDecode(input){
  var e = document.createElement('textarea');
  e.innerHTML = input;
  // handle case of empty input
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

htmlDecode("&lt;img src='myimage.jpg'&gt;"); 
// returns "<img src='myimage.jpg'>"

Basically I create a DOM element programmatically, assign the encoded HTML to its innerHTML and retrieve the nodeValue from the text node created on the innerHTML insertion. Since it just creates an element but never adds it, no site HTML is modified.

It will work cross-browser (including older browsers) and accept all the HTML Character Entities.

EDIT: The old version of this code did not work on IE with blank inputs, as evidenced here on jsFiddle (view in IE). The version above works with all inputs.

UPDATE: appears this doesn't work with large string, and it also introduces a security vulnerability, see comments.

select certain columns of a data table

Here's working example with anonymous output record, if you have any questions place a comment below:                    

public partial class Form1 : Form
{
    DataTable table;
    public Form1()
    {
        InitializeComponent();
        #region TestData
        table = new DataTable();
        table.Clear();
        for (int i = 1; i < 12; ++i)
            table.Columns.Add("Col" + i);
        for (int rowIndex = 0; rowIndex < 5; ++rowIndex)
        {
            DataRow row = table.NewRow();
            for (int i = 0; i < table.Columns.Count; ++i)
                row[i] = String.Format("row:{0},col:{1}", rowIndex, i);
            table.Rows.Add(row);
        }
        #endregion
        bind();
    }

    public void bind()
    {
        var filtered = from t in table.AsEnumerable()
                       select new
                       {
                           col1 = t.Field<string>(0),//column of index 0 = "Col1"
                           col2 = t.Field<string>(1),//column of index 1 = "Col2"
                           col3 = t.Field<string>(5),//column of index 5 = "Col6"
                           col4 = t.Field<string>(6),//column of index 6 = "Col7"
                           col5 = t.Field<string>(4),//column of index 4 = "Col3"
                       };
        filteredData.AutoGenerateColumns = true;
        filteredData.DataSource = filtered.ToList();
    }
}

How can I replace a newline (\n) using sed?

I posted this answer because I have tried with most of the sed commend example provided above which does not work for me in my Unix box and giving me error message Label too long: {:q;N;s/\n/ /g;t q}. Finally I made my requirement and hence shared here which works in all Unix/Linux environment:-

line=$(while read line; do echo -n "$line "; done < yoursourcefile.txt)
echo $line |sed 's/ //g' > sortedoutput.txt

The first line will remove all the new line from file yoursourcefile.txt and will produce a single line. And second sed command will remove all the spaces from it.

Getting Checkbox Value in ASP.NET MVC 4

@Html.EditorFor(x => x.Remember)

Will generate:

<input id="Remember" type="checkbox" value="true" name="Remember" />
<input type="hidden" value="false" name="Remember" />

How does it work:

  • If checkbox remains unchecked, the form submits only the hidden value (false)
  • If checked, then the form submits two fields (false and true) and MVC sets true for the model's bool property

<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

This will always send the default value, if checked.

Converting string to date in mongodb

In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })

Get the current displaying UIViewController on the screen in AppDelegate.m

Mine is better! :)

extension UIApplication {
    var visibleViewController : UIViewController? {
        return keyWindow?.rootViewController?.topViewController
    }
}

extension UIViewController {
    fileprivate var topViewController: UIViewController {
        switch self {
        case is UINavigationController:
            return (self as! UINavigationController).visibleViewController?.topViewController ?? self
        case is UITabBarController:
            return (self as! UITabBarController).selectedViewController?.topViewController ?? self
        default:
            return presentedViewController?.topViewController ?? self
        }
    }
}

Convert time fields to strings in Excel

copy the column paste it into notepad copy it again paste special as Text

const to Non-const Conversion in C++

Changing a constant type will lead to an Undefined Behavior.

However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.

Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.

Using <style> tags in the <body> with other HTML

The <style> tag belongs in the <head> section, separate from all the content.

References: W3C Specs and W3Schools

"Cross origin requests are only supported for HTTP." error when loading a local file

Just change the url to http://localhost instead of localhost. If you open the html file from local, you should create a local server to serve that html file, the simplest way is using Web Server for Chrome. That will fix the issue.

How to take screenshot of a div with JavaScript?

It's to simple you can use this code for capture the screenshot of particular area you have to define the div id in html2canvas. I'm using here 2 div-:

div id="car"
div id ="chartContainer"
if you want to capture only cars then use car i'm capture here car only you can change chartContainer for capture the graph html2canvas($('#car') copy and paste this code

_x000D_
_x000D_
<html>_x000D_
    <head>_x000D_
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">_x000D_
<script>_x000D_
    window.onload = function () {_x000D_
    _x000D_
    var chart = new CanvasJS.Chart("chartContainer", {_x000D_
        animationEnabled: true,_x000D_
        theme: "light2",_x000D_
        title:{_x000D_
            text: "Simple Line Chart"_x000D_
        },_x000D_
        axisY:{_x000D_
            includeZero: false_x000D_
        },_x000D_
        data: [{        _x000D_
            type: "line",       _x000D_
            dataPoints: [_x000D_
                { y: 450 },_x000D_
                { y: 414},_x000D_
                { y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" },_x000D_
                { y: 460 },_x000D_
                { y: 450 },_x000D_
                { y: 500 },_x000D_
                { y: 480 },_x000D_
                { y: 480 },_x000D_
                { y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" },_x000D_
                { y: 500 },_x000D_
                { y: 480 },_x000D_
                { y: 510 }_x000D_
_x000D_
            ]_x000D_
        }]_x000D_
    });_x000D_
    chart.render();_x000D_
    _x000D_
    }_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body bgcolor="black">_x000D_
<div id="wholebody">  _x000D_
<a href="javascript:genScreenshotgraph()"><button style="background:aqua; cursor:pointer">Get Screenshot of Cars onl </button> </a>_x000D_
_x000D_
<div id="car" align="center">_x000D_
    <i class="fa fa-car" style="font-size:70px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:60px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:50px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:20px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:50px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:60px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:70px;color:red;"></i>_x000D_
</div>_x000D_
<br>_x000D_
<div id="chartContainer" style="height: 370px; width: 100%;"></div>_x000D_
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>_x000D_
_x000D_
<div id="box1">_x000D_
</div>_x000D_
</div>>_x000D_
</body>_x000D_
_x000D_
<script>_x000D_
_x000D_
function genScreenshotgraph() _x000D_
{_x000D_
    html2canvas($('#car'), {_x000D_
        _x000D_
      onrendered: function(canvas) {_x000D_
_x000D_
        var imgData = canvas.toDataURL("image/jpeg");_x000D_
        var pdf = new jsPDF();_x000D_
        pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);_x000D_
        pdf.save("download.pdf");_x000D_
        _x000D_
      _x000D_
      _x000D_
      }_x000D_
     });_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

However, numbering starts at 1, so:

x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)

z = np.sin(x)
plt.figure(2)
plt.plot(x, z)

w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)

Also, if you have multiple axes on a figure, such as subplots, use the axes(h) command where h is the handle of the desired axes object to focus on that axes.

(don't have comment privileges yet, sorry for new answer!)

How to make type="number" to positive numbers only

Try

<input type="number" pattern="^[0-9]" title='Only Number' min="1" step="1">

How to bind DataTable to Datagrid

In .cs file

grid.DataContext = table.DefaultView;

In xaml file

<DataGrid Name="grid" ItemsSource="{Binding}">

What happens to C# Dictionary<int, int> lookup if the key does not exist?

int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;

If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.

Hope, this code helps you.

How to get error message when ifstream open fails

You could try letting the stream throw an exception on failure:

std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);

try {
  f.open(fileName);
}
catch (std::ios_base::failure& e) {
  std::cerr << e.what() << '\n';
}

e.what(), however, does not seem to be very helpful:

  • I tried it on Win7, Embarcadero RAD Studio 2010 where it gives "ios_base::failbit set" whereas strerror(errno) gives "No such file or directory."
  • On Ubuntu 13.04, gcc 4.7.3 the exception says "basic_ios::clear" (thanks to arne)

If e.what() does not work for you (I don't know what it will tell you about the error, since that's not standardized), try using std::make_error_condition (C++11 only):

catch (std::ios_base::failure& e) {
  if ( e.code() == std::make_error_condition(std::io_errc::stream) )
    std::cerr << "Stream error!\n"; 
  else
    std::cerr << "Unknown failure opening file.\n";
}

General error: 1364 Field 'user_id' doesn't have a default value

User Auth::user()->id instead.

Here is the correct way :

//PostController
Post::create(request([
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => Auth::user()->id
]));

If your user is authenticated, Then Auth::user()->id will do the trick.

Best way to extract a subvector from a vector?

This discussion is pretty old, but the simplest one isn't mentioned yet, with list-initialization:

 vector<int> subvector = {big_vector.begin() + 3, big_vector.end() - 2}; 

It requires c++11 or above.

Example usage:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){

    vector<int> big_vector = {5,12,4,6,7,8,9,9,31,1,1,5,76,78,8};
    vector<int> subvector = {big_vector.begin() + 3, big_vector.end() - 2};

    cout << "Big vector: ";
    for_each(big_vector.begin(), big_vector.end(),[](int number){cout << number << ";";});
    cout << endl << "Subvector: ";
    for_each(subvector.begin(), subvector.end(),[](int number){cout << number << ";";});
    cout << endl;
}

Result:

Big vector: 5;12;4;6;7;8;9;9;31;1;1;5;76;78;8;
Subvector: 6;7;8;9;9;31;1;1;5;76;

How to use table variable in a dynamic sql statement?

You can't do this because the table variables are out of scope.

You would have to declare the table variable inside the dynamic SQL statement or create temporary tables.

I would suggest you read this excellent article on dynamic SQL.

http://www.sommarskog.se/dynamic_sql.html

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

Is there a way to make a DIV unselectable?

The following CSS code works almost modern browser:

.unselectable {
    -moz-user-select: -moz-none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
    user-select: none;
}

For IE, you must use JS or insert attribute in html tag.

<div id="foo" unselectable="on" class="unselectable">...</div>

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

What is apache's maximum url length?

The default limit for the length of the request line is 8190 bytes (see LimitRequestLine directive). And if we subtract three bytes for the request method (i.e. GET), eight bytes for the version information (i.e. HTTP/1.0/HTTP/1.1) and two bytes for the separating space, we end up with 8177 bytes for the URI path plus query.

iptables block access to port 8000 except from IP address

This question should be on Server Fault. Nevertheless, the following should do the trick, assuming you're talking about TCP and the IP you want to allow is 1.2.3.4:

iptables -A INPUT -p tcp --dport 8000 -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 8000 -j DROP

How to compare two Dates without the time portion?

If you just want to compare only two dates without time, then following code might help you:

final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date dLastUpdateDate = dateFormat.parse(20111116);
Date dCurrentDate = dateFormat.parse(dateFormat.format(new Date()));
if (dCurrentDate.after(dLastUpdateDate))
{
   add your logic
}

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

Below code work for me in web.xml file

<servlet>
    <servlet-name>WebService</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.example.demo.webservice</param-value>
        //Package
    </init-param>
    <init-param>
        <param-name>unit:WidgetPU</param-name>
        <param-value>persistence/widget</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>WebService</servlet-name>
    <url-pattern>/webservices/*</url-pattern>
</servlet-mapping>

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

Got this error in Chrome with default login for ASP.NET with Individual User Accounts

.cshtml:

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Use a local account to log in.</h4>

Controller:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)

Solved by clearing site data for the site:

enter image description here

Using Java 8's Optional with Stream::flatMap

If you're stuck with Java 8 but have access to Guava 21.0 or newer, you can use Streams.stream to convert an optional into a stream.

Thus, given

import com.google.common.collect.Streams;

you can write

Optional<Other> result =
    things.stream()
        .map(this::resolve)
        .flatMap(Streams::stream)
        .findFirst();

In PANDAS, how to get the index of a known value?

There might be more than one index map to your value, it make more sense to return a list:

In [48]: a
Out[48]: 
   c1  c2
0   0   1
1   2   3
2   4   5
3   6   7
4   8   9

In [49]: a.c1[a.c1 == 8].index.tolist()
Out[49]: [4]

SyntaxError: unexpected EOF while parsing

The SyntaxError: unexpected EOF while parsing means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100): and requires at least one line afterwards that contains code that should be in it.

It seems like you were executing your program line by line in the ipython console. This works for single statements like a = 3 but not for code blocks like for loops. See the following example:

In [1]: for i in range(100):
  File "<ipython-input-1-ece1e5c2587f>", line 1
    for i in range(100):
                        ^
SyntaxError: unexpected EOF while parsing

To avoid this error, you have to enter the whole code block as a single input:

In [2]: for i in range(5):
   ...:     print(i, end=', ')
0, 1, 2, 3, 4,

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

From Docker docs:

ADD or COPY

Although ADD and COPY are functionally similar, generally speaking, COPY is preferred. That’s because it’s more transparent than ADD. COPY only supports the basic copying of local files into the container, while ADD has some features (like local-only tar extraction and remote URL support) that are not immediately obvious. Consequently, the best use for ADD is local tar file auto-extraction into the image, as in ADD rootfs.tar.xz /.

More: Best practices for writing Dockerfiles

Check if one date is between two dates

Try this:

HTML

<div id="eventCheck"></div>

JAVASCRIPT

// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

// Add Zero if it number is between 0-9
if(dd<10) {
    dd = '0'+dd;
}
if(mm<10) {
    mm = '0'+mm;
}

var today = yyyy + '' + mm + '' + dd ;


// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017

// Add Zero if it number is between 0-9
if(endDay<10) {
    endDay = '0'+endDay;
} 
if(endMonth<10) {
    endMonth = '0'+endMonth;
}

// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//



// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
    document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)';  // true
} else {
    document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}

Fiddle: https://jsfiddle.net/zm75cq2a/

Table Height 100% inside Div element

to set height of table to its container I must do:

1) set "position: absolute"

2) remove redundant contents of cells (!)

Does Index of Array Exist

Assuming you also want to check if the item is not null

if (array.Length > 25 && array[25] != null)
{
    //it exists
}

VBA: How to display an error message just like the standard error message which has a "Debug" button?

For Me I just wanted to see the error in my VBA application so in the function I created the below code..

Function Database_FileRpt
'-------------------------
On Error GoTo CleanFail
'-------------------------
'
' Create_DailyReport_Action and code


CleanFail:

'*************************************

MsgBox "********************" _

& vbCrLf & "Err.Number: " & Err.Number _

& vbCrLf & "Err.Description: " & Err.Description _

& vbCrLf & "Err.Source: " & Err.Source _

& vbCrLf & "********************" _

& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _

& vbCrLf & "...Excel VBA Program Reset." _

, , "VBA Error Exception Raised!"

*************************************

 ' Note that the next line will reset the error object to 0, the variables 
above are used to remember the values
' so that the same error can be re-raised

Err.Clear

' *************************************

Resume CleanExit

CleanExit:

'cleanup code , if any, goes here. runs regardless of error state.

Exit Function  ' SUB  or Function    

End Function  ' end of Database_FileRpt

' ------------------

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

Edit 3:

Cordova Android 6.2.2 has been released and it's fully compatible with SDK tools 26.0.x and 25.3.1. Use this version:

cordova platform update [email protected]

or

cordova platform rm android
cordova platform add [email protected]

Edit 2:

There has been another Android SDK tools release (26.0.x) that is not fully compatible with cordova-android 6.2.1.

Edit: Cordova Android 6.2.1 has been released and it's now compatible with latest Android SDK.

You can update your current incompatible android platform with cordova platform update [email protected]

Or you can remove the existing platform and add the new one (will delete any manual change you did inside yourProject/platforms/android/ folder)

cordova platform rm android cordova platform add [email protected]

You have to specify the version because current CLI installs 6.1.x by default.

Old answer:

Sadly Android SDK tools 25.3.1 broke cordova-android 6.1.x

For those who don't want to downgrade the SDK tools, you can install cordova-android from github url as most of the problems are already fixed on master branch.

cordova platform add https://github.com/apache/cordova-android

how to convert string to numerical values in mongodb

Using MongoDB 4.0 and newer

You have two options i.e. $toInt or $convert. Using $toInt, follow the example below:

filterDateStage = {
    '$match': {
        'Date': {
            '$gt': '2015-04-01', 
            '$lt': '2015-04-05'
        }
    }
};

groupStage = {
    '$group': {
        '_id': '$PartnerID',
        'total': { '$sum': { '$toInt': '$moop' } }
    }
};

db.getCollection('my_collection').aggregate([
   filterDateStage,
   groupStage
])

If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use $convert instead.

Using $convert

groupStage = {
    '$group': {
        '_id': '$PartnerID',
        'total': { 
            '$sum': { 
                '$convert': { 'input': '$moop', 'to': 'int' }
            } 
        }
    }
};

Using Map/Reduce

With map/reduce you can use javascript functions like parseInt() to do the conversion. As an example, you could define the map function to process each input document: In the function, this refers to the document that the map-reduce operation is processing. The function maps the converted moop string value to the PartnerID for each document and emits the PartnerID and converted moop pair. This is where the javascript native function parseInt() can be applied:

var mapper = function () {
    var x = parseInt(this.moop);
    emit(this.PartnerID, x);
};

Next, define the corresponding reduce function with two arguments keyCustId and valuesMoop. valuesMoop is an array whose elements are the integer moop values emitted by the map function and grouped by keyPartnerID. The function reduces the valuesMoop array to the sum of its elements.

var reducer = function(keyPartnerID, valuesMoop) {
                  return Array.sum(valuesMoop);
              };

db.collection.mapReduce(
    mapper,
    reducer,
    {
        out : "example_results",
        query: { 
            Date: {
                $gt: "2015-04-01", 
                $lt: "2015-04-05"
            }
        }       
    }
 );

 db.example_results.find(function (err, docs) {
    if(err) console.log(err);
    console.log(JSON.stringify(docs));
 });

For example, with the following sample collection of documents:

/* 0 */
{
    "_id" : ObjectId("550c00f81bcc15211016699b"),
    "Date" : "2015-04-04",
    "PartnerID" : "123456",
    "moop" : "1234"
}

/* 1 */
{
    "_id" : ObjectId("550c00f81bcc15211016699c"),
    "Date" : "2015-04-03",
    "PartnerID" : "123456",
    "moop" : "24"
}

/* 2 */
{
    "_id" : ObjectId("550c00f81bcc15211016699d"),
    "Date" : "2015-04-02",
    "PartnerID" : "123457",
    "moop" : "21"
}

/* 3 */
{
    "_id" : ObjectId("550c00f81bcc15211016699e"),
    "Date" : "2015-04-02",
    "PartnerID" : "123457",
    "moop" : "8"
}

The above Map/Reduce operation will save the results to the example_results collection and the shell command db.example_results.find() will give:

/* 0 */
{
    "_id" : "123456",
    "value" : 1258
}

/* 1 */
{
    "_id" : "123457",
    "value" : 29
}

How to make an HTTP request + basic auth in Swift

go plain for SWIFT 3 and APACHE simple Auth:

func urlSession(_ session: URLSession, task: URLSessionTask,
                didReceive challenge: URLAuthenticationChallenge,
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    let credential = URLCredential(user: "test",
                                   password: "test",
                                   persistence: .none)

    completionHandler(.useCredential, credential)


}

Making authenticated POST requests with Spring RestTemplate for Android

Very useful I had a slightly different scenario where I the request xml was itself the body of the POST and not a param. For that the following code can be used - Posting as an answer just in case anyone else having similar issue will benefit.

    final HttpHeaders headers = new HttpHeaders();
    headers.add("header1", "9998");
    headers.add("username", "xxxxx");
    headers.add("password", "xxxxx");
    headers.add("header2", "yyyyyy");
    headers.add("header3", "zzzzz");
    headers.setContentType(MediaType.APPLICATION_XML);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    final HttpEntity<MyXmlbeansRequestDocument> httpEntity = new HttpEntity<MyXmlbeansRequestDocument>(
            MyXmlbeansRequestDocument.Factory.parse(request), headers);
    final ResponseEntity<MyXmlbeansResponseDocument> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity,MyXmlbeansResponseDocument.class);
    log.info(responseEntity.getBody());

How can I group by date time column without taking time into consideration

In pre Sql 2008 By taking out the date part:

GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)

Is a Java hashmap search really O(1)?

Only in theoretical case, when hashcodes are always different and bucket for every hash code is also different, the O(1) will exist. Otherwise, it is of constant order i.e. on increment of hashmap, its order of search remains constant.

Maven command to determine which settings.xml file Maven is using

You can use the maven help plugin to tell you the contents of your user and global settings files.

mvn help:effective-settings

will ask maven to spit out the combined global and user settings.

How can I encode a string to Base64 in Swift?

SwiftyBase64 (full disclosure: I wrote it) is a native Swift Base64 encoding (no decoding library. With it, you can encode standard Base64:

let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode)

or URL and Filename Safe Base64:

let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode, alphabet:.URLAndFilenameSafe)

Turning Sonar off for certain code

I not be able to find squid number in sonar 5.6, with this annotation also works:

@SuppressWarnings({"pmd:AvoidCatchingGenericException", "checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck"})

How to Bulk Insert from XLSX file extension?

Create a linked server to your document

http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm

Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.

You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

How to redirect from one URL to another URL?

Why javascript?

http://www.instant-web-site-tools.com/html-redirect.html

<html>
<meta http-equiv="REFRESH" content="0;url=http://www.URL2.com"> 
</html>

Unless I'm missunderstanding...

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

  1. Open the Servers Tab from Windows ? Show View ? Servers menu

  2. Right click on the server and delete it

  3. Create a new server by going New ? Server on Server Tab

  4. Click on "Configure runtime environments…" link

  5. Select the Apache Tomcat v7.0 server and remove it. This will remove the Tomcat server configuration. This is where many people do mistake – they remove the server but do not remove the Runtime environment.

  6. Click on OK and exit the screen above now.

  7. From the screen below, choose Apache Tomcat v7.0 server and click on next button.

  8. Browse to Tomcat Installation Directory

  9. Click on Next and choose which project you would like to deploy:

  10. Click on Finish after Adding your project

  11. Now launch your server. This will fix your Server timeout or any issues with old server configuration. This solution can also be used to fix “port update not being taking place” issues.

Insert string in beginning of another string

Other answers explain how to insert a string at the beginning of another String or StringBuilder (or StringBuffer).

However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.

When you write:

String s = "Jam";
s = "Hello " + s;

you are actually causing a new String object to be created that is the concatenation of "Hello " and "Jam". You are not actually inserting characters into an existing String object at all.


1 - It is technically possible to use reflection to break abstraction on String objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String object was created explicitly via new String(...) it could be shared, or it could share internal state with other String objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final is undefined. Mutation of String objects is dangerous.

Read environment variables in Node.js

If you want to see all the Enviroment Variables on execution time just write in some nodejs file like server.js:

console.log(process.env);

Why Does OAuth v2 Have Both Access and Refresh Tokens?

Neither of these answers get to the core reason refresh tokens exist. Obviously, you can always get a new access-token/refresh-token pair by sending your client credentials to the auth server - that's how you get them in the first place.

So the sole purpose of the refresh token is to limit the use of the client credentials being sent over the wire to the auth service. The shorter the TTL of the access-token, the more often the client credentials will have to be used to obtain a new access-token, and therefore the more opportunities attackers have to compromise the client credentials (although this may be super difficult anyway if asymmetric encryption is being used to send them). So if you have a single-use refresh-token, you can make the TTL of access-tokens arbitrarily small without compromising the client credentials.

Removing duplicate rows in Notepad++

Notepad++

-> Replace window

Ensure that in Search mode you have selected the Regular expression radio button

Find what:

^(.*)(\r?\n\1)+$

Replace with:

$1

Before:

and we think there

and we think there

single line

Is it possible to

Is it possible to

After:

and we think there

single line

Is it possible to

How to drop all user tables?

If you just want a really simple way to do this.. Heres a script I have used in the past

select 'drop table '||table_name||' cascade constraints;' from user_tables;

This will print out a series of drop commands for all tables in the schema. Spool the result of this query and execute it.

Source: https://forums.oracle.com/forums/thread.jspa?threadID=614090

Likewise if you want to clear more than tables you can edit the following to suit your needs

select 'drop '||object_type||' '|| object_name || ';' from user_objects where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION', 'INDEX')

Pygame Drawing a Rectangle

import pygame, sys
from pygame.locals import *

def main():
    pygame.init()

    DISPLAY=pygame.display.set_mode((500,400),0,32)

    WHITE=(255,255,255)
    BLUE=(0,0,255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

main()

This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect to go about this, and you add the DISPLAY constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.

Look up pygame.org for more info

How to check whether a int is not null or empty?

int cannot be null. If you are not assigning any value to int default value will be 0. If you want to check for null then make int as Integer in declaration. Then Integer object can be null. So, you can check where it is null or not. Even in javax bean validation you won't be able to get error for @NotNull annotation until the variable is declared as Integer.

What are native methods in Java and where should they be used?

I like to know where does we use Native Methods

Ideally, not at all. In reality some functionality is not available in Java and you have to call some C code.

The methods are implemented in C code.

Python to print out status bar and percentage

Easiest is still

import sys
total_records = 1000
for i in range (total_records):
    sys.stdout.write('\rUpdated record: ' + str(i) + ' of ' + str(total_records))
    sys.stdout.flush()

Key is to convert the integer type to string.

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

Start ssh-agent on login

Please go through this article. You may find this very useful:

http://mah.everybody.org/docs/ssh

Just in case the above link vanishes some day, I am capturing the main piece of the solution below:

This solution from Joseph M. Reagle by way of Daniel Starin:

Add this following to your .bash_profile

SSH_ENV="$HOME/.ssh/agent-environment"

function start_agent {
    echo "Initialising new SSH agent..."
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
    echo succeeded
    chmod 600 "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    /usr/bin/ssh-add;
}

# Source SSH settings, if applicable

if [ -f "${SSH_ENV}" ]; then
    . "${SSH_ENV}" > /dev/null
    #ps ${SSH_AGENT_PID} doesn't work under cywgin
    ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
        start_agent;
    }
else
    start_agent;
fi

This version is especially nice since it will see if you've already started ssh-agent and, if it can't find it, will start it up and store the settings so that they'll be usable the next time you start up a shell.

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

When I changed 'iOS Deployment Target' from 'IOS 10.0' to current one (my phone's) 'iOS 10.2', the problem was gone for me.

Building Settings>Deployment>iOS Deployment Target

Entity framework left join

adapted from MSDN, how to left join using EF 4

var query = from u in usergroups
            join p in UsergroupPrices on u.UsergroupID equals p.UsergroupID into gj
            from x in gj.DefaultIfEmpty()
            select new { 
                UsergroupID = u.UsergroupID,
                UsergroupName = u.UsergroupName,
                Price = (x == null ? String.Empty : x.Price) 
            };

The program can't start because MSVCR110.dll is missing from your computer

This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#

div inside php echo

You can do the following:

echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';

If you want to have it inside your statement, do this:

if($cart->count_product > 0) 
{
    echo '<div class="my_class">'.$cart->count_product.'</div>';
}

You don't need the else statement, since you're only going to output the above when it's truthy anyway.

Can I limit the length of an array in JavaScript?

arr.length = Math.min(arr.length, 5)

IF...THEN...ELSE using XML

Personally, I would prefer

<IF>
  <TIME from="5pm" to="9pm" />
  <THEN>
    <!-- action -->
  </THEN>
  <ELSE>
    <!-- action -->
  </ELSE>
</IF>

In this way you don't need an id attribute to tie together the IF, THEN, ELSE tags

Find the number of downloads for a particular app in apple appstore

found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:

d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Just my 2 Cents here ..

Bootstrap.yml or Bootstrap.properties is used to fetch the config from Spring Cloud Server.

For Example, in My Bootstrap.properties file I have the following Config

spring.application.name=Calculation-service
spring.cloud.config.uri=http://localhost:8888

On starting the application , It tries to fetch the configuration for the service by connecting to http://localhost:8888 and looks at Calculation-service.properties present in Spring Cloud Config server

You can validate the same from logs of Calcuation-Service when you start it up

INFO 10988 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888

Change one value based on another value in pandas

df['FirstName']=df['ID'].apply(lambda x: 'Matt' if x==103 else '')
df['LastName']=df['ID'].apply(lambda x: 'Jones' if x==103 else '')

When to use AtomicReference in Java?

You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.

  1. You can create a copy of the shared object
  2. Modify the shared object
  3. You need to check that the shared object is still the same as before - if yes, then update with the reference of the modified copy.

As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

ALTER TABLE add constraint

alter table User 
    add constraint userProperties
    foreign key (properties)
    references Properties(ID)

Find and replace Android studio

Try using: Edit -> Find -> Replace in path...

How to call another components function in angular2

Component 1(child):

@Component(
  selector:'com1'
)
export class Component1{
  function1(){...}
}

Component 2(parent):

@Component(
  selector:'com2',
  template: `<com1 #component1></com1>`
)
export class Component2{
  @ViewChild("component1") component1: Component1;

  function2(){
    this.component1.function1();
  }
}

Convert List<DerivedClass> to List<BaseClass>

I personally like to create libs with extensions to the classes

public static List<TTo> Cast<TFrom, TTo>(List<TFrom> fromlist)
  where TFrom : class 
  where TTo : class
{
  return fromlist.ConvertAll(x => x as TTo);
}

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

Pandas column of lists, create a row for each list element

Very late answer but I want to add this:

A fast solution using vanilla Python that also takes care of the sample_num column in OP's example. On my own large dataset with over 10 million rows and a result with 28 million rows this only takes about 38 seconds. The accepted solution completely breaks down with that amount of data and leads to a memory error on my system that has 128GB of RAM.

df = df.reset_index(drop=True)
lstcol = df.lstcol.values
lstcollist = []
indexlist = []
countlist = []
for ii in range(len(lstcol)):
    lstcollist.extend(lstcol[ii])
    indexlist.extend([ii]*len(lstcol[ii]))
    countlist.extend([jj for jj in range(len(lstcol[ii]))])
df = pd.merge(df.drop("lstcol",axis=1),pd.DataFrame({"lstcol":lstcollist,"lstcol_num":countlist},
index=indexlist),left_index=True,right_index=True).reset_index(drop=True)

Regular expression for validating names and surnames?

A very contentious subject that I seem to have stumbled along here. However sometimes it's nice to head dear little-bobby tables off at the pass and send little Robert to the headmasters office along with his semi-colons and SQL comment lines --.

This REGEX in VB.NET includes regular alphabetic characters and various circumflexed european characters. However poor old James Mc'Tristan-Smythe the 3rd will have to input his pedigree in as the Jim the Third.

<asp:RegularExpressionValidator ID="RegExValid1" Runat="server"
                    ErrorMessage="ERROR: Please enter a valid surname<br/>" SetFocusOnError="true" Display="Dynamic"
                    ControlToValidate="txtSurname" ValidationGroup="MandatoryContent"
                    ValidationExpression="^[A-Za-z'\-\p{L}\p{Zs}\p{Lu}\p{Ll}\']+$">

How to call a stored procedure from Java and JPA

For me, only the following worked with Oracle 11g and Glassfish 2.1 (Toplink):

Query query = entityManager.createNativeQuery("BEGIN PROCEDURE_NAME(); END;");
query.executeUpdate();

The variant with curly braces resulted in ORA-00900.

WebDriver - wait for element using Java

Above wait statement is a nice example of Explicit wait.

As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).

By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.

How to update nested state properties in React

I found this to work for me, having a project form in my case where for example you have an id, and a name and I'd rather maintain state for a nested project.

return (
  <div>
      <h2>Project Details</h2>
      <form>
        <Input label="ID" group type="number" value={this.state.project.id} onChange={(event) => this.setState({ project: {...this.state.project, id: event.target.value}})} />
        <Input label="Name" group type="text" value={this.state.project.name} onChange={(event) => this.setState({ project: {...this.state.project, name: event.target.value}})} />
      </form> 
  </div>
)

Let me know!

Git commit -a "untracked files"?

If you are having problems with untracked files, this 3-line script will help you.

git rm -r --cached .
git add -A
git commit -am 'fix'

Then just git push

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Search and get a line in Python

items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:

you can also get the line if there are other characters before token

items=re.findall("^.*token.*$",s,re.MULTILINE)

The above works like grep token on unix and keyword 'in' or .contains in python and C#

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''

http://pythex.org/ matches the following 2 lines

....
....
token qwerty

Remove carriage return in Unix

If you are running an X environment and have a proper editor (visual studio code), then I would follow the reccomendation:

Visual Studio Code: How to show line endings

Just go to the bottom right corner of your screen, visual studio code will show you both the file encoding and the end of line convention followed by the file, an just with a simple click you can switch that around.

Just use visual code as your replacement for notepad++ on a linux environment and you are set to go.

Change drive in git bash for windows

How I do it in Windows 10

Go to your folder directory you want to open in git bash like so

enter image description here

After you have reached the folder simply type git bash in the top navigation area like so and hit enter.

enter image description here

A git bash for the destined folder will open for you.

enter image description here

Hope that helps.

How to measure time taken by a function to execute

Stopwatch with cumulative cycles

Works with server and client (Node or DOM), uses the Performance API. Good when you have many small cycles e.g. in a function called 1000 times that processes 1000 data objects but you want to see how each operation in this function adds up to the total.

So this one uses a module global (singleton) timer. Same as a class singleton pattern, just a bit simpler to use, but you need to put this in a separate e.g. stopwatch.js file.

const perf = typeof performance !== "undefined" ? performance : require('perf_hooks').performance;
const DIGITS = 2;

let _timers = {};

const _log = (label, delta?) => {
    if (_timers[label]) {
        console.log(`${label}: ` + (delta ? `${delta.toFixed(DIGITS)} ms last, ` : '') +
            `${_timers[label].total.toFixed(DIGITS)} ms total, ${_timers[label].cycles} cycles`);
    }
};

export const Stopwatch = {
    start(label) {
        const now = perf.now();
        if (_timers[label]) {
            if (!_timers[label].started) {
                _timers[label].started = now;
            }
        } else {
            _timers[label] = {
                started: now,
                total: 0,
                cycles: 0
            };
        }
    },
    /** Returns total elapsed milliseconds, or null if stopwatch doesn't exist. */
    stop(label, log = false) {
        const now = perf.now();
        if (_timers[label]) {
            let delta;
            if(_timers[label].started) {
                delta = now - _timers[label].started;
                _timers[label].started = null;
                _timers[label].total += delta;
                _timers[label].cycles++;
            }
            log && _log(label, delta);
            return _timers[label].total;
        } else {
            return null;
        }
    },
    /** Logs total time */
    log: _log,
    delete(label) {
        delete _timers[label];
    }
};

Drawing Isometric game worlds

Either way gets the job done. I assume that by zigzag you mean something like this: (numbers are order of rendering)

..  ..  01  ..  ..
  ..  06  02  ..
..  11  07  03  ..
  16  12  08  04
21  17  13  09  05
  22  18  14  10
..  23  19  15  ..
  ..  24  20  ..
..  ..  25  ..  ..

And by diamond you mean:

..  ..  ..  ..  ..
  01  02  03  04
..  05  06  07  ..
  08  09  10  11
..  12  13  14  ..
  15  16  17  18
..  19  20  21  ..
  22  23  24  25
..  ..  ..  ..  ..

The first method needs more tiles rendered so that the full screen is drawn, but you can easily make a boundary check and skip any tiles fully off-screen. Both methods will require some number crunching to find out what is the location of tile 01. In the end, both methods are roughly equal in terms of math required for a certain level of efficiency.

Get path from open file in Python

And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os Python module.

>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'

This way you can get hold of the directory structure.

Connect to mysql on Amazon EC2 from a remote server

Though this question seems to be answered, another common issue that you can get is the DB user has been mis-configured. This is a mysql administration and permissions issue:

  1. EC2_DB launched with IP 10.55.142.100
  2. EC2_web launched with IP 10.55.142.144
  3. EC2_DB and EC2_WEBare in the same security group with access across your DB port (3306)
  4. EC2_DB has a mysql DB that can be reached locally by the DB root user ('root'@'localhost')
  5. EC2_DB mysql DB has a remote user 'my_user'@'%' IDENTIFIED BY PASSWORD 'password'
  6. A bash call to mysql from EC2_WEB fails: mysql -umy_user -p -h ip-10-55-142-100.ec2.internal as does host references to the explicit IP, public DNS, etc.

Step 6 fails because the mysql DB has the wrong user permisions. It needs this:

GRANT ALL PRIVILEGES ON *.* TO 'my_user'@'ip-10-55-142-144.ec2.internal' IDENTIFIED BY PASSWORD 'password'

I would like to think that % would work for any remote server, but I did not find this to be the case.

Please let me know if this helps you.

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

If you are using a fragment and using an AlertDialog / Toast message, use getActivity() in the context parameter.

Worked for me.

Cheers!

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had approximately the same problem with Laravel 5.5 on ubuntu, finally i've found a solution here to switch between the versions of php used by apache :

  1. sudo a2dismod php5
  2. sudo a2enmod php7.1
  3. sudo service apache2 restart

and it works

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

Return different type of data from a method in java?

@ruchira ur solution it self is best.But i think if it is only about integer and a string we can do it in much easy and simple way..

 class B {   
    public String myfun() {         
        int a=2;           //Integer .. you could use scanner or pass parameters ..i have simply assigned
        String b="hi";      //String
        return Integer.toString(a)+","+b; //returnig string and int with "," in middle          
    }       
}

class A {    
    public static void main(String args[]){

        B obj=new B();  // obj of class B with myfun() method  
        String returned[]=obj.myfun().split(",");
             //splitting integer and string values with "," and storing them in array   
        int b1=Integer.parseInt(returned[0]); //converting first value in array to integer.    
        System.out.println(returned[0]); //printing integer    
        System.out.println(returned[1]); //printing String
    }
}

i hope it was useful.. :)

Android ADB commands to get the device properties

adb shell getprop ro.build.version.sdk

If you want to see the whole list of parameters just type:

adb shell getprop

How to force div to appear below not next to another?

Float the #list and #similar the right and add clear: right; to #similar

Like so:

#map { float:left; width:700px; height:500px; }
#list { float:right; width:200px; background:#eee; list-style:none; padding:0; }
#similar { float:right; width:200px; background:#000; clear:right; } 


<div id="map"></div>        
<ul id="list"></ul>
<div id="similar">this text should be below, not next to ul.</div>

You might need a wrapper(div) around all of them though that's the same width of the left and right element.

matplotlib get ylim values

It's an old question, but I don't see mentioned that, depending on the details, the sharey option may be able to do all of this for you, instead of digging up axis limits, margins, etc. There's a demo in the docs that shows how to use sharex, but the same can be done with y-axes.

Maven: How to rename the war file for the project?

Lookup pom.xml > project tag > build tag.

I would like solution below.

<artifactId>bird</artifactId>
<name>bird</name>

<build>
    ...
    <finalName>${project.artifactId}</finalName>
  OR
    <finalName>${project.name}</finalName>
    ...
</build>

Worked for me. ^^

css 'pointer-events' property alternative for IE

You can also just "not" add a url inside the <a> tag, i do this for menus that are <a> tag driven with drop downs as well. If there is not drop down then i add the url but if there are drop downs with a <ul> <li> list i just remove it.

How to delete all records from table in sqlite with Android?

To delete all the rows within the table you can use:

db.delete(TABLE_NAME, null, null);

Using $_POST to get select option value from HTML

Like this:

<?php
  $option = $_POST['taskOption'];
?>

The index of the $_POST array is always based on the value of the name attribute of any HTML input.

C++ - Hold the console window open?

A more appropriate method is to use std::cin.ignore:

#include <iostream>

void Pause()
{
   std::cout << "Press Enter to continue...";
   std::cout.flush();
   std::cin.ignore(10000, '\n');
   return;
}

Markdown and image alignment

Embedding CSS is bad:

![Flowers](/flowers.jpeg)

CSS in another file:

img[alt=Flowers] { float: right; }

HttpClient.GetAsync(...) never returns when using await/async

I was using to many await, so i was not getting response , i converted in to sync call its started working

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Method = HttpMethod.Get;
                request.RequestUri = new Uri(URL);
                var response = client.GetAsync(URL).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;
               

CSS scale height to match width - possibly with a formfactor

Here it is. Pure CSS. You do need one extra 'container' element.

The fiddle

(tinkerbin, actually): http://tinkerbin.com/rQ71nWDT (Tinkerbin is dead.)

The solution.

Note I'm using an 100% throughout the example. You can use whichever percentage you'd like.

Since height percentages are relative to the height of the parent element, we can't rely on it. We must rely on something else. Luckily padding is relative to the width - whether it's horizontal or vertical padding. In padding-xyz: 100%, 100% equals 100% of the box's width.

Unfortunately, padding is just that, padding. The content-box's height is 0. No problem!

Stick an absolutely positioned element, give it 100% width, 100% height and use it as your actual content box. The 100% height works because percentage heights on absolutely positioned elements are relative to the padding-box of the box their relatively positioned to.

HTML:

<div id="map_container">
  <div id="map">
  </div>
</div>   

CSS:

#map_container {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
}

#map {
  position: absolute;
  width: 100%;
  height: 100%;
}

PostgreSQL: how to convert from Unix epoch to date?

On Postgres 10:

SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)

intelliJ IDEA 13 error: please select Android SDK

I had the same problem as you did when I also updated from intellij Idea 12 to 13. In my situation, my Android SDK's Build target wasn't recognized properly, it said something like "Not set" in red instead Android 2.2. Even though I chose Android 2.2 and clicked apply and OK, it showed the "Not set" message again when I reopened the project structure dialog.

Then I chose an other version, Android 4.0 this time, clicked apply, then chose Android 2.2 again, clicked apply. This worked for me.

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

Stop wasting your time, just add the following encoding="cp437" and errors='ignore' to your code in both read and write:

open('filename.csv', encoding="cp437", errors='ignore')
open(file_name, 'w', newline='', encoding="cp437", errors='ignore')

Godspeed

Search for string within text column in MySQL

Why not use LIKE?

SELECT * FROM items WHERE items.xml LIKE '%123456%'

What is the difference between functional and non-functional requirements?

A functional requirement describes what a software system should do, while non-functional requirements place constraints on how the system will do so.

Let me elaborate.

An example of a functional requirement would be:

  • A system must send an email whenever a certain condition is met (e.g. an order is placed, a customer signs up, etc).

A related non-functional requirement for the system may be:

  • Emails should be sent with a latency of no greater than 12 hours from such an activity.

The functional requirement is describing the behavior of the system as it relates to the system's functionality. The non-functional requirement elaborates a performance characteristic of the system.

Typically non-functional requirements fall into areas such as:

  • Accessibility
  • Capacity, current and forecast
  • Compliance
  • Documentation
  • Disaster recovery
  • Efficiency
  • Effectiveness
  • Extensibility
  • Fault tolerance
  • Interoperability
  • Maintainability
  • Privacy
  • Portability
  • Quality
  • Reliability
  • Resilience
  • Response time
  • Robustness
  • Scalability
  • Security
  • Stability
  • Supportability
  • Testability

A more complete list is available at Wikipedia's entry for non-functional requirements.

Non-functional requirements are sometimes defined in terms of metrics (i.e. something that can be measured about the system) to make them more tangible. Non-functional requirements may also describe aspects of the system that don't relate to its execution, but rather to its evolution over time (e.g. maintainability, extensibility, documentation, etc.).

How do I test if a string is empty in Objective-C?

check this :

if ([yourString isEqualToString:@""])
{
    NsLog(@"Blank String");
}

Or

if ([yourString length] == 0)
{
    NsLog(@"Blank String");
}

Hope this will help.

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You should have a table with the list of emails to check. Then do this query:

SELECT E.Email, CASE WHEN U.Email IS NULL THEN 'Not Exists' ELSE 'Exists' END Status
FROM EmailsToCheck E
LEFT JOIN (SELECT DISTINCT Email FROM Users) U
ON E.Email = U.Email

Java - get the current class name?

In your example, this probably refers to an anonymous class instance. Java gives a name to those classes by appending a $number to the name of the enclosing class.

Find distance between two points on map using Google Map API V2

@salman khan what Usman Kurd suggested is perfect. Only thing i found which can be corrected is that "For google maps v2 we use LatLng class. So below is the code of Usman Kurd that can be used for Google Maps v2. I checked it works perfect.

public double CalculationByDistance(LatLng StartP, LatLng EndP) {
        int Radius=6371;//radius of earth in Km         
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        double dLat = Math.toRadians(lat2-lat1);
        double dLon = Math.toRadians(lon2-lon1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult= Radius*c;
        double km=valueResult/1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec =  Integer.valueOf(newFormat.format(km));
        double meter=valueResult%1000;
        int  meterInDec= Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value",""+valueResult+"   KM  "+kmInDec+" Meter   "+meterInDec);

        return Radius * c;
     }

Difference between Hive internal tables and external tables?

In simple words, there are two things:

Hive can manage things in warehouse i.e. it will not delete data out of warehouse. When we delete table:

1) For internal tables the data is managed internally in warehouse. So will be deleted.

2) For external tables the data is managed eternal from warehouse. So can't be deleted and clients other then hive can also use it.

How do I exit a WPF application programmatically?

To exit your application you can call

System.Windows.Application.Current.Shutdown();

As described in the documentation to the Application.Shutdown method you can also modify the shutdown behavior of your application by specifying a ShutdownMode:

Shutdown is implicitly called by Windows Presentation Foundation (WPF) in the following situations:

  • When ShutdownMode is set to OnLastWindowClose.
  • When the ShutdownMode is set to OnMainWindowClose.
  • When a user ends a session and the SessionEnding event is either unhandled, or handled without cancellation.

Please also note that Application.Current.Shutdown(); may only be called from the thread that created the Application object, i.e. normally the main thread.

Using a Loop to add objects to a list(python)

Auto-incrementing the index in a loop:

myArr[(len(myArr)+1)]={"key":"val"}

What "wmic bios get serialnumber" actually retrieves?

wmic bios get serialnumber     

if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)

I had to do exactly that.:):)

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Go to the following setting:

Window -> Preferences -> Java-Compiler-Errors/Warnings-Deprecated and restricted API-Forbidden reference (access rules)

Set it to Warning or Ignore.

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

apt-get for Cygwin?

This got it working for me:

curl https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg > \
apt-cyg && install apt-cyg /bin

How to start a stopped Docker container with a different command?

Edit this file (corresponding to your stopped container):

vi /var/lib/docker/containers/923...4f6/config.json

Change the "Path" parameter to point at your new command, e.g. /bin/bash. You may also set the "Args" parameter to pass arguments to the command.

Restart the docker service (note this will stop all running containers):

service docker restart

List your containers and make sure the command has changed:

docker ps -a

Start the container and attach to it, you should now be in your shell!

docker start -ai mad_brattain

Worked on Fedora 22 using Docker 1.7.1.

NOTE: If your shell is not interactive (e.g. you did not create the original container with -it option), you can instead change the command to "/bin/sleep 600" or "/bin/tail -f /dev/null" to give you enough time to do "docker exec -it CONTID /bin/bash" as another way of getting a shell.

NOTE2: Newer versions of docker have config.v2.json, where you will need to change either Entrypoint or Cmd (thanks user60561).

Laravel password validation rule

This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:

    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }

Would output:

    [
        'The email must be a valid email address.',
        'The password must be at least 10 characters.',
        'The password format is invalid.',
    ]

(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)

git status shows modifications, git checkout -- <file> doesn't remove them

I solved it this way:

  1. Copy the contents of the correct code you want
  2. Delete the file that is causing the problem ( the one that you can't revert ) from your disk. now you should find both versions of the same file marked as being deleted.
  3. Commit the deletion of the files.
  4. Create the file again with the same name and paste in the correct code you have copied in step 1
  5. commit the creation of the new file.

That's what worked for me.

java.lang.RuntimeException: Uncompilable source code - what can cause this?

I had the same problem. My error was the packaging. So I would suggest you first check the package name and if the class is in the correct package.

test attribute in JSTL <c:if> tag

<%=%> by itself will be sent to the output, in the context of the JSTL it will be evaluated to a string

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Difference between web reference and service reference?

The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.

You can access web references via the advanced options in add service reference (if I recall correctly).

I'd use service reference because as I understand it, it's the newer mechanism of the two.

Check if input is number or letter javascript

A better(error-free) code would be like:

function isReallyNumber(data) {
    return typeof data === 'number' && !isNaN(data);
}

This will handle empty strings as well. Another reason, isNaN("12") equals to false but "12" is a string and not a number, so it should result to true. Lastly, a bonus link which might interest you.

Where can I download Eclipse Android bundle?

You don't actually need the bundle as the ADT can be used with just any latest Eclipse IDE.


1. Make sure you have JDK installed.

  1. Download latest eclipse.

  2. Download latest ADT plugin ADT-XX.X.X.zip. As of this answer the current version is ADT-23.0.7.zip (More versions at http://developer.android.com/tools/sdk/eclipse-adt.html)

  3. Open Eclipse and follow the following steps:

    • Open Help > Install New Software > Add > Archive
    • Navigate to where you downloaded your ADT plugin and select it.
    • Check Developer Tools, click Next, accept any licenses and Finish
  4. After restarting Eclipse, if you are not able to open a layout file go to step 4 but instead of selecting archive add https://dl-ssl.google.com/android/eclipse/ in the Location: textbox. Press Ok, update the ADT and restart Eclipse. Close and reopen the layout files and you'll be good to go.

  5. Run the Android SDK Manager to update its components.


EDIT: The ADT plugin has long since been deprecated. For more information visit this link:

https://developer.android.com/studio/tools/sdk/eclipse-adt.html

Edit In Place Content Editing

Since this is a common piece of functionality it's a good idea to write a directive for this. In fact, someone already did that and open sourced it. I used editablespan library in one of my projects and it worked perfectly, highly recommended.