Programs & Examples On #Emailrelay

How to randomly select an item from a list?

We can also do this using randint.

from random import randint
l= ['a','b','c']

def get_rand_element(l):
    if l:
        return l[randint(0,len(l)-1)]
    else:
        return None

get_rand_element(l)

Could not load file or assembly 'System.Web.Mvc'

I am using Jenkins with .net projects and had troubles with MVC 4 references.

I finallys solved my issue by using a .Net reference search engine functionality based on the registry using :

"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v2.0.50727\AssemblyFoldersEx"

You can create subkey et set the default key to "c:\myreferenceedir" for example.

It saved me with MVC versions and also ASP.net Web pages.

Usefull to add references to the "Add Reference Dialog"

http://dhakshinamoorthy.wordpress.com/2011/12/04/how-to-register-your-net-assembly-in-gac-and-make-it-show-in-add-reference-dialog/

Trying to get property of non-object - Laravel 5

I had also this problem. Add code like below in the related controller (e.g. UserController)

$users = User::all();
return view('mytemplate.home.homeContent')->with('users',$users);

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

select * from temptable
where rnum --unique key
 in 

( 
 SELECT RNUM --unique key
  FROM temptable
 WHERE (  HistoryStatus
) IN (SELECT                HistoryStatus

                             FROM temptable
                            GROUP BY                
HistoryStatus 
                           HAVING COUNT(*) <= 1));

I have not tested this code. I have used similar code and it works. The syntax is in Oracle.

How to add new line in Markdown presentation?

You could use &nbsp; in R markdown to create a new blank line.

For example, in your .Rmd file:

I want 3 new lines: 

&nbsp;
&nbsp;
&nbsp;

End of file. 

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

Set Windows process (or user) memory limit

Use the Application Verifier (AppVerifier) tool from Microsoft.

In my case I need to simulate memory no longer being available so I did the following in the tool:

  1. Added my application
  2. Unchecked Basic
  3. Checked Low Resource Simulation
    • Changed TimeOut to 120000 - my application will run normally for 2 minutes before anything goes into effect.
    • Changed HeapAlloc to 100 - 100% chance of heap allocation error
    • Set Stacks to true - the stack will not be able to grow any larger
  4. Save
  5. Start my application

After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.

Command line .cmd/.bat script, how to get directory of running script

This is equivalent to the path of the script:

%~dp0

This uses the batch parameter extension syntax. Parameter 0 is always the script itself.

If your script is stored at C:\example\script.bat, then %~dp0 evaluates to C:\example\.

ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:

You can get the value of any parameter using a % followed by it's numerical position on the command line.

[...]

When a parameter is used to supply a filename then the following extended syntax can be applied:

[...]

%~d1 Expand %1 to a Drive letter only - C:

[...]

%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.

[...]

The modifiers above can be combined:

%~dp1 Expand %1 to a drive letter and path only

[...]

You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\

How can I get terminal output in python?

You can use Popen in subprocess as they suggest.

with os, which is not recomment, it's like below:

import os
a  = os.popen('pwd').readlines()

WebAPI to Return XML

If you return a serializable object, WebAPI will automatically send JSON or XML based on the Accept header that your client sends.

If you return a string, you'll get a string.

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Got this error because I had the Data Source Name in User DSN instead of System DSN enter image description here

Why doesn't JavaScript support multithreading?

Multi-threading with javascript is clearly possible using webworkers bring by HTML5.

Main difference between webworkers and a standard multi-threading environment is memory resources are not shared with the main thread, a reference to an object is not visible from one thread to another. Threads communicate by exchanging messages, it is therefore possible to implement a synchronzization and concurrent method call algorithm following an event-driven design pattern.

Many frameworks exists allowing to structure programmation between threads, among them OODK-JS, an OOP js framework supporting concurrent programming https://github.com/GOMServices/oodk-js-oop-for-js

How to place two divs next to each other?

It is very easy - you could do it the hard way

_x000D_
_x000D_
.clearfix:after {_x000D_
   content: " "; _x000D_
   visibility: hidden;_x000D_
   display: block;_x000D_
   height: 0;_x000D_
   clear: both;_x000D_
}_x000D_
_x000D_
#first, #second{_x000D_
  box-sizing: border-box;_x000D_
  -moz-box-sizing: border-box;_x000D_
  -webkit-box-sizing: border-box;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
    width: 500px;_x000D_
    border: 1px solid black;_x000D_
}_x000D_
#first {_x000D_
    border: 1px solid red;_x000D_
    float:left;_x000D_
    width:50%;_x000D_
}_x000D_
#second {_x000D_
    border: 1px solid green;_x000D_
    float:left;_x000D_
    width:50%;_x000D_
}
_x000D_
<div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
    <div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

or the easy way

_x000D_
_x000D_
#wrapper {_x000D_
  display: flex;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#first {_x000D_
    border: 1px solid red;_x000D_
}_x000D_
#second {_x000D_
    border: 1px solid green;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
    <div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
    <div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

There's also like a million other ways.
But I'd just with the easy way. I would also like to tell you that a lot of the answers here are incorrect But both the ways that I have shown at least work in HTML 5.

android edittext onchange listener

 myTextBox.addTextChangedListener(new TextWatcher() {  

    public void afterTextChanged(Editable s) {}  

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 

    public void onTextChanged(CharSequence s, int start, int before, int count) {  

    TextView myOutputBox = (TextView) findViewById(R.id.myOutputBox);  
    myOutputBox.setText(s);  

    }  
});  

How to diff one file to an arbitrary version in Git?

git diff master~20 -- pom.xml

Works if you are not in master branch too.

How do you change the launcher logo of an app in Android Studio?

Look in the application's AndroidManifest.xml file for the <application> tag.

This application tag has an android:icon attribute, which is usually @drawable/ic_launcher. The value here is the name of the launcher icon file. If the value is @drawable/ic_launcher, then the name of the icon is ic_launcher.png.

Find this icon in your resource folders (res/mipmap-mdpi, res/mipmap-hdpi, etc.) and replace it.

A note on mipmap resources: If your launcher icon is currently in drawable folders such as res/drawable-hdpi, you should move them to the mipmap equivalents (e.g. res/mipmap-hdpi). Android will better preserve the resolution of drawables in the mipmap folder for display in launcher applications.

Android Studio note: If you are using Android Studio you can let studio place the drawables in the correct place for you. Simply right click on your application module and click New -> Image Asset.

For the icon type select either "Launcher Icons (Legacy Only)" for flat PNG files or "Launcher Icons (Adaptive and Legacy)" if you also want to generate an adaptive icon for API 26+ devices.

How may I reference the script tag that loaded the currently-executing script?

Consider this algorithm. When your script loads (if there are multiple identical scripts), look through document.scripts, find the first script with the correct "src" attribute, and save it and mark it as 'visited' with a data-attribute or unique className.

When the next script loads, scan through document.scripts again, passing over any script already marked as visited. Take the first unvisited instance of that script.

This assumes that identical scripts will likely execute in the order in which they are loaded, from head to body, from top to bottom, from synchronous to asynchronous.

(function () {
  var scripts = document.scripts;

  // Scan for this data-* attribute
  var dataAttr = 'data-your-attribute-here';

  var i = 0;
  var script;
  while (i < scripts.length) {
    script = scripts[i];
    if (/your_script_here\.js/i.test(script.src)
        && !script.hasAttribute(dataAttr)) {

        // A good match will break the loop before
        // script is set to null.
        break;
    }

    // If we exit the loop through a while condition failure,
    // a check for null will reveal there are no matches.
    script = null;
    ++i;
  }

  /**
   * This specific your_script_here.js script tag.
   * @type {Element|Node}
   */
  var yourScriptVariable = null;

  // Mark the script an pass it on.
  if (script) {
    script.setAttribute(dataAttr, '');
    yourScriptVariable = script;
  }
})();

This will scan through all the script for the first matching script that isn't marked with the special attribute.

Then mark that node, if found, with a data-attribute so subsequent scans won't choose it. This is similar to graph traversal BFS and DFS algorithms where nodes may be marked as 'visited' to prevent revisitng.

Why does dividing two int not yield the right value when assigned to double?

This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.

When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).

In this case you have double var = integer result which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).

If you'd like to keep the result as a double you're going to want to create a situation where you have double var = double result

The easiest way to do that is to force the expression on the right side of an equation to cast to double:

c = a/(double)b

Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).

After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.

AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.

How to access the content of an iframe with jQuery?

If iframe's source is an external domain, browsers will hide the iframe contents (Same Origin Policy). A workaround is saving the external contents in a file, for example (in PHP):

<?php
    $contents = file_get_contents($external_url);
    $res = file_put_contents($filename, $contents);
?>

then, get the new file content (string) and parse it to html, for example (in jquery):

$.get(file_url, function(string){
    var html = $.parseHTML(string);
    var contents = $(html).contents();
},'html');

How to Convert double to int in C?

This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.

double a;
a=3669.0;
int b;
b=a+ 1e-9;

Remove substring from the string

How about str.gsub("subString", "") Check out the Ruby Doc

Implementing two interfaces in a class with same method. Which interface method is overridden?

As in interface,we are just declaring methods,concrete class which implements these both interfaces understands is that there is only one method(as you described both have same name in return type). so there should not be an issue with it.You will be able to define that method in concrete class.

But when two interface have a method with the same name but different return type and you implement two methods in concrete class:

Please look at below code:

public interface InterfaceA {
  public void print();
}


public interface InterfaceB {
  public int print();
}

public class ClassAB implements InterfaceA, InterfaceB {
  public void print()
  {
    System.out.println("Inside InterfaceA");
  }
  public int print()
  {
    System.out.println("Inside InterfaceB");
    return 5;
  }
}

when compiler gets method "public void print()" it first looks in InterfaceA and it gets it.But still it gives compile time error that return type is not compatible with method of InterfaceB.

So it goes haywire for compiler.

