Programs & Examples On #Outlook 2003

Outlook 2003 is Microsoft's personal information management software.

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

Best way to use multiple SSH private keys on one client

I love the approach to set the following in file ~/.ssh/config:

# Configuration for GitHub to support multiple GitHub  keys
Host  github.com
  HostName github.com
  User git

# UseKeychain adds each keys passphrase to the keychain so you
# don't have to enter the passphrase each time.
  UseKeychain yes

# AddKeysToAgent would add the key to the agent whenever it is
# used, which might lead to debugging confusion since then
# sometimes the one repository works and sometimes the
# other depending on which key is used first.
#  AddKeysToAgent yes

# I only use my private id file so all private
# repositories don't need the environment variable
# `GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa"` to be set.
  IdentityFile ~/.ssh/id_rsa

Then in your repository you can create a .env file which contains the ssh command to be used:

GIT_SSH_COMMAND="ssh -i ~/.ssh/your_ssh_key"

If you then use e.g. dotenv the environment environment variable is exported automatically and whoop whoop, you can specify the key you want per project/directory. The passphrase is asked for only once since it is added to the keychain.

This solution works perfectly with Git and is designed to work on a Mac (due to UseKeychain).

Best data type to store money values in MySQL

If GAAP Compliance is required or you need 4 decimal places:

DECIMAL(13, 4) Which supports a max value of:

$999,999,999.9999

Otherwise, if 2 decimal places is enough: DECIMAL(13,2)

src: https://rietta.com/blog/best-data-types-for-currencymoney-in/

How do I iterate through table rows and cells in JavaScript?

Try

for (let row of mytab1.rows) 
{
    for(let cell of row.cells) 
    {
       let val = cell.innerText; // your code below
    }
}

_x000D_
_x000D_
for (let row of mytab1.rows) _x000D_
{_x000D_
    for(let cell of row.cells) _x000D_
    {_x000D_
       console.log(cell.innerText)_x000D_
    }_x000D_
}
_x000D_
<div id="myTabDiv">_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
for ( let [i,row] of [...mytab1.rows].entries() ) _x000D_
{_x000D_
    for( let [j,cell] of [...row.cells].entries() ) _x000D_
    {_x000D_
       console.log(`[${i},${j}] = ${cell.innerText}`)_x000D_
    }_x000D_
}
_x000D_
<div id="myTabDiv">_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Don't understand why UnboundLocalError occurs (closure)

try this

counter = 0

def increment():
  global counter
  counter += 1

increment()

VBA check if object is set

The (un)safe way to do this - if you are ok with not using option explicit - is...

Not TypeName(myObj) = "Empty"

This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...

Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ true, the object exists - TypeName is Object

'Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ false, the object has not been declared

This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

How do I split an int into its digits?

Start with the highest power of ten that fits into an int on your platform (for 32 bit int: 1.000.000.000) and perform an integer division by it. The result is the leftmost digit. Subtract this result multipled with the divisor from the original number, then continue the same game with the next lower power of ten and iterate until you reach 1.

ASP MVC href to a controller/view

Here '~' refers to the root directory ,where Home is controller and Download_Excel_File is actionmethod

 <a href="~/Home/Download_Excel_File" />

INNER JOIN ON vs WHERE clause

If you are often programming dynamic stored procedures, you will fall in love with your second example (using where). If you have various input parameters and lots of morph mess, then that is the only way. Otherwise, they both will run the same query plan so there is definitely no obvious difference in classic queries.

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

Remove warning messages in PHP

For ignoring all warnings use this sample, on the top of your code :

error_reporting(0);

How can I export data to an Excel file

I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.

For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.

Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.

http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html

Difference between Activity Context and Application Context

This obviously is deficiency of the API design. In the first place, Activity Context and Application context are totally different objects, so the method parameters where context is used should use ApplicationContext or Activity directly, instead of using parent class Context. In the second place, the doc should specify which context to use or not explicitly.

Calling ASP.NET MVC Action Methods from JavaScript

If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.

<div class="cart">
      @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>

That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

If you want extended auto-completion for PHP (not only for the code in the current window or standard classes), try out the "ACCPC" plugin: https://github.com/StanDog/npp-phpautocompletion

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

Function Pointers in Java

The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.

Collections.sort(list, new Comparator<MyClass>(){
    public int compare(MyClass a, MyClass b)
    {
        // compare objects
    }
});

Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:

list.sort((a, b) -> a.isGreaterThan(b));

and method references:

list.sort(MyClass::isGreaterThan);

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

For functions where you do not want to alter the original placement or image.

$(this).clone().removeAttr("width").attr("width");
$(this).clone().removeAttr("height").attr("height);

Javascript - get array of dates between 2 dates

Here's a one liner that doesn't require any libraries in-case you don't want to create another function. Just replace startDate (in two places) and endDate (which are js date objects) with your variables or date values. Of course you could wrap it in a function if you prefer

Array(Math.floor((endDate - startDate) / 86400000) + 1).fill().map((_, idx) => (new Date(startDate.getTime() + idx * 86400000)))

DataTable: How to get item value with row name and column name? (VB)

For i = 0 To dt.Rows.Count - 1

    ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)

Next

Java: String - add character n-times

Its better to use StringBuilder instead of String because String is an immutable class and it cannot be modified once created: in String each concatenation results in creating a new instance of the String class with the modified string.

How to obtain the query string from the current URL with JavaScript?

q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;

Converting byte array to string in javascript

String to byte array: "FooBar".split('').map(c => c.charCodeAt(0));

Byte array to string: [102, 111, 111, 98, 97, 114].map(c => String.fromCharCode(c)).join('');

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

Python: create dictionary using dict() with integer keys?

There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}

Android: show soft keyboard automatically when focus is on an EditText

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

I call this in onCreate() to show keyboard automatically, when I came in the Activity.

How to "Open" and "Save" using java

Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.

Use Excel pivot table as data source for another Pivot Table

  • Make your first pivot table.

  • Select the first top left cell.

  • Create a range name using offset:

    OFFSET(Sheet1!$A$3,0,0,COUNTA(Sheet1!$A:$A)-1,COUNTA(Sheet1!$3:$3))

  • Make your second pivot with your range name as source of data using F3.

If you change number of rows or columns from your first pivot, your second pivot will be update after refreshing pivot

GFGDT

Pretty-Print JSON Data to a File using Python

You could redirect a file to python and open using the tool and to read it use more.

The sample code will be,

cat filename.json | python -m json.tool | more

Php multiple delimiters in explode

If your delimiter is only characters, you can use strtok, which seems to be more fit here. Note that you must use it with a while loop to achieve the effects.

Setting the value of checkbox to true or false with jQuery

<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>

--

$('#vehicleChkBox').change(function(){
    if(this.checked)
        $('#vehicleChkBox').val('TRUE');
   else
        $('#vehicleChkBox').val('False');
});

Sorting an array of objects by property values

If you use Underscore.js, try sortBy:

// price is of an integer type
_.sortBy(homes, "price"); 

// price is of a string type
_.sortBy(homes, function(home) {return parseInt(home.price);}); 

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

How do I exclude all instances of a transitive dependency when using Gradle?

In addition to what @berguiga-mohamed-amine stated, I just found that a wildcard requires leaving the module argument the empty string:

compile ("com.github.jsonld-java:jsonld-java:$jsonldJavaVersion") {
    exclude group: 'org.apache.httpcomponents', module: ''
    exclude group: 'org.slf4j', module: ''
}

Get current application physical path within Application_Start

 protected void Application_Start(object sender, EventArgs e)
 {
     string path = Server.MapPath("/");
     //or 
     string path2 = Server.MapPath("~");
     //depends on your application needs

 }

vim - How to delete a large block of text without counting the lines?

You can also enter a very large number, and then press dd if you wish to delete all the lines below the cursor.

How to pop an alert message box using PHP?

Create function for alert

<?php
alert("Hello World");

function alert($msg) {
    echo "<script type='text/javascript'>alert('$msg');</script>";
}
?>

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

What's the difference between a null pointer and a void pointer?

Null pointers and void pointers are completely different from each other. If we request the operating system(through malloc() in c langauge) to allocate memory for a particular data type then the operating system allocates memory in heap (if space is available in heap) and sends the address of the memory which was allocated.

When memory is allocated by os in heap then we can assign this address value in any pointer type variable of that data type. This pointer is then called a void pointer until it is not taken for any process.

When the space is not available in heap then the operating system certainly allocates memory and sends an address value of that location but this memory is not allocated in heap by the os because there is no space in heap,in this case this memory is allocated by the os in the system memory.. This memory can not be accessed by the user hence when we assign this address value in a pointer then this pointer is known as null pointer, and we cannot use this pointer. In the case of void pointer we can use it for any process in any programming language.

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

My example:

HTML:

<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

JS:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}

Here is a jsFiddle demo.

Double free or corruption after queue::push

You are getting double free or corruption because first destructor is for object q in this case the memory allocated by new will be free.Next time when detructor will be called for object t at that time the memory is already free (done for q) hence when in destructor delete[] myArray; will execute it will throw double free or corruption. The reason is that both object sharing the same memory so define \copy, assignment, and equal operator as mentioned in above answer.

Get city name using geolocation

You can use https://ip-api.io/ to get city Name. It supports IPv6.

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

Javascript Code:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            }
            $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
                 function (result) {
                     alert('City Name: ' + result.city)
                     console.log(result);
                 });
        });
    });

HTML Code

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
    <input type="text" id="txtIP" />
    <button id="btnGetIpDetail">Get Location of IP</button>
</div>

JSON Output

{
    "ip": "64.30.228.118",
    "country_code": "US",
    "country_name": "United States",
    "region_code": "FL",
    "region_name": "Florida",
    "city": "Fort Lauderdale",
    "zip_code": "33309",
    "time_zone": "America/New_York",
    "latitude": 26.1882,
    "longitude": -80.1711,
    "metro_code": 528,
    "suspicious_factors": {
        "is_proxy": false,
        "is_tor_node": false,
        "is_spam": false,
        "is_suspicious": false
    }
}

javascript window.location in new tab

window.open('https://support.wwf.org.uk', '_blank');

The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article :)

How to normalize a NumPy array to within a certain range?

audio /= np.max(np.abs(audio),axis=0)
image *= (255.0/image.max())