In this way, you will not be able to implement two interface having a method of same name but different return type.

How do you find what version of libstdc++ library is installed on your linux machine?

What exactly do you want to know?

The shared library soname? That's part of the filename, libstdc++.so.6, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname.

The minor revision number? You should be able to get that by simply checking what the symlink points to:

$ ls -l  /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16

That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6 version, which corresponds to the GLIBCXX_3.4.16 symbol versions.

Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++ and libstdc++.so you can get that from:

$ g++ -dumpversion
4.6.3

Or, on most distros, you can just ask the package manager. On my Fedora host that's

$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686

As other answers have said, you can map releases to library versions by checking the ABI docs

How to disable an input box using angular.js

I created a directive for this (angular stable 1.0.8)

<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>

app.controller("myController", function(){
  $scope.editableInput = false;
});

app.directive("inputDisabled", function(){
  return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
      if(val)
        element.removeAttr("disabled");
      else
        element.attr("disabled", "disabled");
    });
  }
});

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

Accessing dictionary value by index in python

Let us take an example of dictionary:

numbers = {'first':0, 'second':1, 'third':3}

When I did

numbers.values()[index]

I got an error:'dict_values' object does not support indexing

When I did

numbers.itervalues()

to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'

Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.

tuple(numbers.items())[key_index][value_index]

for example:

tuple(numbers.items())[0][0] gives 'first'

if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use

list(list(numbers.items())[index])

How to modify the nodejs request default timeout time?

Try this:

var options = {
    url:  'http://url',
    timeout: 120000
}

request(options, function(err, resp, body) {});

Refer to request's documentation for other options.

getting the ng-object selected with ng-change

you also coud try this:

<select  ng-model="selectedItem" ng-change="update()">
   <option ng-repeat="item in items" 
         ng-selected="selectedItem == item.Id" value="{{item.Id}}">
      {{item.Name}}
   </option>
</select>

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

How do I draw a shadow under a UIView?

For fellow Xamarians, the Xamarin.iOS/C# version of the answer would look like the following:

public override void DrawRect(CGRect area, UIViewPrintFormatter formatter)
{
    CGContext currentContext = UIGraphics.GetCurrentContext();
    currentContext.SaveState();
    currentContext.SetShadow(new CGSize(-15, 20), 5);
    base.DrawRect(area, formatter);
    currentContext.RestoreState();                
}

The main difference is that you acquire an instance of CGContext on which you directly call the appropriate methods.

jQuery CSS Opacity

Try with this :

jQuery('#main').css({ opacity: 0.6 });

Reading and writing environment variables in Python?

First things first :) reading books is an excellent approach to problem solving; it's the difference between band-aid fixes and long-term investments in solving problems. Never miss an opportunity to learn. :D

You might choose to interpret the 1 as a number, but environment variables don't care. They just pass around strings:

   The argument envp is an array of character pointers to null-
   terminated strings. These strings shall constitute the
   environment for the new process image. The envp array is
   terminated by a null pointer.

(From environ(3posix).)

You access environment variables in python using the os.environ dictionary-like object:

>>> import os
>>> os.environ["HOME"]
'/home/sarnold'
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'
>>> os.environ["PATH"] = os.environ["PATH"] + ":/silly/"
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/silly/'

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.

If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.

  • To show the wait_timeout value:

SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+

| Variable_name | Value |

+---------------+-------+

| wait_timeout | 28800 |

+---------------+-------+

the value is in second, it means that non-interactive connection still up to 8 hours.

  • To change the value of "wait_timeout" variable:

SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)

After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.

How to debug a referenced dll (having pdb)

It must work. I used to debug a .exe file and a dll at the same time ! What I suggest is 1) Include the path of the dll in your B project, 2) Then compile in debug your A project 3) Control that the path points on the A dll and de pdb file.... 4)After that you start in debug the B project and if all is ok, you will be able to debug in both projects !

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

The behavior depends on which version your repository has. Subversion 1.5 allows 4 types of merge:

  1. merge sourceURL1[@N] sourceURL2[@M] [WCPATH]
  2. merge sourceWCPATH1@N sourceWCPATH2@M [WCPATH]
  3. merge [-c M[,N...] | -r N:M ...] SOURCE[@REV] [WCPATH]
  4. merge --reintegrate SOURCE[@REV] [WCPATH]

Subversion before 1.5 only allowed the first 2 formats.

Technically you can perform all merges with the first two methods, but the last two enable subversion 1.5's merge tracking.

TortoiseSVN's options merge a range or revisions maps to method 3 when your repository is 1.5+ or to method one when your repository is older.

When merging features over to a release/maintenance branch you should use the 'Merge a range of revisions' command.

Only when you want to merge all features of a branch back to a parent branch (commonly trunk) you should look into using 'Reintegrate a branch'.

And the last command -Merge two different trees- is only usefull when you want to step outside the normal branching behavior. (E.g. Comparing different releases and then merging the differenct to yet another branch)

Can I use a case/switch statement with two variables?

First, JavaScript's switch is no faster than if/else (and sometimes much slower).

Second, the only way to use switch with multiple variables is to combine them into one primitive (string, number, etc) value:

var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
    case "foo-bar": ...
    ...
}

But, personally, I would rather see a set of if/else statements.

Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.

How to get dictionary values as a generic list

Going further on the answer of Slaks, if one or more lists in your dictionary is null, a System.NullReferenceException will be thrown when calling ToList(), play safe:

List<MyType> allItems = myDico.Values.Where(x => x != null).SelectMany(x => x).ToList();

Python 3: UnboundLocalError: local variable referenced before assignment

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python 3 offers a related nonlocal statement - check that out as well.

Restore LogCat window within Android Studio

way one :

you can use bin icon in logcat enter image description here

way two: you can clear logcat after per lunch Edit Configuration > Miscellaneous

check Clear log before lunch

enter image description here

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

>=RC.5

import the RouterModule See also https://angular.io/guide/router

@NgModule({ 
  imports: [RouterModule],
  ...
})

>=RC.2

app.routes.ts

import { provideRouter, RouterConfig } from '@angular/router';

export const routes: RouterConfig = [
  ...
];

export const APP_ROUTER_PROVIDERS = [provideRouter(routes)];

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { APP_ROUTER_PROVIDERS } from './app.routes';

bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);

<=RC.1

Your code is missing

  @Component({
    ...
    directives: [ROUTER_DIRECTIVES],
    ...)}

You can't use directives like routerLink or router-outlet without making them known to your component.

While directive names were changed to be case-sensitive in Angular2, elements still use - in the name like <router-outlet> to be compatible with the web-components spec which require a - in the name of custom elements.

register globally

To make ROUTER_DIRECTIVES globally available, add this provider to bootstrap(...):

provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi: true})

then it's no longer necessary to add ROUTER_DIRECTIVES to each component.

AngularJS $http-post - convert binary to excel file and download

Just noticed you can't use it because of IE8/9 but I'll push submit anyway... maybe someone finds it useful

This can actually be done through the browser, using blob. Notice the responseType and the code in the success promise.

$http({
    url: 'your/webservice',
    method: "POST",
    data: json, //this is your json data string
    headers: {
       'Content-type': 'application/json'
    },
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    var objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);
}).error(function (data, status, headers, config) {
    //upload failed
});

There are some problems with it though like:

  1. It doesn't support IE 8 and 9:
  2. It opens a pop up window to open the objectUrl which people might have blocked
  3. Generates weird filenames

It did work!

blob The server side code in PHP I tested this with looks like this. I'm sure you can set similar headers in Java:

$file = "file.xlsx";
header('Content-disposition: attachment; filename='.$file);
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo json_encode(readfile($file));

Edit 20.04.2016

Browsers are making it harder to save data this way. One good option is to use filesaver.js. It provides a cross browser implementation for saveAs, and it should replace some of the code in the success promise above.

Read response headers from API response - Angular 5 + TypeScript

Angular 7 Service:

    this.http.post(environment.urlRest + '/my-operation',body, { headers: headers, observe: 'response'});
    
Component:
    this.myService.myfunction().subscribe(
          (res: HttpResponse) => {
              console.log(res.headers.get('x-token'));
                }  ,
        error =>{
        }) 
    

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

cursor.execute(sql,array)

Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)

How do I detect if software keyboard is visible on Android Device or not?

With the new feature WindowInsetsCompat in androidx core release 1.5.0-alpha02 you could check the visibility of the soft keyboard easily as below

Quoting from reddit comment

val View.keyboardIsVisible: Boolean
    get() = WindowInsetsCompat
        .toWindowInsetsCompat(rootWindowInsets)
        .isVisible(WindowInsetsCompat.Type.ime())

Some note about backward compatibility, quoting from release notes

New Features

The WindowInsetsCompat APIs have been updated to those in the platform in Android 11. This includes the new ime() inset type, which allows checking the visibility and size of the on-screen keyboard.

Some caveats about the ime() type, it works very reliably on API 23+ when your Activity is using the adjustResize window soft input mode. If you’re instead using the adjustPan mode, it should work reliably back to API 14.

References

LEFT OUTER JOIN in LINQ

Take a look at this example. This query should work:

var leftFinal = from left in lefts
                join right in rights on left equals right.Left into leftRights
                from leftRight in leftRights.DefaultIfEmpty()
                select new { LeftId = left.Id, RightId = left.Key==leftRight.Key ? leftRight.Id : 0 };

Convert a String representation of a Dictionary to a dictionary?