Using /= and *= allows you to eliminate an intermediate temporary array, thus saving some memory. Multiplication is less expensive than division, so

image *= 255.0/image.max()    # Uses 1 division and image.size multiplications

is marginally faster than

image /= image.max()/255.0    # Uses 1+image.size divisions

Since we are using basic numpy methods here, I think this is about as efficient a solution in numpy as can be.


In-place operations do not change the dtype of the container array. Since the desired normalized values are floats, the audio and image arrays need to have floating-point point dtype before the in-place operations are performed. If they are not already of floating-point dtype, you'll need to convert them using astype. For example,

image = image.astype('float64')

Best way to check if an PowerShell Object exist?

You can also do

if ($ie) {
    # Do Something if $ie is not null
}

Bootstrap 3: Using img-circle, how to get circle from non-square image?

You have to give height and width to that image.

eg. height : 200px and width : 200px also give border-radius:50%;

to create circle you have to give equal height and width

if you are using bootstrap then give height and width and img-circle class to img

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

How to pass the password to su/sudo/ssh without overriding the TTY?

When there's no better choice (as suggested by others), then man socat can help:

   (sleep 5; echo PASSWORD; sleep 5; echo ls; sleep 1) |
   socat - EXEC:'ssh -l user server',pty,setsid,ctty

          EXEC’utes an ssh session to server. Uses a pty for communication
          between socat and ssh, makes it ssh’s  controlling  tty  (ctty),
          and makes this pty the owner of a new process group (setsid), so
          ssh accepts the password from socat.

All of the pty,setsid,ctty complexity is necessary and, while you might not need to sleep as long, you will need to sleep. The echo=0 option is worth a look too, as is passing the remote command on ssh's command line.

Inserting image into IPython notebook markdown

Change the default block from "Code" to "Markdown" before running this code:

![<caption>](image_filename.png)

If image file is in another folder, you can do the following:

![<caption>](folder/image_filename.png)

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

In my case, I had copied some code from another project that was using Automapper - took me ages to work that one out. Just had to add automapper nuget package to project.

HTTPS setup in Amazon EC2

First, you need to open HTTPS port (443). To do that, you go to https://console.aws.amazon.com/ec2/ and click on the Security Groups link on the left, then create a new security group with also HTTPS available. Then, just update the security group of a running instance or create a new instance using that group.

After these steps, your EC2 work is finished, and it's all an application problem.

How to check whether a string contains a substring in Ruby

Expanding on Clint Pachl's answer:

Regex matching in Ruby returns nil when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example:

"foobar" =~ /bar/  # returns 3
"foobar" =~ /foo/  # returns 0
"foobar" =~ /zzz/  # returns nil

It's important to note that in Ruby only nil and the boolean expression false evaluate to false. Everything else, including an empty Array, empty Hash, or the Integer 0, evaluates to true.

That's why the /foo/ example above works, and why.

if "string" =~ /regex/

works as expected, only entering the 'true' part of the if block if a match occurred.

Jquery, checking if a value exists in array or not

    if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

Reference: Jquery Array

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Bootstrap 3 with remote Modal

If you don't want to send the full modal structure you can replicate the old behaviour doing something like this:

// this is just an example, remember to adapt the selectors to your code!
$('.modal-link').click(function(e) {
    var modal = $('#modal'), modalBody = $('#modal .modal-body');

    modal
        .on('show.bs.modal', function () {
            modalBody.load(e.currentTarget.href)
        })
        .modal();
    e.preventDefault();
});

How to wait for a JavaScript Promise to resolve before resuming function?

You can do it manually. (I know, that that isn't great solution, but..) use while loop till the result hasn't a value

kickOff().then(function(result) {
   while(true){
       if (result === undefined) continue;
       else {
            $("#output").append(result);
            return;
       }
   }
});

How to send JSON instead of a query string with $.ajax?

You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    complete: callback
});

Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.

How do I tell CMake to link in a static library in the source directory?

I found this helpful...

http://www.cmake.org/pipermail/cmake/2011-June/045222.html

From their example:

ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)

What resources are shared between threads?

From Wikipedia (I think that would make a really good answer for the interviewer :P)

Threads differ from traditional multitasking operating system processes in that:

  • processes are typically independent, while threads exist as subsets of a process
  • processes carry considerable state information, whereas multiple threads within a process share state as well as memory and other resources
  • processes have separate address spaces, whereas threads share their address space
  • processes interact only through system-provided inter-process communication mechanisms.
  • Context switching between threads in the same process is typically faster than context switching between processes.

Vue-router redirect on page not found (404)

@mani's response is now slightly outdated as using catch-all '*' routes is no longer supported when using Vue 3 onward. If this is no longer working for you, try replacing the old catch-all path with

{ path: '/:pathMatch(.*)*', component: PathNotFound },

Essentially, you should be able to replace the '*' path with '/:pathMatch(.*)*' and be good to go!

Reason: Vue Router doesn't use path-to-regexp anymore, instead it implements its own parsing system that allows route ranking and enables dynamic routing. Since we usually add one single catch-all route per project, there is no big benefit in supporting a special syntax for *.

(from https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes)

How to install PyQt4 in anaconda?

Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:

conda install pyqt=4

This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example

conda install pyqt=4.11

would install the latest (or last) release of version 4.11.

Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.

How to convert a char array back to a string?

Just use String.value of like below;

  private static void h() {

        String helloWorld = "helloWorld";
        System.out.println(helloWorld);

        char [] charArr = helloWorld.toCharArray();

        System.out.println(String.valueOf(charArr));
    }

$apply already in progress error

Just resolved this issue. Its documented here.

I was calling $rootScope.$apply twice in the same flow. All I did is wrapped the content of the service function with a setTimeout(func, 1).

How to perform mouseover function in Selenium WebDriver using Java?

Sample program to mouse hover using Selenium java WebDriver :

public class Mhover {
    public static void main(String[] args){
       WebDriver driver = new FirefoxDriver();
       driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       driver.get("http://www.google.com");
       WebElement ele = driver.findElement(By.id("gbqfba"));
       Actions action = new Actions(driver);
       action.moveToElement(ele).build().perform();
    }
}

converting Java bitmap to byte array

Here is bitmap extension .convertToByteArray wrote in Kotlin.

/**
 * Convert bitmap to byte array using ByteBuffer.
 */
fun Bitmap.convertToByteArray(): ByteArray {
    //minimum number of bytes that can be used to store this bitmap's pixels
    val size = this.byteCount

    //allocate new instances which will hold bitmap
    val buffer = ByteBuffer.allocate(size)
    val bytes = ByteArray(size)

    //copy the bitmap's pixels into the specified buffer
    this.copyPixelsToBuffer(buffer)

    //rewinds buffer (buffer position is set to zero and the mark is discarded)
    buffer.rewind()

    //transfer bytes from buffer into the given destination array
    buffer.get(bytes)

    //return bitmap's pixels
    return bytes
}

Insert current date/time using now() in a field using MySQL/PHP

These both work fine for me...

<?php
  $db = mysql_connect('localhost','user','pass');
  mysql_select_db('test_db');

  $stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
          "('{$first}','{$last}','NOW())";
  $rslt = mysql_query($stmt);

  $stmt = "INSERT INTO `users` (`first`,`last`,`whenadded`) VALUES ".
          "('{$first}', '{$last}', CURRENT_TIMESTAMP)";
  $rslt = mysql_query($stmt);

?>

Side note: mysql_query() is not the best way to connect to MySQL in current versions of PHP.

Disable submit button on form submit

Specifically if someone is facing problem in Chrome:

What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...

<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;"> 
     <input type="submit" name="submit" value="Submit" id="submit"> 
</form>

How to return multiple objects from a Java method?

As I see it there are really three choices here and the solution depends on the context. You can choose to implement the construction of the name in the method that produces the list. This is the choice you've chosen, but I don't think it is the best one. You are creating a coupling in the producer method to the consuming method that doesn't need to exist. Other callers may not need the extra information and you would be calculating extra information for these callers.

Alternatively, you could have the calling method calculate the name. If there is only one caller that needs this information, you can stop there. You have no extra dependencies and while there is a little extra calculation involved, you've avoided making your construction method too specific. This is a good trade-off.

Lastly, you could have the list itself be responsible for creating the name. This is the route I would go if the calculation needs to be done by more than one caller. I think this puts the responsibility for the creation of the names with the class that is most closely related to the objects themselves.

In the latter case, my solution would be to create a specialized List class that returns a comma-separated string of the names of objects that it contains. Make the class smart enough that it constructs the name string on the fly as objects are added and removed from it. Then return an instance of this list and call the name generation method as needed. Although it may be almost as efficient (and simpler) to simply delay calculation of the names until the first time the method is called and store it then (lazy loading). If you add/remove an object, you need only remove the calculated value and have it get recalculated on the next call.

Download file of any type in Asp.Net MVC using FileResult?

Phil Haack has a nice article where he created a Custom File Download Action Result class. You only need to specify the virtual path of the file and the name to be saved as.

I used it once and here's my code.

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Download(int fileID)
        {
            Data.LinqToSql.File file = _fileService.GetByID(fileID);

            return new DownloadResult { VirtualPath = GetVirtualPath(file.Path),
                                        FileDownloadName = file.Name };
        }

In my example i was storing the physical path of the files so i used this helper method -that i found somewhere i can't remember- to convert it to a virtual path

        private string GetVirtualPath(string physicalPath)
        {
            string rootpath = Server.MapPath("~/");

            physicalPath = physicalPath.Replace(rootpath, "");
            physicalPath = physicalPath.Replace("\\", "/");

            return "~/" + physicalPath;
        }

Here's the full class as taken from Phill Haack's article

public class DownloadResult : ActionResult {

    public DownloadResult() {}

    public DownloadResult(string virtualPath) {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath {
        get;
        set;
    }

    public string FileDownloadName {
        get;
        set;
    }

    public override void ExecuteResult(ControllerContext context) {
        if (!String.IsNullOrEmpty(FileDownloadName)) {
            context.HttpContext.Response.AddHeader("content-disposition", 
            "attachment; filename=" + this.FileDownloadName)
        }

        string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
        context.HttpContext.Response.TransmitFile(filePath);
    }
}

Purpose of Unions in C and C++

The purpose of unions is rather obvious, but for some reason people miss it quite often.

The purpose of union is to save memory by using the same memory region for storing different objects at different times. That's it.

It is like a room in a hotel. Different people live in it for non-overlapping periods of time. These people never meet, and generally don't know anything about each other. By properly managing the time-sharing of the rooms (i.e. by making sure different people don't get assigned to one room at the same time), a relatively small hotel can provide accommodations to a relatively large number of people, which is what hotels are for.