If the string can always be trusted, you could use eval (or use literal_eval as suggested; it's safe no matter what the string is.) Otherwise you need a parser. A JSON parser (such as simplejson) would work if he only ever stores content that fits with the JSON scheme.

How to create JSON string in JavaScript?

This can be pretty easy and simple

var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;

//convert object to json string
var string = JSON.stringify(obj);

//convert string to Json Object
console.log(JSON.parse(string)); // this is your requirement.

How can I build for release/distribution on the Xcode 4?

To set the build configuration to Debug or Release, choose 'Edit Scheme' from the 'Product' menu.

Then you see a clear choice.

The Apple Transition Guide mentions a button at the top left of the Xcode screen, but I cannot see it in Xcode 4.3.

Shortcut for changing font size

Ctrl + Alt + MouseWheel will work in Visual Studio 2015.

How do I order my SQLITE database in descending order, for an android app?

According to docs:

public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

and your ORDER BY param means:

How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

So, your query will be:

 Cursor cursor = db.query(TABLE_NAME, null, null,
            null, null, null, KEY_ITEM + " DESC", null);

how to load CSS file into jsp

I use this version

<style><%@include file="/WEB-INF/css/style.css"%></style>

How do I vertically align text in a div?

<!DOCTYPE html>
<html>

  <head>
    <style>
      .container {
        height: 250px;
        background: #f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-align: center;
        justify-content: center;
      }
      p{
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </body>

</html>

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

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

Jinja2 template variable if None Object set a default value

You can simply add "default none" to your variable as the form below mentioned:

{{ your_var | default('NONE', boolean=true) }}

TypeError: $(...).on is not a function

If you are using old version of jQuery(< 1.7) then you can use "bind" instead of "on". This will only work in case you are using old version, since as of jQuery 3.0, "bind" has been deprecated.

How can I send emails through SSL SMTP with the .NET Framework?

It works with System.Web.Mail (which is marked as obsolete):

private const string SMTP_SERVER        = "http://schemas.microsoft.com/cdo/configuration/smtpserver";
private const string SMTP_SERVER_PORT   = "http://schemas.microsoft.com/cdo/configuration/smtpserverport";
private const string SEND_USING         = "http://schemas.microsoft.com/cdo/configuration/sendusing";
private const string SMTP_USE_SSL       = "http://schemas.microsoft.com/cdo/configuration/smtpusessl";
private const string SMTP_AUTHENTICATE  = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate";
private const string SEND_USERNAME      = "http://schemas.microsoft.com/cdo/configuration/sendusername";
private const string SEND_PASSWORD      = "http://schemas.microsoft.com/cdo/configuration/sendpassword";

System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();

mail.Fields[SMTP_SERVER] = "tempurl.org";
mail.Fields[SMTP_SERVER_PORT] = 465;
mail.Fields[SEND_USING] = 2;
mail.Fields[SMTP_USE_SSL] = true;
mail.Fields[SMTP_AUTHENTICATE] = 1;
mail.Fields[SEND_USERNAME] = "username";
mail.Fields[SEND_PASSWORD] = "password";

System.Web.Mail.SmtpMail.Send(mail);

What is your point of view regarding obsolete namespace usage?

Why can't Python import Image from PIL?

All the answers were great however what did it for me was a combination of uninstalling Pillow

pip uninstall Pillow

Then installing whatever packages you need e.g.

sudo apt-get -y install python-imaging
sudo apt-get -y install zlib1g-dev
sudo apt-get -y install libjpeg-dev

And then using easy_install to reinstall Pillow

easy_install Pillow

Hope this helps others

Using jQuery to see if a div has a child with a certain class

If it's a direct child you can do as below if it could be nested deeper remove the >

$("#text-field").keydown(function(event) {
    if($('#popup>p.filled-text').length !== 0) {
        console.log("Found");
     }
});

The application has stopped unexpectedly: How to Debug?

  1. From the Home screen, press the Menu key.
  2. List item
  3. Touch Settings.
  4. Touch Applications.
  5. Touch Manage Applications.
  6. Touch All.
  7. Select the application that is having issues.
  8. Touch Clear data and Clear cache if they are available. This resets the app as if it was new, and may delete personal data stored in the app.

Convert command line arguments into an array in Bash

Here is another usage :

#!/bin/bash
array=( "$@" )
arraylength=${#array[@]}
for (( i=0; i<${arraylength}; i++ ));
do
   echo "${array[$i]}"
done

Functions are not valid as a React child. This may happen if you return a Component instead of from render

What would be wrong with doing;

<div className="" key={index}>
   {i.title}
</div>

[/*Use IIFE */]

{(function () {
     if (child.children && child.children.length !== 0) {
     let menu = createMenu(child.children);
     console.log("nested menu", menu);
     return menu;
   }
 })()}

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

How to get selected value of a dropdown menu in ReactJS

As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList 1 remember you will always get the result as option value and not the dropdown text which is displayed on the screen

import React, { Component } from "react";
import { Server } from "net";

class InlineStyle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectValue: ""
    };

    this.handleDropdownChange = this.handleDropdownChange.bind(this);
  }

  handleDropdownChange(e) {
    this.setState({ selectValue: e.target.value });
  }

  render() {
    return (
      <div>
        <div>
          <div>
            <select id="dropdown" onChange={this.handleDropdownChange}>
              <option value="N/A">N/A</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
            </select>
          </div>

          <div>Selected value is : {this.state.selectValue}</div>
        </div>
      </div>
    );
  }
}
export default InlineStyle;

Working with $scope.$emit and $scope.$on

You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.

app.controller('firstCtrl', function($scope, $rootScope) {        
        function firstCtrl($scope) {
        {
            $rootScope.$emit('someEvent', [1,2,3]);
        }
}

app.controller('secondCtrl', function($scope, $rootScope) {
        function secondCtrl($scope)
        {
            $rootScope.$on('someEvent', function(event, data) { console.log(data); });
        }
}

Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.

How to obtain the total numbers of rows from a CSV file in Python?

You need to count the number of rows:

row_count = sum(1 for row in fileObject)  # fileObject is your csv.reader

Using sum() with a generator expression makes for an efficient counter, avoiding storing the whole file in memory.

If you already read 2 rows to start with, then you need to add those 2 rows to your total; rows that have already been read are not being counted.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.

Here is the code:

package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Facebook {
    public static void main(String args[]){
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.facebook.com");
        WebElement email= driver.findElement(By.id("email"));
        Actions builder = new Actions(driver);
        Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "[email protected]");
        seriesOfActions.perform();
        WebElement pass = driver.findElement(By.id("pass"));
        WebElement login =driver.findElement(By.id("u_0_b"));
        Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);
        seriesOfAction.perform();
        driver.
    }    
}

How to count the number of occurrences of a character in an Oracle varchar value?

Here you go:

select length('123-345-566') - length(replace('123-345-566','-',null)) 
from dual;

Technically, if the string you want to check contains only the character you want to count, the above query will return NULL; the following query will give the correct answer in all cases:

select coalesce(length('123-345-566') - length(replace('123-345-566','-',null)), length('123-345-566'), 0) 
from dual;

The final 0 in coalesce catches the case where you're counting in an empty string (i.e. NULL, because length(NULL) = NULL in ORACLE).

form_for but to post to a different action

new syntax

<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>

Put request with simple string as request body

This works for me (code called from node js repl):

const axios = require("axios");

axios
    .put(
        "http://localhost:4000/api/token", 
        "mytoken", 
        {headers: {"Content-Type": "text/plain"}}
    )
    .then(r => console.log(r.status))
    .catch(e => console.log(e));

Logs: 200

And this is my request handler (I am using restify):

function handleToken(req, res) {
    if(typeof req.body === "string" && req.body.length > 3) {
        res.send(200);
    } else {
        res.send(400);
    }
}

Content-Type header is important here.

Table 'performance_schema.session_variables' doesn't exist

Follow these steps without -p :

  1. mysql_upgrade -u root
  2. systemctl restart mysqld

I had the same problem and it works!

Excel VBA to Export Selected Sheets to PDF

Once you have Selected a group of sheets, you can use Selection

Consider:

Sub luxation()
    ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
    Selection.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="C:\TestFolder\temp.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

EDIT#1:

Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:

Sub Macro1()

   Sheets("Sheet1").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet2").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet3").Activate
   ActiveSheet.UsedRange.Select

   ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
   Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
      "C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
      True
End Sub

Command to collapse all sections of code?

CTL + M + L expands all

CTL + M + O collapses all

In the MSDN article "Default Keyboard Shortcuts in Visual Studio," see the section "Text Editor" if you're looking for other shortcuts - these 2 are just a few of the many that are available.

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can use the HTML5 pattern attribute or use JavaScript.

The pattern could look for example like this:

<input id="groupidtext" type="text" pattern="(.){6,6}" style="width: 100px;" maxlength="6" />

But the pattern attribute will only work with HTML5 browsers. For old browsers you'll need JavaScript.

As suggested in the comments to add, this will only work as soon as a form is about to be submitted. If this input is not in a form and you need validation as a user types, use JavaScript.

Getting a File's MD5 Checksum in Java

I recently had to do this for just a dynamic string, MessageDigest can represent the hash in numerous ways. To get the signature of the file like you would get with the md5sum command I had to do something like the this:

try {
   String s = "TEST STRING";
   MessageDigest md5 = MessageDigest.getInstance("MD5");
   md5.update(s.getBytes(),0,s.length());
   String signature = new BigInteger(1,md5.digest()).toString(16);
   System.out.println("Signature: "+signature);

} catch (final NoSuchAlgorithmException e) {
   e.printStackTrace();
}

This obviously doesn't answer your question about how to do it specifically for a file, the above answer deals with that quiet nicely. I just spent a lot of time getting the sum to look like most application's display it, and thought you might run into the same trouble.

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Might wanna check this, got everything you need for your app icons

http://developer.android.com/guide/practices/ui_guidelines/icon_design.html

update

I think by default it uses your launcher icon... Your best bet is to create a separate image... Designed for the action bar and using that. For that check: http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems

Check if an array is empty or exists

You should do this

    if (!image_array) {
      // image_array defined but not assigned automatically coerces to false
    } else if (!(0 in image_array)) {
      // empty array
      // doSomething
    }

Postgres Error: More than one row returned by a subquery used as an expression

The result produced by the Query is having no of rows that need proper handling this issue can be resolved if you provide the valid handler in the query like 1. limiting the query to return one single row 2. this can also be done by providing "select max(column)" that will return the single row

Submitting HTML form using Jquery AJAX

If you add:

jquery.form.min.js

You can simply do this:

<script>
$('#myform').ajaxForm(function(response) {
  alert(response);
});

// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>

NOTE:

You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.

XAMPP Apache Webserver localhost not working on MAC OS

In my case, Web Sharing was running, which blocked XAMPP.

'Untick' Web Sharing in the Bluetooth Settings (or Network), which causes HTTPD to show in activity log.

Apache should now run and be available!

Simple way to repeat a string

using Dollar is simple as typing:

@Test
public void repeatString() {
    String string = "abc";
    assertThat($(string).repeat(3).toString(), is("abcabcabc"));
}

PS: repeat works also for array, List, Set, etc

Adding an onclicklistener to listview (android)

The prestListView.getItemAtPosition(position); returns the UI widget: Text, Icon, ...

Try this instead:

Object o = prestationAdapterEco.getItemAtPosition(position);

or

Object o = arg0.getItemAtPosition(position);

Get the object from the adapter. Not from the list-view.

2. Object o is a prestationEco object. Not a String.

Angular2 dynamic change CSS property

Just use standard CSS variables:

Your global css (eg: styles.css)

body {
  --my-var: #000
}

In your component's css or whatever it is:

span {
  color: var(--my-var)
}

Then you can change the value of the variable directly with TS/JS by setting inline style to html element:

document.querySelector("body").style.cssText = "--my-var: #000";

Otherwise you can use jQuery for it:

$("body").css("--my-var", "#fff");

Jquery Open in new Tab (_blank)

you cannot set target attribute to div, becacuse div does not know how to handle http requests. instead of you set target attribute for link tag.

$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")

Order a MySQL table by two columns

Default sorting is ascending, you need to add the keyword DESC to both your orders:

ORDER BY article_rating DESC, article_time DESC

Working with INTERVAL and CURDATE in MySQL

You need DATE_ADD/DATE_SUB:

AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))

should work.

What is N-Tier architecture?

N-tier data applications are data applications that are separated into multiple tiers. Also called "distributed applications" and "multitier applications," n-tier applications separate processing into discrete tiers that are distributed between the client and the server. When you develop applications that access data, you should have a clear separation between the various tiers that make up the application.

A typical n-tier application includes a presentation tier, a middle tier, and a data tier. The easiest way to separate the various tiers in an n-tier application is to create discrete projects for each tier that you want to include in your application. For example, the presentation tier might be a Windows Forms application, whereas the data access logic might be a class library located in the middle tier. Additionally, the presentation layer might communicate with the data access logic in the middle tier through a service such as a service. Separating application components into separate tiers increases the maintainability and scalability of the application. It does this by enabling easier adoption of new technologies that can be applied to a single tier without the requirement to redesign the whole solution. In addition, n-tier applications typically store sensitive information in the middle-tier, which maintains isolation from the presentation tier.

Taken from Microsoft website.

How to do a regular expression replace in MySQL?

I'm happy to report that since this question was asked, now there is a satisfactory answer! Take a look at this terrific package:

https://github.com/mysqludf/lib_mysqludf_preg

Sample SQL:

SELECT PREG_REPLACE('/(.*?)(fox)/' , 'dog' , 'the quick brown fox' ) AS demo;

I found the package from this blog post as linked on this question.

Calculating Distance between two Latitude and Longitude GeoCoordinates

This is an old question, nevertheless the answers did not satisfy me regarding to performance and optimization.

Here my optimized C# variant (distance in km, without variables and redundant calculations, very close to mathematical expression of Haversine Formular https://en.wikipedia.org/wiki/Haversine_formula).

Inspired by: https://rosettacode.org/wiki/Haversine_formula#C.23

public static class Haversine
{
    public static double Calculate(double lat1, double lon1, double lat2, double lon2)
    {
        double rad(double angle) => angle * 0.017453292519943295769236907684886127d; // = angle * Math.Pi / 180.0d
        double havf(double diff) => Math.Pow(Math.Sin(rad(diff) / 2d), 2); // = sin²(diff / 2)
        return 12745.6 * Math.Asin(Math.Sqrt(havf(lat2 - lat1) + Math.Cos(rad(lat1)) * Math.Cos(rad(lat2)) * havf(lon2 - lon1))); // earth radius 6.372,8?km x 2 = 12745.6
    }
}

Haversine Formular from Wikipedia

CSS selector for text input fields?

You can use the attribute selector here:

input[type="text"] {
    font-family: Arial, sans-serif;
}

This is supported in IE7 and above. You can use IE7.js to add support for this if you need to support IE6.

See: http://reference.sitepoint.com/css/attributeselector for more information

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

AngularJS - Passing data between pages

If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.

How to get terminal's Character Encoding

Check encoding and language:

$ echo $LC_CTYPE
ISO-8859-1
$ echo $LANG
pt_BR

Get all languages:

$ locale -a

Change to pt_PT.utf8:

$ export LC_ALL=pt_PT.utf8 
$ export LANG="$LC_ALL"

jquery <a> tag click event

<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
  var usersid =  $(this).attr("id");
  //post code
})

//other method is to use the data attribute

<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
    var usersid =  $(this).data("id");
    var username = $(this).data("username");
})

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

.any() and .all() are great for the extreme cases, but not when you're looking for a specific number of null values. Here's an extremely simple way to do what I believe you're asking. It's pretty verbose, but functional.

import pandas as pd
import numpy as np

# Some test data frame
df = pd.DataFrame({'num_legs':          [2, 4,      np.nan, 0, np.nan],
                   'num_wings':         [2, 0,      np.nan, 0, 9],
                   'num_specimen_seen': [10, np.nan, 1,     8, np.nan]})

# Helper : Gets NaNs for some row
def row_nan_sums(df):
    sums = []
    for row in df.values:
        sum = 0
        for el in row:
            if el != el: # np.nan is never equal to itself. This is "hacky", but complete.
                sum+=1
        sums.append(sum)
    return sums

# Returns a list of indices for rows with k+ NaNs
def query_k_plus_sums(df, k):
    sums = row_nan_sums(df)
    indices = []
    i = 0
    for sum in sums:
        if (sum >= k):
            indices.append(i)
        i += 1
    return indices

# test
print(df)
print(query_k_plus_sums(df, 2))

Output

   num_legs  num_wings  num_specimen_seen
0       2.0        2.0               10.0
1       4.0        0.0                NaN
2       NaN        NaN                1.0
3       0.0        0.0                8.0
4       NaN        9.0                NaN
[2, 4]

Then, if you're like me and want to clear those rows out, you just write this:

# drop the rows from the data frame
df.drop(query_k_plus_sums(df, 2),inplace=True)
# Reshuffle up data (if you don't do this, the indices won't reset)
df = df.sample(frac=1).reset_index(drop=True)
# print data frame
print(df)

Output:

   num_legs  num_wings  num_specimen_seen
0       4.0        0.0                NaN
1       0.0        0.0                8.0
2       2.0        2.0               10.0

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

I'm not sure where to post this answer of mine but I think it's the right place. I came across this very error today and switching the subsystems didn't change a thing.

Changing the 64bit lib files to 32bit (x86) did the trick for me, I hope it will help someone out there !

Using .htaccess to make all .html pages to run as .php files?

Normally you should add:

Options +ExecCGI
 AddType application/x-httpd-php .php .html
 AddHandler x-httpd-php5 .php .html

However for GoDaddy shared hosting (php-cgi), you need to add also these lines:

AddHandler fcgid-script .html
FCGIWrapper /usr/local/cpanel/cgi-sys/php5 .html

Source: Parse HTML As PHP Using HTACCESS File On Godaddy.

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.


Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.


Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

Using RegEX To Prefix And Append In Notepad++

Use a Macro.

Macro>Start Recording

Use the keyboard to make your changes in a repeatable manner e.g.

home>type "able">end>down arrow>home

Then go back to the menu and click stop recording then run a macro multiple times.

That should do it and no regex based complications!

How to use group by with union in t-sql

with UnionTable as  
(
    SELECT a.id, a.time FROM dbo.a
    UNION
    SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id

Using $_POST to get select option value from HTML

Use this way:

$selectOption = $_POST['taskOption'];

But it is always better to give values to your <option> tags.

<select name="taskOption">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
</select>

AngularJS directive does not update on scope variable changes

We can try this

$scope.$apply(function() {
    $scope.step1 = true;
    //scope.list2.length = 0;
});

http://jsfiddle.net/Etb9d/

How to make layout with View fill the remaining space?

You can use set the layout_width or layout_width to 0dp (By the orientation you want to fill remaining space). Then use the layout_weight to make it fill remaining space.

Tick symbol in HTML/XHTML

Would √ (square root symbol, &#8730;) suffice?

Alternatively, ensure you're setting the Content-Type: header before sending data to the browser. Merely specifying the <meta> content-type tag may not be enough to encourage browsers to use the correct character set.

How can I make a checkbox readonly? not disabled?

I personally like to do it this way:

<input type="checkbox" name="option" value="1" disabled="disabled" />
<input type="hidden" name="option" value="1">

I think this is better for two reasons:

  1. User clearly understand that he can't edit this value
  2. The value is sent when submitting the form.

What are the differences between numpy arrays and matrices? Which one should I use?

Just to add one case to unutbu's list.

One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.

For example demean rows of a matrix or array:

with matrix

>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
        [2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
        [ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5,  0.5],
        [-0.5,  0.5]])

with array

>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
       [2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5,  2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
       [ 0.5,  0.5]])
>>> a - am[:, np.newaxis]  #right
array([[-0.5,  0.5],
       [-0.5,  0.5]])

I also think that mixing arrays and matrices gives rise to many "happy" debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.

Convert char* to string C++

char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;

How do I exit a while loop in Java?