That's exactly what union does. If you know that several objects in your program hold values with non-overlapping value-lifetimes, then you can "merge" these objects into a union and thus save memory. Just like a hotel room has at most one "active" tenant at each moment of time, a union has at most one "active" member at each moment of program time. Only the "active" member can be read. By writing into other member you switch the "active" status to that other member.

For some reason, this original purpose of the union got "overridden" with something completely different: writing one member of a union and then inspecting it through another member. This kind of memory reinterpretation (aka "type punning") is not a valid use of unions. It generally leads to undefined behavior is described as producing implementation-defined behavior in C89/90.

EDIT: Using unions for the purposes of type punning (i.e. writing one member and then reading another) was given a more detailed definition in one of the Technical Corrigenda to the C99 standard (see DR#257 and DR#283). However, keep in mind that formally this does not protect you from running into undefined behavior by attempting to read a trap representation.

How to get scrollbar position with Javascript?

If you are using jQuery there is a perfect function for you: .scrollTop()

doc here -> http://api.jquery.com/scrollTop/

note: you can use this function to retrieve OR set the position.

see also: http://api.jquery.com/?s=scroll

transparent navigation bar ios

Swift 4.2 Solution: For transparent Background:

  1. For General Approach:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.isTranslucent = true
    
    }
    
  2. For Specific Object:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        navBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navBar.shadowImage = UIImage()
        navBar.navigationBar.isTranslucent = true
    
    }
    

Hope it's useful.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Same-origin policy

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:

protocol://hostname:port/...

Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.

Examples

Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html

URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname 

Workaround

Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:

  • In your main page:

    const frame = document.getElementById('your-frame-id');
    frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
    

    The second argument to postMessage() can be '*' to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.

  • In your <iframe> (contained in the main page):

    window.addEventListener('message', event => {
        // IMPORTANT: check the origin of the data! 
        if (event.origin.startsWith('http://your-first-site.com')) { 
            // The data was sent from your site.
            // Data sent with postMessage is stored in event.data:
            console.log(event.data); 
        } else {
            // The data was NOT sent from your site! 
            // Be careful! Do not use it. This else branch is
            // here just for clarity, you usually shouldn't need it.
            return; 
        } 
    }); 
    

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.

Disabling same-origin policy in your browser

There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes).

Get record counts for all tables in MySQL database

If you want the exact numbers, use the following ruby script. You need Ruby and RubyGems.

Install following Gems:

$> gem install dbi
$> gem install dbd-mysql

File: count_table_records.rb

require 'rubygems'
require 'dbi'

db_handler = DBI.connect('DBI:Mysql:database_name:localhost', 'username', 'password')

# Collect all Tables
sql_1 = db_handler.prepare('SHOW tables;')
sql_1.execute
tables = sql_1.map { |row| row[0]}
sql_1.finish

tables.each do |table_name|
  sql_2 = db_handler.prepare("SELECT count(*) FROM #{table_name};")
  sql_2.execute
  sql_2.each do |row|
    puts "Table #{table_name} has #{row[0]} rows."
  end
  sql_2.finish
end

db_handler.disconnect

Go back to the command-line:

$> ruby count_table_records.rb

Output:

Table users has 7328974 rows.

How can I copy data from one column to another in the same table?

How about this

UPDATE table SET columnB = columnA;

This will update every row.

Difference between long and int data types

You're on a 32-bit machine or a 64-bit Windows machine. On my 64-bit machine (running a Unix-derivative O/S, not Windows), sizeof(int) == 4, but sizeof(long) == 8.

They're different types — sometimes the same size as each other, sometimes not.

(In the really old days, sizeof(int) == 2 and sizeof(long) == 4 — though that might have been the days before C++ existed, come to think of it. Still, technically, it is a legitimate configuration, albeit unusual outside of the embedded space, and quite possibly unusual even in the embedded space.)

What are the parameters for the number Pipe - Angular 2

From the DOCS

Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.

SYNTAX:

number_expression | number[:digitInfo[:locale]]

where expression is a number:

digitInfo is a string which has a following format:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
  • minIntegerDigits is the minimum number of integer digits to use.Defaults to 1
  • minFractionDigits is the minimum number of digits
  • after fraction. Defaults to 0. maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.
  • locale is a string defining the locale to use (uses the current LOCALE_ID by default)

DEMO

How to get status code from webclient?

This is what I use for expanding WebClient functionality. StatusCode and StatusDescription will always contain the most recent response code/description.

                /// <summary>
                /// An expanded web client that allows certificate auth and 
                /// the retrieval of status' for successful requests
                /// </summary>
                public class WebClientCert : WebClient
                {
                    private X509Certificate2 _cert;
                    public WebClientCert(X509Certificate2 cert) : base() { _cert = cert; }
                    protected override WebRequest GetWebRequest(Uri address)
                    {
                        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
                        if (_cert != null) { request.ClientCertificates.Add(_cert); }
                        return request;
                    }
                    protected override WebResponse GetWebResponse(WebRequest request)
                    {
                        WebResponse response = null;
                        response = base.GetWebResponse(request);
                        HttpWebResponse baseResponse = response as HttpWebResponse;
                        StatusCode = baseResponse.StatusCode;
                        StatusDescription = baseResponse.StatusDescription;
                        return response;
                    }
                    /// <summary>
                    /// The most recent response statusCode
                    /// </summary>
                    public HttpStatusCode StatusCode { get; set; }
                    /// <summary>
                    /// The most recent response statusDescription
                    /// </summary>
                    public string StatusDescription { get; set; }
                }

Thus you can do a post and get result via:

            byte[] response = null;
            using (WebClientCert client = new WebClientCert())
            {
                response = client.UploadValues(postUri, PostFields);
                HttpStatusCode code = client.StatusCode;
                string description = client.StatusDescription;
                //Use this information
            }

Read CSV with Scanner()

If you absolutely must use Scanner, then you must set its delimiter via its useDelimiter(...) method. Else it will default to using all white space as its delimiter. Better though as has already been stated -- use a CSV library since this is what they do best.

For example, this delimiter will split on commas with or without surrounding whitespace:

scanner.useDelimiter("\\s*,\\s*");

Please check out the java.util.Scanner API for more on this.

PHP Notice: Undefined offset: 1 with array when reading data

my quickest solution was to minus 1 to the length of the array as

  $len = count($data);

    for($i=1; $i<=$len-1;$i++){
      echo $data[$i];
    }

my offset was always the last value if the count was 140 then it will say offset 140 but after using the minus 1 everything was fine

How to escape a JSON string to have it in a URL?

Using encodeURIComponent():

var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),

NoSql vs Relational database

The biggest advantage of NoSQL over RDBMS is Scalability.
NoSQL databases can easily scale-out to many nodes, but for RDBMS it is very hard.
Scalability not only gives you more storage space but also much higher performance since many hosts work at the same time.

How to get the GL library/headers?

Windows

On Windows you need to include the gl.h header for OpenGL 1.1 support and link against OpenGL32.lib. Both are a part of the Windows SDK. In addition, you might want the following headers which you can get from http://www.opengl.org/registry .

  • <GL/glext.h> - OpenGL 1.2 and above compatibility profile and extension interfaces..
  • <GL/glcorearb.h> - OpenGL core profile and ARB extension interfaces, as described in appendix G.2 of the OpenGL 4.3 Specification. Does not include interfaces found only in the compatibility profile.
  • <GL/glxext.h> - GLX 1.3 and above API and GLX extension interfaces.
  • <GL/wglext.h> - WGL extension interfaces.

Linux

On Linux you need to link against libGL.so, which is usually a symlink to libGL.so.1, which is yet a symlink to the actual library/driver which is a part of your graphics driver. For example, on my system the actual driver library is named libGL.so.256.53, which is the version number of the nvidia driver I use. You also need to include the gl.h header, which is usually a part of a Mesa or Xorg package. Again, you might need glext.h and glxext.h from http://www.opengl.org/registry . glxext.h holds GLX extensions, the equivalent to wglext.h on Windows.

If you want to use OpenGL 3.x or OpenGL 4.x functionality without the functionality which were moved into the GL_ARB_compatibility extension, use the new gl3.h header from the registry webpage. It replaces gl.h and also glext.h (as long as you only need core functionality).

Last but not the least, glaux.h is not a header associated with OpenGL. I assume you've read the awful NEHE tutorials and just went along with it. Glaux is a horribly outdated Win32 library (1996) for loading uncompressed bitmaps. Use something better, like libPNG, which also supports alpha channels.

How to use 'find' to search for files created on a specific date?

As pointed out by Max, you can't, but checking files modified or accessed is not all that hard. I wrote a tutorial about this, as late as today. The essence of which is to use -newerXY and ! -newerXY:

Example: To find all files modified on the 7th of June, 2007:

$ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08

To find all files accessed on the 29th of september, 2008:

$ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30

Or, files which had their permission changed on the same day:

$ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30

If you don't change permissions on the file, 'c' would normally correspond to the creation date, though.

jQuery ajax success callback function definition

after few hours play with it and nearly become dull. miracle came to me, it work.

<pre>


var listname = [];   


 $.ajax({
    url : wedding, // change to your local url, this not work with absolute url
    success: function (data) {
       callback(data);
    }
});

function callback(data) {
      $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
             //   $('#displayImage1').append( "<img src='" + wedding + val +"'>" );
                 listname.push(val);
            } 
        });
}

function myfunction() {

alert (listname);

}

</pre>

Case insensitive string as HashMap key

Wouldn't it be better to "wrap" the String in order to memorize the hashCode. In the normal String class hashCode() is O(N) the first time and then it is O(1) since it is kept for future use.

public class HashWrap {
    private final String value;
    private final int hash;

    public String get() {
        return value;
    }

    public HashWrap(String value) {
        this.value = value;
        String lc = value.toLowerCase();
        this.hash = lc.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o instanceof HashWrap) {
            HashWrap that = (HashWrap) o;
            return value.equalsIgnoreCase(that.value);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.hash;
    }

    //might want to implement compare too if you want to use with SortedMaps/Sets.
}

This would allow you to use any implementation of Hashtable in java and to have O(1) hasCode().

How can I get current location from user in iOS

Try this Simple Steps....

NOTE: Please check device location latitude & logitude if you are using simulator means. By defaults its none only.

Step 1: Import CoreLocation framework in .h File

#import <CoreLocation/CoreLocation.h>

Step 2: Add delegate CLLocationManagerDelegate

@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}

Step 3: Add this code in class file

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self CurrentLocationIdentifier]; // call this method
}

Step 4: Method to detect current location

//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
    //---- For getting current gps location
    locationManager = [CLLocationManager new];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
    //------
}

Step 5: Get location using this method

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    currentLocation = [locations objectAtIndex:0];
    [locationManager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if (!(error))
         {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
             NSLog(@"\nCurrent Location Detected\n");
             NSLog(@"placemark %@",placemark);
             NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
             NSString *Address = [[NSString alloc]initWithString:locatedAt];
             NSString *Area = [[NSString alloc]initWithString:placemark.locality];
             NSString *Country = [[NSString alloc]initWithString:placemark.country];
             NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
             NSLog(@"%@",CountryArea);
         }
         else
         {
             NSLog(@"Geocode failed with error %@", error);
             NSLog(@"\nCurrent Location Not Detected\n");
             //return;
             CountryArea = NULL;
         }
         /*---- For more results 
         placemark.region);
         placemark.country);
         placemark.locality); 
         placemark.name);
         placemark.ocean);
         placemark.postalCode);
         placemark.subLocality);
         placemark.location);
          ------*/
     }];
}

Free Barcode API for .NET

I do recommend BarcodeLibrary

Here is a small piece of code of how to use it.

        BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
        {
            IncludeLabel = true,
            Alignment = AlignmentPositions.CENTER,
            Width = 300,
            Height = 100,
            RotateFlipType = RotateFlipType.RotateNoneFlipNone,
            BackColor = Color.White,
            ForeColor = Color.Black,
        };

        Image img = barcode.Encode(TYPE.CODE128B, "123456789");

Add line break within tooltips

Just use the entity code &#013; for a linebreak in a title attribute.

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

Yes lists and tuples are always ordered while dictionaries are not

Drawing an image from a data URL to a canvas

Given a data URL, you can create an image (either on the page or purely in JS) by setting the src of the image to your data URL. For example:

var img = new Image;
img.src = strDataURI;

The drawImage() method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.

You might use it like so:

var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
  ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;

Edit: I previously suggested in this space that it might not be necessary to use the onload handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload to use the new image, and then set the src—is necessary for some browsers to surely use the results.

Android - How to achieve setOnClickListener in Kotlin?

Button OnClickListener implementation from function in android using kotlin.

Very First Create Button View From .xml File

             `<Button
                android:id="@+id/btn2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Button2"
                android:layout_weight="0.5"/>`

//and create button instance in Activity

 private var btn1:Button?=null

or

//For Late Initialization can Follow like this,

private lateinit var btn1:Button

//in onCreate,

 btn1=findViewById(R.id.btn1) as Button

     btn1?.setOnClickListener { btn1Click() }

//implementing button OnClick event from Function,

 private fun btn1Click() {
        Toast.makeText(this, "button1", Toast.LENGTH_LONG).show()
    }

What is the difference between NULL, '\0' and 0?

A one-L NUL, it ends a string.

A two-L NULL points to no thing.

And I will bet a golden bull

That there is no three-L NULLL.

How do you deal with NUL?

Check if item is in an array / list

I'm also going to assume that you mean "list" when you say "array." Sven Marnach's solution is good. If you are going to be doing repeated checks on the list, then it might be worth converting it to a set or frozenset, which can be faster for each check. Assuming your list of strs is called subjects:

subject_set = frozenset(subjects)
if query in subject_set:
    # whatever

change the date format in laravel view page

You can use Carbon::createFromTimestamp

BLADE

{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}

Filter an array using a formula (without VBA)

Sounds like you're just trying to do a classic two-column lookup. http://www.dailydoseofexcel.com/archives/2009/04/21/vlookup-on-two-columns/

Tons of solutions for this, most simple is probably the following (which doesn't require an array formula):

=SUMPRODUCT((Lookup!A:A=Param!A1)*(Lookup!B:B=Param!B1)*(Lookup!C:C))

To translate your specific example, you would use:

=SUMPRODUCT((A1:A3=A2)*(B1:B3="B")*(C1:C3))

What strategies and tools are useful for finding memory leaks in .NET?

Are you using unmanaged code? If you are not using unmanaged code, according to Microsoft, memory leaks in the traditional sense are not possible.

Memory used by an application may not be released however, so an application's memory allocation may grow throughout the life of the application.

From How to identify memory leaks in the common language runtime at Microsoft.com

A memory leak can occur in a .NET Framework application when you use unmanaged code as part of the application. This unmanaged code can leak memory, and the .NET Framework runtime cannot address that problem.

Additionally, a project may only appear to have a memory leak. This condition can occur if many large objects (such as DataTable objects) are declared and then added to a collection (such as a DataSet). The resources that these objects own may never be released, and the resources are left alive for the whole run of the program. This appears to be a leak, but actually it is just a symptom of the way that memory is being allocated in the program.

For dealing with this type of issue, you can implement IDisposable. If you want to see some of the strategies for dealing with memory management, I would suggest searching for IDisposable, XNA, memory management as game developers need to have more predictable garbage collection and so must force the GC to do its thing.

One common mistake is to not remove event handlers that subscribe to an object. An event handler subscription will prevent an object from being recycled. Also, take a look at the using statement which allows you to create a limited scope for a resource's lifetime.

OSError - Errno 13 Permission denied

You need to change the directory permission so that web server process can change the directory.

  • To change ownership of the directory, use chown:

    chown -R user-id:group-id /path/to/the/directory
    
  • To see which user own the web server process (change httpd accordingly):

    ps aux | grep httpd | grep -v grep
    

    OR

    ps -efl | grep httpd | grep -v grep
    

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

Making an iframe responsive

With the following markup:

<div class="video"><iframe src="https://www.youtube.com/embed/StTqXEQ2l-Y"></iframe></div>

The following CSS makes the video full-width and 16:9:

.video {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
}

.video > .video__iframe {
    position: absolute;
    width: 100%;
    height: 100%;
    border: none;
  }
}

How to disable RecyclerView scrolling?

recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            // Stop only scrolling.
            return rv.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING;
        }
    });

Load CSV file with Spark

Spark 2.0.0+

You can use built-in csv data source directly:

spark.read.csv(
    "some_input_file.csv", header=True, mode="DROPMALFORMED", schema=schema
)

or

(spark.read
    .schema(schema)
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .csv("some_input_file.csv"))

without including any external dependencies.

Spark < 2.0.0:

Instead of manual parsing, which is far from trivial in a general case, I would recommend spark-csv:

Make sure that Spark CSV is included in the path (--packages, --jars, --driver-class-path)

And load your data as follows:

(df = sqlContext
    .read.format("com.databricks.spark.csv")
    .option("header", "true")
    .option("inferschema", "true")
    .option("mode", "DROPMALFORMED")
    .load("some_input_file.csv"))

It can handle loading, schema inference, dropping malformed lines and doesn't require passing data from Python to the JVM.

Note:

If you know the schema, it is better to avoid schema inference and pass it to DataFrameReader. Assuming you have three columns - integer, double and string:

from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType

schema = StructType([
    StructField("A", IntegerType()),
    StructField("B", DoubleType()),
    StructField("C", StringType())
])

(sqlContext
    .read
    .format("com.databricks.spark.csv")
    .schema(schema)
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .load("some_input_file.csv"))

How to give Jenkins more heap space when it´s started as a service under Windows?

I've added to /etc/sysconfig/jenkins (CentOS):

# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Xmx1024m -XX:MaxPermSize=512m"

For ubuntu the same config should be located in /etc/default

How to programmatically close a JFrame

 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

DLL and LIB files - what and why?

One important reason for creating a DLL/LIB rather than just compiling the code into an executable is reuse and relocation. The average Java or .NET application (for example) will most likely use several 3rd party (or framework) libraries. It is much easier and faster to just compile against a pre-built library, rather than having to compile all of the 3rd party code into your application. Compiling your code into libraries also encourages good design practices, e.g. designing your classes to be used in different types of applications.

Try/catch does not seem to have an effect

Edit: As stated in the comments, the following solution applies to PowerShell V1 only.

See this blog post on "Technical Adventures of Adam Weigert" for details on how to implement this.

Example usage (copy/paste from Adam Weigert's blog):

Try {
    echo " ::Do some work..."
    echo " ::Try divide by zero: $(0/0)"
} -Catch {
    echo "  ::Cannot handle the error (will rethrow): $_"
    #throw $_
} -Finally {
    echo " ::Cleanup resources..."
}

Otherwise you'll have to use exception trapping.

MIT vs GPL license

You are correct that the GPL is more restrictive than the MIT license.

You cannot include GPL code in a MIT licensed product. If you distribute a combined work that combines GPL and MIT code (except in some particular situations, e.g. 'mere aggregation'), that distribution must be compliant with the GPL.

You can include MIT licensed code in a GPL product. The whole combined work must be distributed in a way compliant with the GPL. If you have made changes to the MIT parts of the code, you would be required to publish the source for those changes if you distribute an application that contains GPL and MIT code.

If you are the copyright owner of the GPL code, you can of course choose to release that code under the MIT license instead - in that case it's your code and you can publish it under as many licenses as you want.

Could not resolve this reference. Could not locate the assembly

If anyone face this issue with some nuget packages, you can fix that by reinstalling the packages using the Package Manager Console:

Update-Package -reinstall 

How to run VBScript from command line without Cscript/Wscript

Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.

Check the answer -> Here

And here is an example:

Converter.bat

::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b

:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b

'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester

docker: executable file not found in $PATH

problem is glibc, which is not part of apline base iamge.

After adding it worked for me :)