You can use "break", already mentioned in the answers above. If you need to return some values. You can use "return" like the code below:

 while(true){
       if(some condition){
            do something;
            return;}
        else{
            do something;
            return;}
            }

in this case, this while is in under a method which is returning some kind of values.

Extract a subset of a dataframe based on a condition involving a field

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there")

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ]

Maintain image aspect ratio when changing height

Declare where display: flex; was given Element.
align-items: center;

Merge/flatten an array of arrays

You can also try the new Array.flat() method. It works in the following manner:

_x000D_
_x000D_
let arr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]].flat()

console.log(arr);
_x000D_
_x000D_
_x000D_

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the 1 layer of depth (i.e. arrays inside arrays)

If you want to also flatten out 3 dimensional or even higher dimensional arrays you simply call the flat method multiple times. For example (3 dimensions):

_x000D_
_x000D_
let arr = [1,2,[3,4,[5,6]]].flat().flat().flat();

console.log(arr);
_x000D_
_x000D_
_x000D_

Be careful!

Array.flat() method is relatively new. Older browsers like ie might not have implemented the method. If you want you code to work on all browsers you might have to transpile your JS to an older version. Check for MDN web docs for current browser compatibility.

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

Android: Changing Background-Color of the Activity (Main View)

You can also try and provide an Id for the main layout and change the background of that through basic manipulation and retrieval. E.g:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/hello"

Which can then be followed by accessing through R.id.hello.... Pretty basic and I hope this does help :)

Hashset vs Treeset

Basing on lovely visual answer on Maps by @shevchyk here is my take:

+------------------------------------------------------------------------------+
¦   Property   ¦       HashSet       ¦      TreeSet      ¦     LinkedHashSet   ¦
¦--------------+---------------------+-------------------+---------------------¦
¦              ¦  no guarantee order ¦ sorted according  ¦                     ¦
¦   Order      ¦ will remain constant¦ to the natural    ¦    insertion-order  ¦
¦              ¦      over time      ¦    ordering       ¦                     ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ Add/remove   ¦        O(1)         ¦     O(log(n))     ¦        O(1)         ¦
¦--------------+---------------------+-------------------+---------------------¦
¦              ¦                     ¦   NavigableSet    ¦                     ¦
¦  Interfaces  ¦         Set         ¦       Set         ¦         Set         ¦
¦              ¦                     ¦    SortedSet      ¦                     ¦
¦--------------+---------------------+-------------------+---------------------¦
¦              ¦                     ¦    not allowed    ¦                     ¦
¦  Null values ¦       allowed       ¦ 1st element only  ¦      allowed        ¦
¦              ¦                     ¦     in Java 7     ¦                     ¦
¦--------------+---------------------------------------------------------------¦
¦              ¦   Fail-fast behavior of an iterator cannot be guaranteed      ¦
¦   Fail-fast  ¦ impossible to make any hard guarantees in the presence of     ¦
¦   behavior   ¦           unsynchronized concurrent modification              ¦
¦--------------+---------------------------------------------------------------¦
¦      Is      ¦                                                               ¦
¦ synchronized ¦              implementation is not synchronized               ¦
+------------------------------------------------------------------------------+

Reason: no suitable image found

  1. Remove the app from device
  2. Clean the project (CMD + SHift + K)
  3. Build/Run on device

How can you find out which process is listening on a TCP or UDP port on Windows?

Based on answers with info and kill, for me it is useful to combine them in one command. And you can run this from cmd to get information about process that listen on given port (example 8080):

for /f "tokens=3 delims=LISTENING" %i  in ('netstat -ano ^| findStr "8080" ^| findStr "["') do @tasklist /nh /fi "pid eq %i"

Or if you want to kill it:

for /f "tokens=3 delims=LISTENING" %i  in ('netstat -ano ^| findStr "8080" ^| findStr "["') do @Taskkill /F /IM %i

You can also put those command into a bat file (they will be slightly different - replace %i for %%i):

File portInfo.bat

for /f "tokens=3 delims=LISTENING" %%i  in (
    'netstat -ano ^| findStr "%1" ^| findStr "["'
) do @tasklist /nh /fi "pid eq %%i"

File portKill.bat

for /f "tokens=3 delims=LISTENING" %%i  in (
    'netstat -ano ^| findStr "%1" ^| findStr "["'
) do @Taskkill /F /IM %%i

Then you from cmd you can do this:

portInfo.bat 8080

or

portKill.bat 8080

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

  1. First of all check latest Chrome version (This is your browser Chrome version) link

  2. Download same version of Chrome Web Driver from this link

Do not download latest Chrome Web Driver if it does not match your Chrome Browser version.

Note: When I write this message, latest Chrome Browser version is 84 but latest Chrome Driver version is 85. I am using Chrome Driver version 84 so that Chrome Driver and Chrome Browser versions are the same.

Is there a way to catch the back button event in javascript?

Use the hashchange event:

window.addEventListener("hashchange", function(e) {
  // ...
})

If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.

Standard deviation of a list

Here's some pure-Python code you can use to calculate the mean and standard deviation.

All code below is based on the statistics module in Python 3.4+.

def mean(data):
    """Return the sample arithmetic mean of data."""
    n = len(data)
    if n < 1:
        raise ValueError('mean requires at least one data point')
    return sum(data)/n # in Python 2 use sum(data)/float(n)

def _ss(data):
    """Return sum of square deviations of sequence data."""
    c = mean(data)
    ss = sum((x-c)**2 for x in data)
    return ss

def stddev(data, ddof=0):
    """Calculates the population standard deviation
    by default; specify ddof=1 to compute the sample
    standard deviation."""
    n = len(data)
    if n < 2:
        raise ValueError('variance requires at least two data points')
    ss = _ss(data)
    pvar = ss/(n-ddof)
    return pvar**0.5

Note: for improved accuracy when summing floats, the statistics module uses a custom function _sum rather than the built-in sum which I've used in its place.

Now we have for example:

>>> mean([1, 2, 3])
2.0
>>> stddev([1, 2, 3]) # population standard deviation
0.816496580927726
>>> stddev([1, 2, 3], ddof=1) # sample standard deviation
0.1

HttpContext.Current.Session is null when routing requests

The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there.

I doubt the problem is in the Session provider since it works without the routing.

How to create a popup window (PopupWindow) in Android

Button endDataSendButton = (Button)findViewById(R.id.end_data_send_button);

Similarly you can get the text view by adding a id to it.

Check if element is visible in DOM

The jQuery code from http://code.jquery.com/jquery-1.11.1.js has an isHidden param

var isHidden = function( elem, el ) {
    // isHidden might be called from jQuery#filter function;
    // in that case, element will be second argument
    elem = el || elem;
    return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};

So it looks like there is an extra check related to the owner document

I wonder if this really catches the following cases:

  1. Elements hidden behind other elements based on zIndex
  2. Elements with transparency full making them invisible
  3. Elements positioned off screen (ie left: -1000px)
  4. Elements with visibility:hidden
  5. Elements with display:none
  6. Elements with no visible text or sub elements
  7. Elements with height or width set to 0

How to remove indentation from an unordered list item?

I have the same problem with a footer I'm trying to divide up. I found that this worked for me by trying few of above suggestions combined:

footer div ul {
    list-style-position: inside;
    padding-left: 0;
}

This seems to keep it to the left under my h1 and the bullet points inside the div rather than outside to the left.

SMTP connect() failed PHPmailer - PHP

You are missing the directive that states the connection uses SSL

require ("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPAuth = true;     // turn of SMTP authentication
$mail->Username = "YAHOO ACCOUNT";  // SMTP username
$mail->Password = "YAHOO ACCOUNT PASSWORD"; // SMTP password
$mail->SMTPSecure = "ssl";
$mail->Host = "YAHOO HOST"; // SMTP host
$mail->Port = 465;

Then add in the other parts

$webmaster_email = "[email protected]";       //Reply to this email ID
$email="[email protected]";                // Recipients email ID
$name="My Name";                              // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50;                         // set word wrap
$mail->IsHTML(true);                          // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY ";                      //HTML Body 
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body 

if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}

As a side note, I have had trouble using Body + AltBody together although they are supposed to work. As a result, I wrote the following wrapper function which works perfectly.

<?php
require ("class.phpmailer.php");

// Setup Configuration for Mail Server Settings
$email['host']          = 'smtp.email.com';
$email['port']          = 366;
$email['user']          = '[email protected]';
$email['pass']          = 'from password';
$email['from']          = 'From Name';
$email['reply']         = '[email protected]';
$email['replyname']     = 'Reply To Name';

$addresses_to_mail_to = '[email protected];[email protected]';
$email_subject = 'My Subject';
$email_body = '<html>Code Here</html>';
$who_is_receiving_name = 'John Smith';

$result = sendmail(
    $email_body,
    $email_subject,
    $addresses_to_mail_to,
    $who_is_receiving_name
);

var_export($result);


function sendmail($body, $subject, $to, $name, $attach = "") {

  global $email;
  $return = false;

  $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
  $mail->IsSMTP(); // telling the class to use SMTP
  try {
    $mail->Host       = $email['host']; // SMTP server
//    $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->Host       = $email['host']; // sets the SMTP server
    $mail->Port       = $email['port'];                    // set the SMTP port for the GMAIL server
    $mail->SMTPSecure = "tls";
    $mail->Username   = $email['user']; // SMTP account username
    $mail->Password   = $email['pass'];        // SMTP account password
    $mail->AddReplyTo($email['reply'], $email['replyname']);
    if(stristr($to,';')) {
      $totmp = explode(';',$to);
      foreach($totmp as $destto) {
        if(trim($destto) != "") {
          $mail->AddAddress(trim($destto), $name);
        }
      }
    } else {
      $mail->AddAddress($to, $name);
    }
    $mail->SetFrom($email['user'], $email['from']);
    $mail->Subject = $subject;
    $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
    $mail->MsgHTML($body);
    if(is_array($attach)) {
        foreach($attach as $attach_f) {
            if($attach_f != "") {
              $mail->AddAttachment($attach_f);      // attachment
            }
        }
    } else {
        if($attach != "") {
          $mail->AddAttachment($attach);      // attachment
        }
    }
    $mail->Send();
  } catch (phpmailerException $e) {
    $return = $e->errorMessage();
  } catch (Exception $e) {
    $return = $e->errorMessage();
  }

  return $return;
}