Here are the steps to get the glibc

apk --no-cache add ca-certificates wget
wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub
wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-2.28-r0.apk
apk add glibc-2.28-r0.apk

Oracle 11g SQL to get unique values in one column of a multi-column query

select person, language     
from table A     
group by person, language  

will return unique rows

Should image size be defined in the img tag height/width attributes or in CSS?

The historical reason to define height/width in tags is so that browsers can size the actual <img> elements in the page even before the CSS and/or image resources are loaded. If you do not supply height and width explicitly the <img> element will be rendered at 0x0 until the browser can size it based on the file. When this happens it causes a visual reflow of the page once the image loads, and is compounded if you have multiple images on the page. Sizing the <img> via height/width creates a physical placeholder in the page flow at the correct size, enabling your content to load asynchronously without disrupting the user experience.

Alternately, if you are doing mobile-responsive design, which is a best practice these days, it's quite common to specify a width (or max-width) only and define the height as auto. That way when you define media queries (e.g. CSS) for different screen widths, you can simply adjust the image width and let the browser deal with keeping the image height / aspect ratio correct. This is sort of a middle ground approach, as you may get some reflow, but it allows you to support a broad range of screen sizes, so the benefit usually outweighs the negative.

Finally, there are times when you may not know the image size ahead of time (image src might be loaded dynamically, or can change during the lifetime of the page via script) in which case using CSS only makes sense.

The bottom line is that you need to understand the trade-offs and decide which strategy makes the most sense for what you're trying to achieve.

Print a variable in hexadecimal in Python

You mean you have a string of bytes in my_hex which you want to print out as hex numbers, right? E.g., let's take your example:

>>> my_string = "deadbeef"
>>> my_hex = my_string.decode('hex')  # python 2 only
>>> print my_hex
Þ ­ ¾ ï

This construction only works on Python 2; but you could write the same string as a literal, in either Python 2 or Python 3, like this:

my_hex = "\xde\xad\xbe\xef"

So, to the answer. Here's one way to print the bytes as hex integers:

>>> print " ".join(hex(ord(n)) for n in my_hex)
0xde 0xad 0xbe 0xef

The comprehension breaks the string into bytes, ord() converts each byte to the corresponding integer, and hex() formats each integer in the from 0x##. Then we add spaces in between.

Bonus: If you use this method with unicode strings (or Python 3 strings), the comprehension will give you unicode characters (not bytes), and you'll get the appropriate hex values even if they're larger than two digits.

Addendum: Byte strings

In Python 3 it is more likely you'll want to do this with a byte string; in that case, the comprehension already returns ints, so you have to leave out the ord() part and simply call hex() on them:

>>> my_hex = b'\xde\xad\xbe\xef'
>>> print(" ".join(hex(n) for n in my_hex))
0xde 0xad 0xbe 0xef

React Native absolute positioning horizontal centre

If you want to center one element itself you could use alignSelf:

logoImg: {
    position: 'absolute',
    alignSelf: 'center',
    bottom: '-5%'
}

This is an example (Note the logo parent is a view with position: relative)

enter image description here

SQL Server - copy stored procedures from one db to another

SELECT definition + char(13) + 'GO' FROM MyDatabase.sys.sql_modules s INNER JOIN MyDatabase.sys.procedures p ON [s].[object_id] = [p].[object_id] WHERE p.name LIKE 'Something%'" queryout "c:\SP_scripts.sql -S MyInstance -T -t -w

get the sp and execute it

What is the best IDE to develop Android apps in?

LATEST NEWS

Android Studio has officially come out of beta and been released. It is now the official IDE for Android Development - Eclipse won't be supported anymore. It is definitely the IDE of choice for Android Development. Link to download page: http://developer.android.com/sdk/index.html


NEWS

As of Google I/O 2013, the Android team has moved to IntelliJ Idea with the new Android Studio IDE: http://developer.android.com/sdk/installing/studio.html

Great to see Google endorse Idea. It is safe to say that Android Studio, and thus Idea, will from now on be the definitive IDE for Android development! :D


ORIGINAL ANSWER

IntelliJ now has support for Android. See Enabling Android Support from the JetBrains help page and the Google Code project page for the plugin. The Getting Started wiki page is pretty helpful.

If you are used to IntelliJ, I don't think it would be beneficial to switch IDEs just for Android tools. You can work on Android with any text editor (I use Vim). If you're more productive with a specific environment I don't see why you'd have to learn a new one. Not worth it in my opinion. Plus I'm a big IntelliJ fan. The IntelliJ plugin lets you make apk files and push the app to the emulator, that's all you need for Android app development. I'd say you're safe sticking with IntelliJ.

Update: there is now an official free IDE for IntelliJ android dev! http://blogs.jetbrains.com/idea/2010/10/intellij-idea-10-free-ide-for-android-development/

Callback functions in Java

If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.

public class Main {

    public interface Visitor{
        int doJob(int a, int b);
    }


    public static void main(String[] args) {
        Visitor adder = new Visitor(){
            public int doJob(int a, int b) {
                return a + b;
            }
        };

        Visitor multiplier = new Visitor(){
            public int doJob(int a, int b) {
                return a*b;
            }
        };

        System.out.println(adder.doJob(10, 20));
        System.out.println(multiplier.doJob(10, 20));

    }
}

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

The Function adds gaussian , salt-pepper , poisson and speckle noise in an image

Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n is uniform noise with specified mean & variance.


import numpy as np
import os
import cv2
def noisy(noise_typ,image):
   if noise_typ == "gauss":
      row,col,ch= image.shape
      mean = 0
      var = 0.1
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col,ch))
      gauss = gauss.reshape(row,col,ch)
      noisy = image + gauss
      return noisy
   elif noise_typ == "s&p":
      row,col,ch = image.shape
      s_vs_p = 0.5
      amount = 0.004
      out = np.copy(image)
      # Salt mode
      num_salt = np.ceil(amount * image.size * s_vs_p)
      coords = [np.random.randint(0, i - 1, int(num_salt))
              for i in image.shape]
      out[coords] = 1

      # Pepper mode
      num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
      coords = [np.random.randint(0, i - 1, int(num_pepper))
              for i in image.shape]
      out[coords] = 0
      return out
  elif noise_typ == "poisson":
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
  elif noise_typ =="speckle":
      row,col,ch = image.shape
      gauss = np.random.randn(row,col,ch)
      gauss = gauss.reshape(row,col,ch)        
      noisy = image + image * gauss
      return noisy

Disable browsers vertical and horizontal scrollbars

Using JQuery you can disable scrolling bar with this code :

$('body').on({
    'mousewheel': function(e) {
        if (e.target.id == 'el') return;
        e.preventDefault();
        e.stopPropagation();
     }
});

Also you can enable it again with this code :

 $('body').unbind('mousewheel');

What is the difference between HTML tags and elements?

Tags and Elements are not the same.

Elements


They are the pieces themselves, i.e. a paragraph is an element, or a header is an element, even the body is an element. Most elements can contain other elements, as the body element would contain header elements, paragraph elements, in fact pretty much all of the visible elements of the DOM.

Eg:

<p>This is the <span>Home</span> page</p>

Tags


Tags are not the elements themselves, rather they're the bits of text you use to tell the computer where an element begins and ends. When you 'mark up' a document, you generally don't want those extra notes that are not really part of the text to be presented to the reader. HTML borrows a technique from another language, SGML, to provide an easy way for a computer to determine which parts are "MarkUp" and which parts are the content. By using '<' and '>' as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e. the presence of '<' tells the browser 'this next bit is markup, pay attention'.

The browser sees the letters '

' and decides 'A new paragraph is starting, I'd better start a new line and maybe indent it'. Then when it sees '

' it knows that the paragraph it was working on is finished, so it should break the line there before going on to whatever is next.

- Opening tag.

- Closing tagenter image description here

VBA setting the formula for a cell

Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.

strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address

The workbook and worksheet that strProjectName references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

How to fix 'android.os.NetworkOnMainThreadException'?

You are able to move a part of your code into another thread to offload the main thread and avoid getting ANR, NetworkOnMainThreadException, IllegalStateException(e.g. Cannot access database on the main thread since it may potentially lock the UI for a long period of time).

There are some approaches that you should choose depends on the situation

Java Thread or Android HandlerThread

Java threads are one-time use only and die after executing its run method.

HandlerThread is a handy class for starting a new thread that has a looper.

AsyncTask (deprecated in API level 30)

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

Since Main thread monopolizes UI components it is not possible to access to some View, that is why Handler is on the rescue

Thread pool implementation ThreadPoolExecutor, ScheduledThreadPoolExecutor...

ThreadPoolExecutor class that implements ExecutorService which gives fine control on the thread pool (Eg, core pool size, max pool size, keep alive time, etc.)

ScheduledThreadPoolExecutor - a class that extends ThreadPoolExecutor. It can schedule tasks after a given delay or periodically.

FutureTask

FutureTask performs asynchronous processing, however, if the result is not ready yet or processing has not complete, calling get() will be block the thread

AsyncTaskLoaders

AsyncTaskLoaders as they solve a lot of problems that are inherent to AsyncTask

IntentService

This is the defacto choice for long running processing on Android, a good example would be to upload or download large files. The upload and download may continue even if the user exits the app and you certainly do not want to block the user from being able to use the app while these tasks are going on.

JobScheduler

Effectively, you have to create a Service and create a job using JobInfo.Builder that specifies your criteria for when to run the service.

RxJava

Library for composing asynchronous and event-based programs by using observable sequences.

Coroutines (Kotlin)

The main gist of it is, it makes asynchronous code looks so much like synchronous

Read more here, here, here, here

Printing everything except the first field with awk

If you're open to another Perl solution:

perl -ple 's/^(\S+)\s+(.*)/$2 $1/' file

overlay two images in android to set an imageview

ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya:

The logo is going to be on top of shazam background image.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget39"
android:layout_width="219px"
android:layout_height="225px"
android:src="@drawable/shazam_bkgd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageView
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shazam_logo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
</RelativeLayout>

Change <select>'s option and trigger events with JavaScript

These questions may be relevant to what you're asking for:

Here are my thoughts: You can stack up more than one call in your onclick event like this:

<select id="sel" onchange='alert("changed")'>
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true; alert("changed");' value="Change option to 2" />

You could also call a function to do this.

If you really want to call one function and have both behave the same way, I think something like this should work. It doesn't really follow the best practice of "Functions should do one thing and do it well", but it does allow you to call one function to handle both ways of changing the dropdown. Basically I pass (value) on the onchange event and (null, index of option) on the onclick event.

Here is the codepen: http://codepen.io/mmaynar1/pen/ZYJaaj

<select id="sel" onchange='doThisOnChange(this.value)'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" onclick='doThisOnChange(null,1);' value="Change option to 2"/>

<script>
doThisOnChange = function( value, optionIndex)
{
    if ( optionIndex != null )
    {
       var option = document.getElementById( "sel" ).options[optionIndex];
       option.selected = true;
       value = option.value;
    }
    alert( "Do something with the value: " + value );
}
</script>

Domain Account keeping locking out with correct password every few minutes

I have seen this problem when the user had set up a scheduled task to run under his account. He forgot to update the password on the task after he changed his account password. The scheduled task was trying to logon with the old password and kept locking out his account.

How to set text size of textview dynamically for different screens

I think You should use the textView.setTextSize(float size) method to set the size of text. textView.setText(arg) used to set the text in the Text View.

Can I get the name of the currently running function in JavaScript?

This should do it:

var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);

For the caller, just use caller.toString().

How do I measure request and response times at once using cURL?

Option 1. To measure total time:

curl -o /dev/null -s -w 'Total: %{time_total}s\n'  https://www.google.com

Sample output:

enter image description here

Option 2. To get time to establish connection, TTFB: time to first byte and total time:

curl -o /dev/null -s -w 'Establish Connection: %{time_connect}s\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n'  https://www.google.com

Sample output:

enter image description here

Ref: Get response time with curl

PHP - iterate on string characters

Hmm... There's no need to complicate things. The basics work great always.

    $string = 'abcdef';
    $len = strlen( $string );
    $x = 0;

Forward Direction:

while ( $len > $x ) echo $string[ $x++ ];

Outputs: abcdef

Reverse Direction:

while ( $len ) echo $string[ --$len ];

Outputs: fedcba

Assignment makes pointer from integer without cast

strToLower should return a char * instead of a char. Something like this would do.

char *strToLower(char *cString)

What's the difference between Thread start() and Runnable run()

First example: No multiple threads. Both execute in single (existing) thread. No thread creation.

R1 r1 = new R1();
R2 r2 = new R2();

r1 and r2 are just two different objects of classes that implement the Runnable interface and thus implement the run() method. When you call r1.run() you are executing it in the current thread.

Second example: Two separate threads.

Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);

t1 and t2 are objects of the class Thread. When you call t1.start(), it starts a new thread and calls the run() method of r1 internally to execute it within that new thread.

How to AUTO_INCREMENT in db2?

You will have to create an auto-increment field with the sequence object (this object generates a number sequence).

Use the following CREATE SEQUENCE syntax:

  CREATE SEQUENCE seq_person
  MINVALUE 1
  START WITH 1
  INCREMENT BY 1
  CACHE 10

The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.

To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):

  INSERT INTO Persons (P_Id,FirstName,LastName)
  VALUES (seq_person.nextval,'Lars','Monsen')

The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.

However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.

If you had a row named full_brand_name and you wanted to use the first two letters as a short name in the field small_name you could use:

CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
  SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END

SQL to Entity Framework Count Group-By

with EF 6.2 it worked for me

  var query = context.People
               .GroupBy(p => new {p.name})
               .Select(g => new { name = g.Key.name, count = g.Count() });

How can I debug a .BAT script?

Did you try to reroute the result to a file? Like whatever.bat >log.txt

You have to make sure that in this case every other called script is also logging to the file like >>log.txt

Also if you put a date /T and time /T in the beginning and in the end of that batch file, you will get the times it was at that point and you can map your script running time and order.

Test iOS app on device without apple developer program or jailbreak

Go to Build Settings, under Code Signing, set Code Signing Identity as iOS Developer & Provisioning Profile as Automatic.

Select your device (now visible) from drop down list and run your app.

enter image description here

Install msi with msiexec in a Specific Directory

msiexec /i "msi path" INSTALLDIR="C:\myfolder" /q

Only this variant worked well.

link_to method and click event in Rails

just use

=link_to "link", "javascript:function()"

How to use refs in React with Typescript

From React type definition

    type ReactInstance = Component<any, any> | Element;
....
    refs: {
            [key: string]: ReactInstance
    };

So you can access you refs element as follow

stepInput = () => ReactDOM.findDOMNode(this.refs['stepInput']);

without redefinition of refs index.

As @manakor mentioned you can get error like

Property 'stepInput' does not exist on type '{ [key: string]: Component | Element; }

if you redefine refs(depends on IDE and ts version you use)

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

How to add an object to an array

You are running into a scope problem if you use your code as such. You have to declare it outside the functions if you plan to use it between them (or if calling, pass it as a parameter).

var a = new Array();
var b = new Object();

function first() {
a.push(b);
// Alternatively, a[a.length] = b
// both methods work fine
}

function second() {
var c = a[0];
}

// code
first();
// more code
second();
// even more code

PHP and MySQL Select a Single Value

It is quite evident that there is only a single id corresponding to a single username because username is unique.

But the actual problem lies in the query itself-

$sql = "SELECT 'id' FROM Users WHERE username='$name'";

O/P

+----+
| id |
+----+
| id |
+----+

i.e. 'id' actually is treated as a string not as the id attribute.

Correct synatx:

$sql = "SELECT `id` FROM Users WHERE username='$name'";