Casting interfaces for deserialization in JSON.NET

Several years on and I had a similar issue. In my case there were heavily nested interfaces and a preference for generating the concrete classes at runtime so that It would work with a generic class.

I decided to create a proxy class at run time that wraps the object returned by Newtonsoft.

The advantage of this approach is that it does not require a concrete implementation of the class and can handle any depth of nested interfaces automatically. You can see more about it on my blog.

using Castle.DynamicProxy;
using Newtonsoft.Json.Linq;
using System;
using System.Reflection;

namespace LL.Utilities.Std.Json
{
    public static class JObjectExtension
    {
        private static ProxyGenerator _generator = new ProxyGenerator();

        public static dynamic toProxy(this JObject targetObject, Type interfaceType) 
        {
            return _generator.CreateInterfaceProxyWithoutTarget(interfaceType, new JObjectInterceptor(targetObject));
        }

        public static InterfaceType toProxy<InterfaceType>(this JObject targetObject)
        {

            return toProxy(targetObject, typeof(InterfaceType));
        }
    }

    [Serializable]
    public class JObjectInterceptor : IInterceptor
    {
        private JObject _target;

        public JObjectInterceptor(JObject target)
        {
            _target = target;
        }
        public void Intercept(IInvocation invocation)
        {

            var methodName = invocation.Method.Name;
            if(invocation.Method.IsSpecialName && methodName.StartsWith("get_"))
            {
                var returnType = invocation.Method.ReturnType;
                methodName = methodName.Substring(4);

                if (_target == null || _target[methodName] == null)
                {
                    if (returnType.GetTypeInfo().IsPrimitive || returnType.Equals(typeof(string)))
                    {

                        invocation.ReturnValue = null;
                        return;
                    }

                }

                if (returnType.GetTypeInfo().IsPrimitive || returnType.Equals(typeof(string)))
                {
                    invocation.ReturnValue = _target[methodName].ToObject(returnType);
                }
                else
                {
                    invocation.ReturnValue = ((JObject)_target[methodName]).toProxy(returnType);
                }
            }
            else
            {
                throw new NotImplementedException("Only get accessors are implemented in proxy");
            }

        }
    }



}

Usage:

var jObj = JObject.Parse(input);
InterfaceType proxyObject = jObj.toProxy<InterfaceType>();

HTML5 Video Autoplay not working correctly

Chrome does not allow autoplay if the video is not muted. Try using this:

<video width="440px" loop="true" autoplay="autoplay" controls muted>
  <source src="http://www.tuscorlloyds.com/CorporateVideo.mp4" type="video/mp4" />
  <source src="http://www.tuscorlloyds.com/CorporateVideo.ogv" type="video/ogv" />
  <source src="http://www.tuscorlloyds.com/CorporateVideo.webm" type="video/webm" />
</video>

WCF Exception: Could not find a base address that matches scheme http for the endpoint

Open IIS And right click on Default App Pool and Add Binding to make application work with HTTPS protocol.

type : https

IP address : All unassigned

port no : 443

SSL Certificate : WMSVC

then

Click on and restart IIS

Done

how to get javaScript event source element?

You can pass this when you call the function

<button onclick="doSomething('param',this)" id="id_button">action</button>

<script>
    function doSomething(param,me){

    var source = me
    console.log(source);
}
</script>

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

mat-form-field must contain a MatFormFieldControl

I had the same error message, but in my case, nothing above didn't fix the problem. The solution was in "label". You need to add 'mat-label' and to put your input inside 'label' tags also. Solution of my problem is in the snippet below:

  <mat-label>
     Username
  </mat-label>
  <label>
    <input 
       matInput 
       type="text" 
       placeholder="Your username" 
       formControlName="username"/>
  </label>

How to state in requirements.txt a direct github source

Github has a zip endpoint that in my opinion is preferable to using the git protocol. The advantages are:

  • You don't have to specify #egg=<project name>
  • Git doesn't need to be installed in your environment, which is nice for containerized environments
  • It works much better with pip hashing
  • The URL structure is easier to remember and more discoverable

You usually want requirements.txt entries to look like this, e.g. without the -e prefix:

https://github.com/org/package/archive/1a58aa586efd4bca37f2cfb9d9348958986aab6c.zip

To install from main branch:

https://github.com/org/package/archive/main.zip

Pass all variables from one shell script to another?

Adding to the answer of Fatal Error, There is one more way to pass the variables to another shell script.

The above suggested solution have some drawbacks:

  1. using Export : It will cause the variable to be present out of their scope which is not a good design practice.
  2. using Source : It may cause name collisions or accidental overwriting of a predefined variable in some other shell script file which have sourced another file.

There is another simple solution avaiable for us to use. Considering the example posted by you,

test.sh

#!/bin/bash

TESTVARIABLE=hellohelloheloo
./test2.sh "$TESTVARIABLE"

test2.sh

#!/bin/bash

echo $1

output

hellohelloheloo

Also it is important to note that "" are necessary if we pass multiword strings. Taking one more example

master.sh

#!/bin/bash
echo in master.sh
var1="hello world"
sh slave1.sh $var1
sh slave2.sh "$var1"
echo back to master

slave1.sh

#!/bin/bash
echo in slave1.sh
echo value :$1

slave2.sh

#!/bin/bash
echo in slave2.sh
echo value : $1

output

in master.sh
in slave1.sh
value :"hello
in slave2.sh
value :"hello world"

It happens because of the reasons aptly described in this link

How to set layout_gravity programmatically?

layoutParams2.gravity = Gravity.RIGHT|Gravity.BOTTOM;

use this to add mor than one gravity

What happened to Lodash _.pluck?

Use _.map instead of _.pluck. In the latest version the _.pluck has been removed.

Use RSA private key to generate public key?

openssl genrsa -out mykey.pem 1024

will actually produce a public - private key pair. The pair is stored in the generated mykey.pem file.

openssl rsa -in mykey.pem -pubout > mykey.pub

will extract the public key and print that out. Here is a link to a page that describes this better.

EDIT: Check the examples section here. To just output the public part of a private key:

openssl rsa -in key.pem -pubout -out pubkey.pem

To get a usable public key for SSH purposes, use ssh-keygen:

ssh-keygen -y -f key.pem > key.pub

Iif equivalent in C#

C# has the ? ternary operator, like other C-style languages. However, this is not perfectly equivalent to IIf(); there are two important differences.

To explain the first difference, the false-part argument for this IIf() call causes a DivideByZeroException, even though the boolean argument is True.

IIf(true, 1, 1/0)

IIf() is just a function, and like all functions all the arguments must be evaluated before the call is made. Put another way, IIf() does not short circuit in the traditional sense. On the other hand, this ternary expression does short-circuit, and so is perfectly fine:

(true)?1:1/0;

The other difference is IIf() is not type safe. It accepts and returns arguments of type Object. The ternary operator is type safe. It uses type inference to know what types it's dealing with. Note you can fix this very easily with your own generic IIF(Of T)() implementation, but out of the box that's not the way it is.

If you really want IIf() in C#, you can have it:

object IIf(bool expression, object truePart, object falsePart) 
{return expression?truePart:falsePart;}

or a generic/type-safe implementation:

T IIf<T>(bool expression, T truePart, T falsePart) 
{return expression?truePart:falsePart;}

On the other hand, if you want the ternary operator in VB, Visual Studio 2008 and later provide a new If() operator that works like C#'s ternary operator. It uses type inference to know what it's returning, and it really is an operator rather than a function. This means there's no issues from pre-evaluating expressions, even though it has function semantics.

onclick open window and specific size

Just add them to the parameter string.

window.open(this.href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=350,height=250')

Reading a date using DataReader

If the query's column has an appropriate type then

var dateString = MyReader.GetDateTime(MyReader.GetOrdinal("column")).ToString(myDateFormat)

If the query's column is actually a string then see other answers.

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

AngularJS format JSON string output

In addition to the angular json filter already mentioned, there is also the angular toJson() function.

angular.toJson(obj, pretty);

The second param of this function lets you switch on pretty printing and set the number of spaces to use.

If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

(default: 2)

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

How do I store data in local storage using Angularjs?

this is a bit of my code that stores and retrieves to local storage. i use broadcast events to save and restore the values in the model.

app.factory('userService', ['$rootScope', function ($rootScope) {

    var service = {

        model: {
            name: '',
            email: ''
        },

        SaveState: function () {
            sessionStorage.userService = angular.toJson(service.model);
        },

        RestoreState: function () {
            service.model = angular.fromJson(sessionStorage.userService);
        }
    }

    $rootScope.$on("savestate", service.SaveState);
    $rootScope.$on("restorestate", service.RestoreState);

    return service;
}]);

JavaScript open in a new window, not tab

You might try following function:

<script type="text/javascript">
function open(url)
{
  var popup = window.open(url, "_blank", "width=200, height=200") ;
  popup.location = URL;
}
</script>

The HTML code for execution:

<a href="#" onclick="open('http://www.google.com')">google search</a>

Excel date to Unix timestamp

You're apparently off by one day, exactly 86400 seconds. Use the number 2209161600 Not the number 2209075200 If you Google the two numbers, you'll find support for the above. I tried your formula but was always coming up 1 day different from my server. It's not obvious from the unix timestamp unless you think in unix instead of human time ;-) but if you double check then you'll see this might be correct.

Undefined symbols for architecture x86_64 on Xcode 6.1

Check if that file is included in Build Phases -> Compiled Sources

How to get UTC timestamp in Ruby?

if you need a human-readable timestamp (like rails migration has) ex. "20190527141340"

Time.now.utc.to_formatted_s(:number)  # using Rails

Time.now.utc.strftime("%Y%m%d%H%M%S") # using Ruby

Split string to equal length substrings in Java

Here is my version based on RegEx and Java 8 streams. It's worth to mention that Matcher.results() method is available since Java 9.

Test included.

public static List<String> splitString(String input, int splitSize) {
    Matcher matcher = Pattern.compile("(?:(.{" + splitSize + "}))+?").matcher(input);
    return matcher.results().map(MatchResult::group).collect(Collectors.toList());
}

@Test
public void shouldSplitStringToEqualLengthParts() {
    String anyValidString = "Split me equally!";
    String[] expectedTokens2 = {"Sp", "li", "t ", "me", " e", "qu", "al", "ly"};
    String[] expectedTokens3 = {"Spl", "it ", "me ", "equ", "all"};

    Assert.assertArrayEquals(expectedTokens2, splitString(anyValidString, 2).toArray());
    Assert.assertArrayEquals(expectedTokens3, splitString(anyValidString, 3).toArray());
}

Creating a button in Android Toolbar

I was able to achieve that by wrapping Button with ConstraintLayout:

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="0dp">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/top_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/white_color">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/cancel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/cancel"
                    android:layout_marginStart="5dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <Button
                    android:id="@+id/btn_publish"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/publish"
                    android:background="@drawable/button_publish_rounded"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    android:layout_marginEnd="10dp"
                    app:layout_constraintLeft_toRightOf="@id/cancel"
                    tools:layout_editor_absoluteY="0dp" />

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

You may create a drawable resourcebutton_publish_rounded, define the button properties and assign this file to button's android:background property:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/green" />
    <corners android:radius="100dp" />
</shape>

How can I check if a string is a number?

namespace Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            bool isNumeric;
            int n;
            do
            {
                Console.Write("Enter a number:");
                isNumeric = int.TryParse(Console.ReadLine(), out n);
            } while (isNumeric == false);
            Console.WriteLine("Thanks for entering number" + n);
            Console.Read();
        }
    }
}

StringStream in C#

You can create a MemoryStream from a String and use that in any third-party function that requires a stream. In this case, MemoryStream, with the help of UTF8.GetBytes, provides the functionality of Java's StringStream.

From String examples

String content = "stuff";
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)))
{
    Print(stream); //or whatever action you need to perform with the stream
    stream.Seek(0, SeekOrigin.Begin); //If you need to use the same stream again, don't forget to reset it.
    UseAgain(stream);
}

To String example

stream.Seek(0, SeekOrigin.Begin);
string s;
using (var readr = new StreamReader(stream))
{
    s = readr.ReadToEnd();
}
//and don't forget to dispose the stream if you created it

How to output git log with the first line only?

Better and easier git log by making an alias. Paste the code below to terminal just once for one session. Paste the code to zshrc or bash profile to make it persistant.

git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

Output

git lg

Output changed lines

git lg -p

Alternatively (recommended)
Paste this code to global .gitconfig file

[alias]
  lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

Further Reading.
https://coderwall.com/p/euwpig/a-better-git-log
Advanced Reading.
http://durdn.com/blog/2012/11/22/must-have-git-aliases-advanced-examples/

How to hide the keyboard when I press return key in a UITextField?

In viewDidLoad declare:

[yourTextField setDelegate:self];

Then, include the override of the delegate method:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

C# generic list <T> how to get the type of T?

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

MySQL table is marked as crashed and last (automatic?) repair failed

If your MySQL process is running, stop it. On Debian:

sudo service mysql stop

Go to your data folder. On Debian:

cd /var/lib/mysql/$DATABASE_NAME

Try running:

myisamchk -r $TABLE_NAME

If that doesn't work, you can try:

myisamchk -r -v -f $TABLE_NAME

You can start your MySQL server again. On Debian:

sudo service mysql start

Jquery DatePicker Set default date

First you need to get the current date

var currentDate = new Date();

Then you need to place it in the arguments of datepicker like given below

$("#datepicker").datepicker("setDate", currentDate);

Check the following jsfiddle.

SQLite3 database or disk is full / the database disk image is malformed

I have seen this happen when the database gets corrupted, have you tried cloning it into a new one ?

Safley copy a s SQLite db

Safely copy a SQLite database

It's trivially easy to copy a SQLite database. It's less trivial to do this in a way that won't corrupt it. Here's how:

shell$ sqlite3 some.db
sqlite> begin immediate;
<press CTRL+Z>
shell$ cp some.db some.db.backup
shell$ exit
sqlite> rollback;

This will give you a nice clean backup that's sure to be in a proper state, since writing to the database half-way through your copying process is impossible.

canvas.toDataURL() SecurityError

Try the code below ...

<img crossOrigin="anonymous"
     id="imgpicture" 
     fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
                bungalow,high end luxury properties,landed properties,gated guarded house.png" 
     ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" 
     height="220"
     width="200"
     class="watermark">

How to Convert date into MM/DD/YY format in C#

 DateTime.Today.ToString("MM/dd/yy")

Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

What is an example of the simplest possible Socket.io example?

Maybe this may help you as well. I was having some trouble getting my head wrapped around how socket.io worked, so I tried to boil an example down as much as I could.

I adapted this example from the example posted here: http://socket.io/get-started/chat/

First, start in an empty directory, and create a very simple file called package.json Place the following in it.

{
"dependencies": {}
}

Next, on the command line, use npm to install the dependencies we need for this example

$ npm install --save express socket.io

This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}

Create a file called server.js This will obviously be our server run by node. Place the following code into it:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

http.listen(3001, function(){

  console.log('listening on *:3001');

});

//for testing, we're just going to send data to the client every second
setInterval( function() {

  /*
    our message we want to send to the client: in this case it's just a random
    number that we generate on the server
  */
  var msg = Math.random();
  io.emit('message', msg);
  console.log (msg);

}, 1000);

Create the last file called index.html and place the following code into it.

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

You can now test this very simple example and see some output similar to the following:

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653

If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.

How To Set Up GUI On Amazon EC2 Ubuntu server

1) Launch Ubuntu Instance on EC2.
2) Open SSH Port in instance security.
3) Do SSH to instance.
4) Execute:

sudo apt-get update    sudo apt-get upgrade

5) Because you will be connecting from Windows Remote Desktop, edit the sshd_config file on your Linux instance to allow password authentication.

sudo vim /etc/ssh/sshd_config

6) Change PasswordAuthentication to yes from no, then save and exit.
7) Restart the SSH daemon to make this change take effect.

sudo /etc/init.d/ssh restart

8) Temporarily gain root privileges and change the password for the ubuntu user to a complex password to enhance security. Press the Enter key after typing the command passwd ubuntu, and you will be prompted to enter the new password twice.

sudo –i
passwd ubuntu

9) Switch back to the ubuntu user account and cd to the ubuntu home directory.

su ubuntu
cd

10) Install Ubuntu desktop functionality on your Linux instance, the last command can take up to 15 minutes to complete.

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get update
sudo -E apt-get install -y ubuntu-desktop

11) Install xrdp

sudo apt-get install xfce4
sudo apt-get install xfce4 xfce4-goodies

12) Make xfce4 the default window manager for RDP connections.

echo xfce4-session > ~/.xsession

13) Copy .xsession to the /etc/skel folder so that xfce4 is set as the default window manager for any new user accounts that are created.

sudo cp /home/ubuntu/.xsession /etc/skel

14) Open the xrdp.ini file to allow changing of the host port you will connect to.

sudo vim /etc/xrdp/xrdp.ini

(xrdp is not installed till now. First Install the xrdp with sudo apt-get install xrdp then edit the above mentioned file)

15) Look for the section [xrdp1] and change the following text (then save and exit [:wq]).

port=-1
- to -
port=ask-1

16) Restart xrdp.

sudo service xrdp restart

17) On Windows, open the Remote Desktop Connection client, paste the fully qualified name of your Amazon EC2 instance for the Computer, and then click Connect.

18) When prompted to Login to xrdp, ensure that the sesman-Xvnc module is selected, and enter the username ubuntu with the new password that you created in step 8. When you start a session, the port number is -1.

19) When the system connects, several status messages are displayed on the Connection Log screen. Pay close attention to these status messages and make note of the VNC port number displayed. If you want to return to a session later, specify this number in the port field of the xrdp login dialog box.

See more details: https://aws.amazon.com/premiumsupport/knowledge-center/connect-to-linux-desktop-from-windows/
http://c-nergy.be/blog/?p=5305

DB2 Date format

SELECT VARCHAR_FORMAT(CURRENT TIMESTAMP, 'YYYYMMDD')
FROM SYSIBM.SYSDUMMY1

Should work on both Mainframe and Linux/Unix/Windows DB2. Info Center entry for VARCHAR_FORMAT().

Using client certificate in Curl command

This is how I did it:

curl -v \
  --key ./admin-key.pem \
  --cert ./admin.pem \
  https://xxxx/api/v1/

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I had the same problem, but while using a library project. The issue has been solved in r17: Instead of using the package's namespace:

xmlns:app="http://schemas.android.com/apk/res/hu.droidium.exercises"

One has to use a dummy namespace:

xmlns:app="http://schemas.android.com/apk/res-auto"

This will fix the problem of the attributes not being accessible from the referencing project.

How to replace a character by a newline in Vim

From Eclipse, the ^M characters can be embedded in a line, and you want to convert them to newlines.

:s/\r/\r/g

Javascript foreach loop on associative array object

arr_jq_TabContents[key] sees the array as an 0-index form.

Failed to execute 'atob' on 'Window'

BlobBuilder is obsolete, use Blob constructor instead:

URL.createObjectURL(new Blob([/*whatever content*/] , {type:'text/plain'}));

This returns a blob URL which you can then use in an anchor's href. You can also modify an anchor's download attribute to manipulate the file name:

<a href="/*assign url here*/" id="link" download="whatever.txt">download me</a>