i.e. use grave accent(`) instead of single quote(').

or

$sql = "SELECT id FROM Users WHERE username='$name'";

Complete code

session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;

Get a list of distinct values in List

Distinct the Note class by Author

var DistinctItems = Note.GroupBy(x => x.Author).Select(y => y.First());

foreach(var item in DistinctItems)
{
    //Add to other List
}

Show/Hide Multiple Divs with Jquery

Check This Example

Html:

<div class="buttons">
<a class="button" id="showall">All</a>
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>

<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>

Javascript:

$('#showall').click(function(){
    $('div').show();
});

$('#showdiv1').click(function(){
    $('div[id^=div]').hide();
    $('#div1').show();
});
$('#showdiv2').click(function(){
    $('div[id^=div]').hide();
    $('#div2').show();
});

$('#showdiv3').click(function(){
    $('div[id^=div]').hide();
    $('#div3').show();
});

$('#showdiv4').click(function(){
    $('div[id^=div]').hide();
    $('#div4').show();

});

Getting the text that follows after the regex match

Your regex "sentence(.*)" is right. To retrieve the contents of the group in parenthesis, you would call:

Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
   String s = m.group(1); // " that is awesome"
}

Note the use of m.find() in this case (attempts to find anywhere on the string) and not m.matches() (would fail because of the prefix "some lame"; in this case the regex would need to be ".*sentence(.*)")

SQL Server Operating system error 5: "5(Access is denied.)"

This is Windows related issue where SQL Server does not have the appropriate permission to the folder that contains .bak file and hence this error.

The easiest work around is to copy your .bak file to default SQL backup location which has all the necessary permissions. You do not need to fiddle with anything else. In SQL SERVER 2012, this location is

D:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup (SQL 2012)
C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup (SQL 2014)
C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Backup (SQL 2016)

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

Error occurred during initialization of boot layer FindException: Module not found

The reason behind this is that meanwhile creating your own class, you had also accepted to create a default class as prescribed by your IDE and after writing your code in your own class, you are getting such an error. In order to eliminate this, go to the PROJECT folder ? src ? Default package. Keep only one class (in which you had written code) and delete others.

After that, run your program and it will definitely run without any error.

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

SQL Server: use CASE with LIKE

SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname, 
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE 
Lname END AS LnameTrue FROM dbo.____Fname_Lname

No signing certificate "iOS Distribution" found

Tried the above solutions with no luck ... restarted my mac solved the issue...

Passing a URL with brackets to curl

Never mind, I found it in the docs:

-g/--globoff
              This  option  switches  off  the "URL globbing parser". When you set this option, you can
              specify URLs that contain the letters {}[] without having them being interpreted by  curl
              itself.  Note  that  these  letters  are not normal legal URL contents but they should be
              encoded according to the URI standard.

Could not reliably determine the server's fully qualified domain name

Under Debian Squeeze;

  1. Edit Apache2 conf file : vim /etc/apache2/apache2.conf
  2. Insert the following line at the apache2.conf: ServerName localhost
  3. Restart Apache2: apache2ctl restart or /etc/init.d/apache2 restart

Should work fine (it did solve the problem in my case)

tks noodl for the link on the different layouts. :)

Can Flask have optional URL parameters?

Almost the same as Audrius cooked up some months ago, but you might find it a bit more readable with the defaults in the function head - the way you are used to with python:

@app.route('/<user_id>')
@app.route('/<user_id>/<username>')
def show(user_id, username='Anonymous'):
    return user_id + ':' + username

What is the Java equivalent of PHP var_dump?

The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.

PHP error: Notice: Undefined index:

Are you putting the form processor in the same script as the form? If so, it is attempting to process before the post values are set (everything is executing).

Wrap all the processing code in a conditional that checks if the form has even been sent.

if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
//process form!
}else{
//show form, don't process yet!  You can break out of php here and render your form
}

Scripts execute from the top down when programming procedurally. You need to make sure the program knows to ignore the processing logic if the form has not been sent. Likewise, after processing, you should redirect to a success page with something like

header('Location:http://www.yourdomainhere.com/formsuccess.php');

I would not get into the habit of supressing notices or errors.

Please don't take offense if I suggest that if you are having these problems and you are attempting to build a shopping cart, that you instead utilize a mature ecommerce solution like Magento or OsCommerce. A shopping cart is an interface that requires a high degree of security and if you are struggling with these kind of POST issues I can guarantee you will be fraught with headaches later. There are many great stable releases, some as simple as mere object models, that are available for download.

Reading an Excel file in PHP

It depends on how you want to use the data in the excel file. If you want to import it into mysql, you could simply save it as a CSV formatted file and then use fgetcsv to parse it.

What does getActivity() mean?

Two likely definitions:

How to clear an EditText on click?

If you want to have text in the edit text and remove it like you say, try:

    final EditText text_box = (EditText) findViewById(R.id.input_box);
    text_box.setOnFocusChangeListener(new OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View v, boolean hasFocus) 
        {
            if (hasFocus==true)
            {
                if (text_box.getText().toString().compareTo("Enter Text")==0)
                {
                    text_box.setText("");
                }
            }
        }
    });

How to enter a multi-line command

To expand on cristobalito's answer:

I assume you're talking about on the command-line - if it's in a script, then a new-line >acts as a command delimiter.

On the command line, use a semi-colon ';'

For example:

Sign a PowerShell script on the command-line. No line breaks.

powershell -Command "&{$cert=Get-ChildItem –Path cert:\CurrentUser\my -codeSigningCert ; Set-AuthenticodeSignature -filepath Z:\test.ps1 -Cert $cert}

Can we create an instance of an interface in Java?

No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.

Get the first key name of a JavaScript object

In Javascript you can do the following:

Object.keys(ahash)[0];

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

If you are using management studio and have the query analyzer window open you can drag the table name to the query analyzer window and ... bingo! you get the table script. I've not tried this in SQL2008

How to conclude your merge of a file?

The easiest solution I found for this:

git commit -m "fixing merge conflicts"
git push

Jquery selector input[type=text]')

$('input[type=text],select', '.sys');

for looping:

$('input[type=text],select', '.sys').each(function() {
   // code
});

Display a loading bar before the entire page is loaded

Use a div #overlay with your loading info / .gif that will cover all your page:

<div id="overlay">
     <img src="loading.gif" alt="Loading" />
     Loading...
</div>

jQuery:

$(window).load(function(){
   // PAGE IS FULLY LOADED  
   // FADE OUT YOUR OVERLAYING DIV
   $('#overlay').fadeOut();
});

Here's an example with a Loading bar:

jsBin demo

  <div id="overlay">
    <div id="progstat"></div>
    <div id="progress"></div>
  </div>

  <div id="container">
    <img src="http://placehold.it/3000x3000/cf5">
  </div>

CSS:

*{margin:0;}
body{ font: 200 16px/1 sans-serif; }
img{ width:32.2%; }

#overlay{
  position:fixed;
  z-index:99999;
  top:0;
  left:0;
  bottom:0;
  right:0;
  background:rgba(0,0,0,0.9);
  transition: 1s 0.4s;
}
#progress{
  height:1px;
  background:#fff;
  position:absolute;
  width:0;                /* will be increased by JS */
  top:50%;
}
#progstat{
  font-size:0.7em;
  letter-spacing: 3px;
  position:absolute;
  top:50%;
  margin-top:-40px;
  width:100%;
  text-align:center;
  color:#fff;
}

JavaScript:

;(function(){
  function id(v){ return document.getElementById(v); }
  function loadbar() {
    var ovrl = id("overlay"),
        prog = id("progress"),
        stat = id("progstat"),
        img = document.images,
        c = 0,
        tot = img.length;
    if(tot == 0) return doneLoading();

    function imgLoaded(){
      c += 1;
      var perc = ((100/tot*c) << 0) +"%";
      prog.style.width = perc;
      stat.innerHTML = "Loading "+ perc;
      if(c===tot) return doneLoading();
    }
    function doneLoading(){
      ovrl.style.opacity = 0;
      setTimeout(function(){ 
        ovrl.style.display = "none";
      }, 1200);
    }
    for(var i=0; i<tot; i++) {
      var tImg     = new Image();
      tImg.onload  = imgLoaded;
      tImg.onerror = imgLoaded;
      tImg.src     = img[i].src;
    }    
  }
  document.addEventListener('DOMContentLoaded', loadbar, false);
}());

How do I auto size a UIScrollView to fit its content

For swift4 using reduce:

self.scrollView.contentSize = self.scrollView.subviews.reduce(CGRect.zero, {
   return $0.union($1.frame)
}).size

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

I forgot to annotate my component with "@Input" (Doh!)

book-list.component.html (Offending code):

<app-book-item
  *ngFor="let book of book$ | async"
  [book]="book">  <-- Can't bind to 'book' since it isn't a known property of 'app-book-item'
</app-book-item>

Corrected version of book-item.component.ts:

import { Component, OnInit, Input } from '@angular/core';

import { Book } from '../model/book';
import { BookService } from '../services/book.service';

@Component({
  selector: 'app-book-item',
  templateUrl: './book-item.component.html',
  styleUrls: ['./book-item.component.css']
})
export class BookItemComponent implements OnInit {

  @Input()
  public book: Book;

  constructor(private bookService: BookService)  { }

  ngOnInit() {}

}

Git: How to find a deleted file in the project commit history?

Here is my solution:

git log --all --full-history --oneline -- <RELATIVE_FILE_PATH>
git checkout <COMMIT_SHA>^ -- <RELATIVE_FILE_PATH>

Iterating a JavaScript object's properties using jQuery

Late, but can be done by using Object.keys like,

_x000D_
_x000D_
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
  ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
_x000D_
_x000D_

What is the difference between Serialization and Marshaling?

My understanding of marshalling is different to the other answers.

Serialization:

To Produce or rehydrate a wire-format version of an object graph utilizing a convention.

Marshalling:

To Produce or rehydrate a wire-format version of an object graph by utilizing a mapping file, so that the results can be customized. The tool may start by adhering to a convention, but the important difference is the ability to customize results.

Contract First Development:

Marshalling is important within the context of contract first development.

  • Its possible to make changes to an internal object graph, while keeping the external interface stable over time. This way all of the service subscribers won't have to be modified for every trivial change.
  • Its possible to map the results across different languages. For example from the property name convention of one language ('property_name') to another ('propertyName').

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

You could resolve the problem with:

for line in open(your_file_path, 'rb'):

'rb' is reading the file in binary mode. Read more here.

get parent's view from a layout

Check my answer here

The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view

jQuery OR Selector?

Use a comma.

'.classA, .classB'

You may choose to omit the space.

Typescript es6 import module "File is not a module error"

In addition to Tim's answer, this issue occurred for me when I was splitting up a refactoring a file, splitting it up into their own files.

VSCode, for some reason, indented parts of my [class] code, which caused this issue. This was hard to notice at first, but after I realised the code was indented, I formatted the code and the issue disappeared.

for example, everything after the first line of the Class definition was auto-indented during the paste.

export class MyClass extends Something<string> {
    public blah: string = null;

    constructor() { ... }
  }

How to allow only numbers in textbox in mvc4 razor

for decimal values greater than zero, HTML5 works as follows:

<input id="txtMyDecimal" min="0" step="any" type="number">

CORS - How do 'preflight' an httprequest?

During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

For example, suppose the browser makes a request with the following headers:

Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Your server should then respond with the following headers:

Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.

Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

Android TabLayout Android Design

I've just managed to setup new TabLayout, so here are the quick steps to do this (????)?*:???

  1. Add dependencies inside your build.gradle file:

    dependencies {
        compile 'com.android.support:design:23.1.1'
    }
    
  2. Add TabLayout inside your layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"/>
    
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    </LinearLayout>
    
  3. Setup your Activity like this:

    import android.os.Bundle;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    
    public class TabLayoutActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_pull_to_refresh);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
            ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    
            if (toolbar != null) {
                setSupportActionBar(toolbar);
            }
    
            viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
            tabLayout.setupWithViewPager(viewPager);
        }
    
        public class SectionPagerAdapter extends FragmentPagerAdapter {
    
            public SectionPagerAdapter(FragmentManager fm) {
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return new FirstTabFragment();
                    case 1:
                    default:
                        return new SecondTabFragment();
                }
            }
    
            @Override
            public int getCount() {
                return 2;
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "First Tab";
                    case 1:
                    default:
                        return "Second Tab";
                }
            }
        }
    
    }
    

What is the use of hashCode in Java?

hashCode

Whenever you override equals(), you are also expected to override hashCode(). The hash code is used when storing the object as a key in a map.

A hash code is a number that puts instances of a class into a finite number of categories. Imagine that I gave you a deck of cards, and I told you that I was going to ask you for specific cards and I want to get the right card back quickly. You have as long as you want to prepare, but I’m in a big hurry when I start asking for cards. You might make 13 piles of cards: All of the aces in one pile, all the twos in another pile, and so forth. That way, when I ask for the five of hearts, you can just pull the right card out of the four cards in the pile with fives. It is certainly faster than going through the whole deck of 52 cards! You could even make 52 piles if you had enough space on the table.

reference : OCP Oracle Certified Professional Java SE 8 Programmer II

Check if String / Record exists in DataTable

I think that if your "item_manuf_id" is the primary key of the DataTable you could use the Find method ...

string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
 //You have it ...
 }

How do I protect javascript files?

Good question with a simple answer: you can't!

Javascript is a client-side programming language, therefore it works on the client's machine, so you can't actually hide anything from the client.
Obfuscating your code is a good solution, but it's not enough, because, although it is hard, someone could decipher your code and "steal" your script.
There are a few ways of making your code hard to be stolen, but as i said nothing is bullet-proof.

Off the top of my head, one idea is to restrict access to your external js files from outside the page you embed your code in. In that case, if you have

<script type="text/javascript" src="myJs.js"></script>

and someone tries to access the myJs.js file in browser, he shouldn't be granted any access to the script source.
For example, if your page is written in php, you can include the script via the include function and let the script decide if it's safe" to return it's source.
In this example, you'll need the external "js" (written in php) file myJs.php :

<?php
    $URL = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    if ($URL != "my-domain.com/my-page.php")
    die("/\*sry, no acces rights\*/");
?>
// your obfuscated script goes here

that would be included in your main page my-page.php :

<script type="text/javascript">
    <?php include "myJs.php"; ?>;
</script> 

This way, only the browser could see the js file contents.

Another interesting idea is that at the end of your script, you delete the contents of your dom script element, so that after the browser evaluates your code, the code disappears :

<script id="erasable" type="text/javascript">
    //your code goes here
    document.getElementById('erasable').innerHTML = "";
</script>

These are all just simple hacks that cannot, and I can't stress this enough : cannot, fully protect your js code, but they can sure piss off someone who is trying to "steal" your code.

Update:

I recently came across a very interesting article written by Patrick Weid on how to hide your js code, and he reveals a different approach: you can encode your source code into an image! Sure, that's not bullet proof either, but it's another fence that you could build around your code.
The idea behind this approach is that most browsers can use the canvas element to do pixel manipulation on images. And since the canvas pixel is represented by 4 values (rgba), each pixel can have a value in the range of 0-255. That means that you can store a character (actual it's ascii code) in every pixel. The rest of the encoding/decoding is trivial.
Thanks, Patrick!

How do I clear a search box with an 'x' in bootstrap 3?

Here is my working solution with search and clear icon for Angularjs\Bootstrap with CSS.

    <div class="form-group has-feedback has-clear">
                    <input type="search" class="form-control removeXicon" ng-model="filter" style="max-width:100%" placeholder="Search..." />
                    <div ng-switch on="!!filter">
                        <div ng-switch-when="false">
                            <span class="glyphicon glyphicon-search form-control-feedback"></span>
                        </div>
                        <div ng-switch-when="true">
                            <span class="glyphicon glyphicon-remove-sign form-control-feedback" ng-click="$parent.filter = ''" style="pointer-events: auto; text-decoration: none;cursor: pointer;"></span>
                        </div>
                    </div>                        
                </div>

------

CSS

/* hide the built-in IE10+ clear field icon */
.removeXicon::-ms-clear {
  display: none;
}

/* hide the built-in chrome clear field icon */
.removeXicon::-webkit-search-decoration,
.removeXicon::-webkit-search-cancel-button,
.removeXicon::-webkit-search-results-button,
.removeXicon::-webkit-search-results-decoration { 
      display: none; 
}

How to convert a const char * to std::string

This page on string::string gives two potential constructors that would do what you want:

string ( const char * s, size_t n );
string ( const string& str, size_t pos, size_t n = npos );

Example:

#include<cstdlib>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;

int main(){

    char* p= (char*)calloc(30, sizeof(char));
    strcpy(p, "Hello world");

    string s(p, 15);
    cout << s.size() << ":[" << s << "]" << endl;
    string t(p, 0, 15);
    cout << t.size() << ":[" << t << "]" << endl;

    free(p);
    return 0;
}

Output:

15:[Hello world]
11:[Hello world]

The first form considers p to be a simple array, and so will create (in our case) a string of length 15, which however prints as a 11-character null-terminated string with cout << .... Probably not what you're looking for.

The second form will implicitly convert the char* to a string, and then keep the maximum between its length and the n you specify. I think this is the simplest solution, in terms of what you have to write.

MySQLi prepared statements error reporting

Not sure if this answers your question or not. Sorry if not

To get the error reported from the mysql database about your query you need to use your connection object as the focus.

so:

echo $mysqliDatabaseConnection->error

would echo the error being sent from mysql about your query.

Hope that helps

How to trim a string to N chars in Javascript?

I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.

String.prototype.trimEllip = function (length) {
  return this.length > length ? this.substring(0, length) + "..." : this;
}

And use it like:

var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)

How to refresh materialized view in oracle

Best option is to use the '?' argument for the method. This way DBMS_MVIEW will choose the best way to refresh, so it'll do the fastest refresh it can for you. , and won't fail if you try something like method=>'f' when you actually need a complete refresh. :-)

from the SQL*Plus prompt:

EXEC DBMS_MVIEW.REFRESH('my_schema.my_mview', method => '?');

Python : Trying to POST form using requests

I was having problems here (i.e. sending form-data whilst uploading a file) until I used the following:

files = {'file': (filename, open(filepath, 'rb'), 'text/xml'),
         'Content-Disposition': 'form-data; name="file"; filename="' + filename + '"',
         'Content-Type': 'text/xml'}

That's the input that ended up working for me. In Chrome Dev Tools -> Network tab, I clicked the request I was interested in. In the Headers tab, there's a Form Data section, and it showed both the Content-Disposition and the Content-Type headers being set there.

I did NOT need to set headers in the actual requests.post() command for this to succeed (including them actually caused it to fail)

How to find files that match a wildcard string in Java?

As posted in another answer, the wildcard library works for both glob and regex filename matching: http://code.google.com/p/wildcard/

I used the following code to match glob patterns including absolute and relative on *nix style file systems:

String filePattern = String baseDir = "./";
// If absolute path. TODO handle windows absolute path?
if (filePattern.charAt(0) == File.separatorChar) {
    baseDir = File.separator;
    filePattern = filePattern.substring(1);
}
Paths paths = new Paths(baseDir, filePattern);
List files = paths.getFiles();

I spent some time trying to get the FileUtils.listFiles methods in the Apache commons io library (see Vladimir's answer) to do this but had no success (I realise now/think it can only handle pattern matching one directory or file at a time).

Additionally, using regex filters (see Fabian's answer) for processing arbitrary user supplied absolute type glob patterns without searching the entire file system would require some preprocessing of the supplied glob to determine the largest non-regex/glob prefix.

Of course, Java 7 may handle the requested functionality nicely, but unfortunately I'm stuck with Java 6 for now. The library is relatively minuscule at 13.5kb in size.

Note to the reviewers: I attempted to add the above to the existing answer mentioning this library but the edit was rejected. I don't have enough rep to add this as a comment either. Isn't there a better way...

SQL Server Group By Month

DECLARE @start [datetime] = 2010/4/1;

Should be...

DECLARE @start [datetime] = '2010-04-01';

The one you have is dividing 2010 by 4, then by 1, then converting to a date. Which is the 57.5th day from 1900-01-01.

Try SELECT @start after your initialisation to check if this is correct.

How can I install Visual Studio Code extensions offline?

As of today the download URL for the latest version of the extension is embedded verbatim in the source of the page on Marketplace, e.g. source at URL:

https://marketplace.visualstudio.com/items?itemName=lukasz-wronski.ftp-sync

contains string:

https://lukasz-wronski.gallerycdn.vsassets.io/extensions/lukasz-wronski/ftp-sync/0.3.3/1492669004156/Microsoft.VisualStudio.Services.VSIXPackage

I use following Python regexp to extract dl URL:

urlre = re.search(r'source.+(http.+Microsoft\.VisualStudio\.Services\.VSIXPackage)', content)
if urlre:
    return urlre.group(1)

C++ display stack trace on exception

Since the stack is already unwound when entering the catch block, the solution in my case was to not catch certain exceptions which then lead to a SIGABRT. In the signal handler for SIGABRT I then fork() and execl() either gdb (in debug builds) or Google breakpads stackwalk (in release builds). Also I try to only use signal handler safe functions.

GDB:

static const char BACKTRACE_START[] = "<2>--- backtrace of entire stack ---\n";
static const char BACKTRACE_STOP[] = "<2>--- backtrace finished ---\n";

static char *ltrim(char *s)
{
    while (' ' == *s) {
        s++;
    }
    return s;
}

void Backtracer::print()
{
    int child_pid = ::fork();
    if (child_pid == 0) {
        // redirect stdout to stderr
        ::dup2(2, 1);

        // create buffer for parent pid (2+16+1 spaces to allow up to a 64 bit hex parent pid)
        char pid_buf[32];
        const char* stem = "                   ";
        const char* s = stem;
        char* d = &pid_buf[0];
        while (static_cast<bool>(*s))
        {
            *d++ = *s++;
        }
        *d-- = '\0';
        char* hexppid = d;

        // write parent pid to buffer and prefix with 0x
        int ppid = getppid();
        while (ppid != 0) {
            *hexppid = ((ppid & 0xF) + '0');
            if(*hexppid > '9') {
                *hexppid += 'a' - '0' - 10;
            }
            --hexppid;
            ppid >>= 4;
        }
        *hexppid-- = 'x';
        *hexppid = '0';

        // invoke GDB
        char name_buf[512];
        name_buf[::readlink("/proc/self/exe", &name_buf[0], 511)] = 0;
        ssize_t r = ::write(STDERR_FILENO, &BACKTRACE_START[0], sizeof(BACKTRACE_START));
        (void)r;
        ::execl("/usr/bin/gdb",
                "/usr/bin/gdb", "--batch", "-n", "-ex", "thread apply all bt full", "-ex", "quit",
                &name_buf[0], ltrim(&pid_buf[0]), nullptr);
        ::exit(1); // if GDB failed to start
    } else if (child_pid == -1) {
        ::exit(1); // if forking failed
    } else {
        // make it work for non root users
        if (0 != getuid()) {
            ::prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
        }
        ::waitpid(child_pid, nullptr, 0);
        ssize_t r = ::write(STDERR_FILENO, &BACKTRACE_STOP[0], sizeof(BACKTRACE_STOP));
        (void)r;
    }
}

minidump_stackwalk:

static bool dumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* context, bool succeeded)
{
    int child_pid = ::fork();
    if (child_pid == 0) {
        ::dup2(open("/dev/null", O_WRONLY), 2); // ignore verbose output on stderr
        ssize_t r = ::write(STDOUT_FILENO, &MINIDUMP_STACKWALK_START[0], sizeof(MINIDUMP_STACKWALK_START));
        (void)r;
        ::execl("/usr/bin/minidump_stackwalk", "/usr/bin/minidump_stackwalk", descriptor.path(), "/usr/share/breakpad-syms", nullptr);
        ::exit(1); // if minidump_stackwalk failed to start
    } else if (child_pid == -1) {
        ::exit(1); // if forking failed
    } else {
        ::waitpid(child_pid, nullptr, 0);
        ssize_t r = ::write(STDOUT_FILENO, &MINIDUMP_STACKWALK_STOP[0], sizeof(MINIDUMP_STACKWALK_STOP));
        (void)r;
    }
    ::remove(descriptor.path()); // this is not signal safe anymore but should still work
    return succeeded;
}

Edit: To make it work for breakpad I also had to add this:

std::set_terminate([]()
{
    ssize_t r = ::write(STDERR_FILENO, EXCEPTION, sizeof(EXCEPTION));
    (void)r;
    google_breakpad::ExceptionHandler::WriteMinidump(std::string("/tmp"), dumpCallback, NULL);
    exit(1); // avoid creating a second dump by not calling std::abort
});

Source: How to get a stack trace for C++ using gcc with line number information? and Is it possible to attach gdb to a crashed process (a.k.a "just-in-time" debugging)