Fiddled. If I recall correctly, there are arbitrary restrictions on trusted non-user initiated downloads; thus we'll stick with a link clicking which is seen as sufficiently user-initiated :)

Update: it's actually pretty trivial to save current document's html! Whenever our interactive link is clicked, we'll update its href with a relevant blob. After executing the click-bound event, that's the download URL that will be navigated to!

$('#link').on('click', function(e){
  this.href = URL.createObjectURL(
    new Blob([document.documentElement.outerHTML] , {type:'text/html'})
  );
});

Fiddled again.

List of lists into numpy array

It's as simple as:

>>> lists = [[1, 2], [3, 4]]
>>> np.array(lists)
array([[1, 2],
       [3, 4]])

How to do Select All(*) in linq to sql

from row in TableA select row

Or just:

TableA

In method syntax, with other operators:

TableA.Where(row => row.IsInteresting) // no .Select(), returns the whole row.

Essentially, you already are selecting all columns, the select then transforms that to the columns you care about, so you can even do things like:

from user in Users select user.LastName+", "+user.FirstName

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM : virtual machine of java. tells machine what to do with the Java Code. You cannot download JVM as is. It comes packaged in some other component.

JRE: Some other component referred as above is the JRE. It is JVM+ other jars to create runtime environmeny

JDK: contains JRE(which in turn contains JVM). Once you get JDK you need not install JRE and JVM separately. It contains compiler which compiles your .java files to .class files

How to check if text fields are empty on form submit using jQuery?

var save_val = $("form").serializeArray();
$(save_val).each(function( index, element ) {
    alert(element.name);
    alert(element.val);
});

Why use a READ UNCOMMITTED isolation level?

Use READ_UNCOMMITTED in situation where source is highly unlikely to change.

  • When reading historical data. e.g some deployment logs that happened two days ago.
  • When reading metadata again. e.g. metadata based application.

Don't use READ_UNCOMMITTED when you know souce may change during fetch operation.

Can you force Vue.js to reload/re-render?

The approach of adding :key to the vue-router lib's router-view component cause's fickers for me, so I went vue-router's 'in-component guard' to intercept updates and refresh the entire page accordingly when there's an update of the path on the same route (as $router.go, $router.push, $router.replace weren't any help). The only caveat with this is that we're for a second breaking the singe-page app behavior, by refreshing the page.

  beforeRouteUpdate(to, from, next) {
    if (to.path !== from.path) {
      window.location = to.path;
    }
  },

Clearing Magento Log Data

Further hint: If you don't need those information you can change the Table Type to "Blackhole" (instead of InnoDB). This means, nothing will be stored in the future and the insert statements are still working fine.

You can also disable the logs by setting all events to disabled:

https://gist.github.com/tegansnyder/189f1c3ce897b4ab494d

How to run a stored procedure in oracle sql developer?

Consider you've created a procedure like below.

CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
  FIRST_NAME IN VARCHAR2, 
  LAST_NAME IN VARCHAR2,
  FULL_NAME OUT VARCHAR2 
) IS 
BEGIN
  FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;

In Oracle SQL Developer, you can run this procedure in two ways.

1. Using SQL Worksheet

Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5

DECLARE
  FULL_NAME Varchar2(50);
BEGIN
  GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
  Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;

2. Using GUI Controls

  • Expand Procedures

  • Right click on the procudure you've created and Click Run

  • In the pop-up window, Fill the parameters and Click OK.

Cheers!

How do you build a Singleton in Dart?

In this example I do other things that are also necessary when wanting to use a Singleton. For instance:

  • pass a value to the singleton's constructor
  • initialize a value inside the constructor itself
  • set a value to a Singleton's variable
  • be able to access and access those values.

Like this:

class MySingleton {

  static final MySingleton _singleton = MySingleton._internal();

  String _valueToBeSet;
  String _valueAlreadyInSingleton;
  String _passedValueInContructor;

  get getValueToBeSet => _valueToBeSet;

  get getValueAlreadyInSingleton => _valueAlreadyInSingleton;

  get getPassedValueInConstructor => _passedValueInContructor;

  void setValue(newValue) {
    _valueToBeSet = newValue;
  }

  factory MySingleton(String passedString) {
    _singleton._valueAlreadyInSingleton = "foo";
    _singleton._passedValueInContructor = passedString;

    return _singleton;
  }

  MySingleton._internal();
}

Usage of MySingleton:

void main() {

MySingleton mySingleton =  MySingleton("passedString");
mySingleton.setValue("setValue");
print(mySingleton.getPassedValueInConstructor);
print(mySingleton.getValueToBeSet);
print(mySingleton.getValueAlreadyInSingleton);

}

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

It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult is generic, however you can determine the exact issue catching HttpRequestException and then inspecting InnerException: if it's a WebException then you can check the WebException.Status property, for example WebExceptionStatus.NameResolutionFailure should indicate a DNS resolution problem.


It may happen, there isn't much you can do.

What I'd suggest to always wrap that (network related) code in a loop with a try/catch block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:

private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;

public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
    using (var client = new HttpClient()) {
        for (int i=1; i <= NumberOfRetries; ++i) {
            try {
                return await client.GetAsync(url); 
            }
            catch (Exception e) when (i < NumberOfRetries) {
                await Task.Delay(DelayOnRetry);
            }
        }
    }
}

HTML 5 Geo Location Prompt in Chrome

if you're hosting behind a server, and still facing issues: try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/

The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).

For my sanity check I was using Remy Sharp's demo: https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html

and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):

"User denied Geolocation"

I made the following change to get more detailed error message:

function error(msg) {
  var s = document.querySelector('#status');
  msg = msg.message ? msg.message : msg; //add this line
  s.innerHTML = typeof msg == 'string' ? msg : "failed";
  s.className = 'fail';

  // console.log(arguments);
}

failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :

"The current location cannot be determined"

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

String's Maximum length in Java - calling length() method

The Return type of the length() method of the String class is int.

public int length()

Refer http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()

So the maximum value of int is 2147483647.

String is considered as char array internally,So indexing is done within the maximum range. This means we cannot index the 2147483648th member.So the maximum length of String in java is 2147483647.

Primitive data type int is 4 bytes(32 bits) in java.As 1 bit (MSB) is used as a sign bit,The range is constrained within -2^31 to 2^31-1 (-2147483648 to 2147483647). We cannot use negative values for indexing.So obviously the range we can use is from 0 to 2147483647.

DataGridView checkbox column - value and functionality

1) How do I make it so that the whole column is "checked" by default?

var doWork = new DataGridViewCheckBoxColumn();
doWork.Name = "IncludeDog" //Added so you can find the column in a row
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";

//Make the default checked
doWork.CellTemplate.Value = true;
doWork.CellTemplate.Style.NullValue = true;

dataGridView1.Columns.Insert(0, doWork);

2) How can I make sure I'm only getting values from the "checked" rows?

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.IsNewRow) continue;//If editing is enabled, skip the new row

    //The Cell's Value gets it wrong with the true default, it will return         
    //false until the cell changes so use FormattedValue instead.
    if (Convert.ToBoolean(row.Cells["IncludeDog"].FormattedValue))
    {
        //Do stuff with row
    }
}

Passing HTML input value as a JavaScript Function Parameter

Use this it will work,

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="a"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    var m = document.getElementById("a").value;
    var n = document.getElementById("b").value;
    var sum = m + n;
    alert(sum);
  }
</script>
</body>

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

What is the purpose of the return statement?

Just to add to @Nathan Hughes's excellent answer:

The return statement can be used as a kind of control flow. By putting one (or more) return statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"

Here's an example:

>>> def make_3_characters_long(some_string):
...     if len(some_string) == 3:
...         return False
...     if str(some_string) != some_string:
...         return "Not a string!"
...     if len(some_string) < 3:
...         return ''.join(some_string,'x')[:,3]
...     return some_string[:,3]
... 
>>> threechars = make_3_characters_long('xyz')    
>>> if threechars:
...     print threechars
... else:
...     print "threechars is already 3 characters long!"
... 
threechars is already 3 characters long!

See the Code Style section of the Python Guide for more advice on this way of using return.

Tool to generate JSON schema from JSON data

Summarising the other answers, here are the JSON schema generators proposed so far:

Online:

Python:

NodeJS:

Ruby:

How can I open two pages from a single click without using JavaScript?

<a href="http://www.omsaicreche.blogspot.com" onclick="location.href='http://www.omsaivatikanoida.blogspot.com';" target="_blank">Open Two Links With One Click</a>

I tried the above codes. I could not get success in old page. Than I created a new page in blogger and types following codes... I was successful

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

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

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

What's the difference between a mock & stub?

If you compare it to debugging:

Stub is like making sure a method returns the correct value

Mock is like actually stepping into the method and making sure everything inside is correct before returning the correct value.

How do I add an element to array in reducer of React native redux?

If you need to insert into a specific position in the array, you can do this:

case ADD_ITEM :
    return { 
        ...state,
        arr: [
            ...state.arr.slice(0, action.pos),
            action.newItem,
            ...state.arr.slice(action.pos),
        ],
    }

C++ - How to append a char to char*?

char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;

OUTPUT:

test

How can I get a list of all values in select box?

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";
      }

How can I read the client's machine/computer name from the browser?

Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.

EDIT: Not possible across all browser at least.

Inserting a PDF file in LaTeX

Use the pdfpages package.

\usepackage{pdfpages}

To include all the pages in the PDF file:

\includepdf[pages=-]{myfile.pdf}

To include just the first page of a PDF:

\includepdf[pages={1}]{myfile.pdf}

Run texdoc pdfpages in a shell to see the complete manual for pdfpages.

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

In addition to @Bruno's answer, you need to supply the -name for alias, otherwise Tomcat will throw Alias name tomcat does not identify a key entry error

Sample Command: openssl pkcs12 -export -in localhost.crt -inkey localhost.key -out localhost.p12 -name localhost