Programs & Examples On #Cfrunloop

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

UICollectionView - dynamic cell height?

TL;DR: Scan down to image, and then check out working project here.

Updating my answer for a simpler solution that I found..

In my case, I wanted to fix the width, and have variable height cells. I wanted a drop in, reusable solution that handled rotation and didn't require a lot of intervention.

What I arrived at, was override (just) systemLayoutFitting(...) in the collection cell (in this case a base class for me), and first defeat UICollectionView's effort to set the wrong dimension on contentView by adding a constraint for the known dimension, in this case, the width.

class EstimatedWidthCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.translatesAutoresizingMaskIntoConstraints = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        contentView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func systemLayoutSizeFitting(
        _ targetSize: CGSize, withHorizontalFittingPriority
        horizontalFittingPriority: UILayoutPriority,
        verticalFittingPriority: UILayoutPriority) -> CGSize {

        width.constant = targetSize.width

and then return the final size for the cell - used for (and this feels like a bug) the dimension of the cell itself, but not contentView - which is otherwise constrained to a conflicting size (hence the constraint above). To calculate the correct cell size, I use a lower priority for the dimension that I wanted to float, and I get back the height required to fit the content within the width to which I want to fix:

        let size = contentView.systemLayoutSizeFitting(
            CGSize(width: targetSize.width, height: 1),
            withHorizontalFittingPriority: .required,
            verticalFittingPriority: verticalFittingPriority)

        print("\(#function) \(#line) \(targetSize) -> \(size)")
        return size
    }

    lazy var width: NSLayoutConstraint = {
        return contentView.widthAnchor
            .constraint(equalToConstant: bounds.size.width)
            .isActive(true)
    }()
}

But where does this width come from? It is configured via the estimatedItemSize on the collection view's flow layout:

lazy var collectionView: UICollectionView = {
    let view = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
    view.backgroundColor = .cyan
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

lazy var layout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    let width = view.bounds.size.width // should adjust for inset
    layout.estimatedItemSize = CGSize(width: width, height: 10)
    layout.scrollDirection = .vertical
    return layout
}()

Finally, to handle rotation, I implement trailCollectionDidChange to invalidate the layout:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    layout.estimatedItemSize = CGSize(width: view.bounds.size.width, height: 10)
    layout.invalidateLayout()
    super.traitCollectionDidChange(previousTraitCollection)
}

The final result looks like this:

enter image description here

And I have published a working sample here.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

This started to happen for me on Xcode 7, and I had no outlets with yellow flags that I could delete.

The only thing that worked for me was replacing this line in the AppDelegate:

[window addSubview:viewController.view];

to:

[window setRootViewController:viewController];

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

End of File (EOF) in C

EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.

The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.

The value of EOF is -1 because it has to be different from any return value from getchar that is an actual character. So getchar returns any character value as an unsigned char, converted to int, which will therefore be non-negative.

If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar() will return EOF, and hence getchar() != EOF will be false, and the loop will terminate.

[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.

How do I set default value of select box in angularjs

  <select ng-model="selectedCar" ><option ng-repeat="car in cars "  value="{{car.model}}">{{car.model}}</option></select>
<script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.cars = [{model : "Ford Mustang", color : "red"}, {model : "Fiat 500", color : "white"},{model : "Volvo XC90", color : "black"}];
$scope.selectedCar=$scope.cars[0].model ;});

Fragment MyFragment not attached to Activity

In my case fragment methods have been called after

getActivity().onBackPressed();

Does :before not work on img elements?

I think the best way to look at why this doesn't work is that :before and :after insert their content before or after the content within the tag you're applying them to. So it works with divs or spans (or most other tags) because you can put content inside them.

<div>
:before
Content
:after
</div>

However, an img is a self-contained, self-closing tag, and since it has no separate closing tag, you can't put anything inside of it. (That would need to look like <img>Content</img>, but of course that doesn't work.)

I know this is an old topic, but it pops up first on Google, so hopefully this will help others learn.

How to get Current Directory?

IMHO here are some improvements to anon's answer.

#include <windows.h>
#include <string>
#include <iostream>

std::string GetExeFileName()
{
  char buffer[MAX_PATH];
  GetModuleFileName( NULL, buffer, MAX_PATH );
  return std::string(buffer);
}

std::string GetExePath() 
{
  std::string f = GetExeFileName();
  return f.substr(0, f.find_last_of( "\\/" ));
}

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

df.iloc[-3:]

see the docs.

As Wes points out, in this specific case you should just use tail!

jQuery loop over JSON result from AJAX Success?

you can remove the outer loop and replace this with data.data:

$.each(data.data, function(k, v) {
    /// do stuff
});

You were close:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

count number of rows in a data frame in R based on group

Suppose we have a df_data data frame as below

> df_data
   ID MONTH-YEAR VALUE
1 110   JAN.2012  1000
2 111   JAN.2012  2000
3 121   FEB.2012  3000
4 131   FEB.2012  4000
5 141   MAR.2012  5000

To count number of rows in df_data grouped by MONTH-YEAR column, you can use:

> summary(df_data$`MONTH-YEAR`)

FEB.2012 JAN.2012 MAR.2012 
   2        2        1 

enter image description here summary function will create a table from the factor argument, then create a vector for the result (line 7 & 8)

How can I use jQuery in Greasemonkey?

If you want to use jQuery on a site where it is already included, this is the way to go (inspired by BrunoLM):

var $ = unsafeWindow.jQuery;

I know this wasn't the original intent of the question, but it is increasingly becoming a common case and you didn't explicitly exclude this case. ;)

Force IE10 to run in IE10 Compatibility View?

I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

My thanks to Scott Hanselman for this fix.

Here is the link -

http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.

Rick

could not access the package manager. is the system running while installing android application

Check your project build is in Debug mode not Release, I had some problem for debugging always I forget to change Release mode to Debug (Xamarin Users)

What is the point of the diamond operator (<>) in Java 7?

This line causes the [unchecked] warning:

List<String> list = new LinkedList();

So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?

I think, it would be much more difficult task then adding <> feature.

UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

How to update std::map after using the find method?

I would use the operator[].

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

So using this technique it becomes really easy to read all the character from a stream and count them:

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

Cannot convert lambda expression to type 'string' because it is not a delegate type

If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.

Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.

In your case it could be :

objContentLine = (from q in db.qryContents
                  where q.LineID == Value
                  orderby q.RowID descending
                  select q).FirstOrDefault();

Errors:

Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type

Error 242 Delegate 'System.Func<..>' does not take 1 arguments

Error 243 The name 'Value' does not exist in the current context

Fix the "Value" variable error and the other errors will also disappear.

Elegant way to check for missing packages and install them?

library <- function(x){
  x = toString(substitute(x))
if(!require(x,character.only=TRUE)){
  install.packages(x)
  base::library(x,character.only=TRUE)
}}

This works with unquoted package names and is fairly elegant (cf. GeoObserver's answer)

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

You can also use a shorter way:

<?php header('Content-Type: charset=utf-8'); ?>

See RFC 2616. It's valid to specify only character set.

jQuery: set selected value of dropdown list?

You can select dropdown option value by name

jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }
});

Caching a jquery ajax response in javascript/browser

I was looking for caching for my phonegap app storage and I found the answer of @TecHunter which is great but done using localCache.

I found and come to know that localStorage is another alternative to cache the data returned by ajax call. So, I created one demo using localStorage which will help others who may want to use localStorage instead of localCache for caching.

Ajax Call:

$.ajax({
    type: "POST",
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    url: url,
    data: '{"Id":"' + Id + '"}',
    cache: true, //It must "true" if you want to cache else "false"
    //async: false,
    success: function (data) {
        var resData = JSON.parse(data);
        var Info = resData.Info;
        if (Info) {
            customerName = Info.FirstName;
        }
    },
    error: function (xhr, textStatus, error) {
        alert("Error Happened!");
    }
});

To store data into localStorage:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.cache) {
    var success = originalOptions.success || $.noop,
        url = originalOptions.url;

    options.cache = false; //remove jQuery cache as we have our own localStorage
    options.beforeSend = function () {
        if (localStorage.getItem(url)) {
            success(localStorage.getItem(url));
            return false;
        }
        return true;
    };
    options.success = function (data, textStatus) {
        var responseData = JSON.stringify(data.responseJSON);
        localStorage.setItem(url, responseData);
        if ($.isFunction(success)) success(responseJSON); //call back to original ajax call
    };
}
});

If you want to remove localStorage, use following statement wherever you want:

localStorage.removeItem("Info");

Hope it helps others!

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

How to use npm with ASP.NET Core

Shawn Wildermuth has a nice guide here: https://wildermuth.com/2017/11/19/ASP-NET-Core-2-0-and-the-End-of-Bower

The article links to the gulpfile on GitHub where he's implemented the strategy in the article. You could just copy and paste most of the gulpfile contents into yours, but be sure to add the appropriate packages in package.json under devDependencies: gulp gulp-uglify gulp-concat rimraf merge-stream

"Post Image data using POSTMAN"

That's not how you send file on postman. What you did is sending a string which is the path of your image, nothing more.

What you should do is;

  1. After setting request method to POST, click to the 'body' tab.
  2. Select form-data. At first line, you'll see text boxes named key and value. Write 'image' to the key. You'll see value type which is set to 'text' as default. Make it File and upload your file.
  3. Then select 'raw' and paste your json file. Also just next to the binary choice, You'll see 'Text' is clicked. Make it JSON.

form-data section

raw section

You're ready to go.

In your Django view,

from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import parser_classes

@parser_classes((MultiPartParser, ))
class UploadFileAndJson(APIView):

    def post(self, request, format=None):
        thumbnail = request.FILES["file"]
        info = json.loads(request.data['info'])
        ...
        return HttpResponse()

Count textarea characters

They say IE has issues with the input event but other than that, the solution is rather straightforward.

_x000D_
_x000D_
ta = document.querySelector("textarea");_x000D_
count = document.querySelector("label");_x000D_
_x000D_
ta.addEventListener("input", function (e) {_x000D_
  count.innerHTML = this.value.length;_x000D_
});
_x000D_
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">_x000D_
</textarea>_x000D_
<label for="my-textarea"></label>
_x000D_
_x000D_
_x000D_

Multiple variables in a 'with' statement?

You can also separate creating a context manager (the __init__ method) and entering the context (the __enter__ method) to increase readability. So instead of writing this code:

with Company(name, id) as company, Person(name, age, gender) as person, Vehicle(brand) as vehicle:
    pass

you can write this code:

company = Company(name, id)
person = Person(name, age, gender)
vehicle = Vehicle(brand)

with company, person, vehicle:
    pass

Note that creating the context manager outside of the with statement makes an impression that the created object can also be further used outside of the statement. If this is not true for your context manager, the false impression may counterpart the readability attempt.

The documentation says:

Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.

This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used.

Sys is undefined

I fixed my problem by moving the <script type="text/javascript"></script> block containing the Sys.* calls lower down (to the last item before the close of the body's <asp:Content/> section) in the HTML on the page. I originally had my the script block in the HEAD <asp:Content/> section of my page. I was working inside a page that had a MasterPageFile. Hope this helps someone out.

How to establish ssh key pair when "Host key verification failed"

First you should remove existing key. SSH keys in most of Linux-based OS will be saved this file "/root/.ssh/known_hosts", so in order to remove the key related to host the following command will be used:

ssh-keygen -f "/root/.ssh/known_hosts" -R [Hostname]

Regards K1

Open PDF in new browser full window

var pdf = MyPdf.pdf;
window.open(pdf);

This will open the pdf document in a full window from JavaScript

A function to open windows would look like this:

function openPDF(pdf){
  window.open(pdf);
  return false;
}

How to adjust layout when soft keyboard appears

Android Developer has the right answer, but the provided source code is pretty verbose and doesn't actually implement the pattern described in the diagram.

Here is a better template:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

    <RelativeLayout android:layout_width="match_parent"
                    android:layout_height="match_parent">

        <LinearLayout android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:orientation="vertical">

                <!-- stuff to scroll -->

        </LinearLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true">

            <!-- footer -->

        </FrameLayout>

    </RelativeLayout>

</ScrollView>

Its up to you to decide what views you use for the "scrolling" and "footer" parts. Also know that you probably have to set the ScrollViews fillViewPort .

jQuery.post( ) .done( ) and success:

jQuery used to ONLY have the callback functions for success and error and complete.

Then, they decided to support promises with the jqXHR object and that's when they added .done(), .fail(), .always(), etc... in the spirit of the promise API. These new methods serve much the same purpose as the callbacks but in a different form. You can use whichever API style works better for your coding style.

As people get more and more familiar with promises and as more and more async operations use that concept, I suspect that more and more people will move to the promise API over time, but in the meantime jQuery supports both.

The .success() method has been deprecated in favor of the common promise object method names.

From the jQuery doc, you can see how various promise methods relate to the callback types:

jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {}); Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

If you want to code in a way that is more compliant with the ES6 Promises standard, then of these four options you would only use .then().

preventDefault() on an <a> tag

Why not just do it in css?

Take out the 'href' attribute in your anchor tag

<ul class="product-info">
  <li>
    <a>YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>

In your css,

  a{
    cursor: pointer;
    }

clientHeight/clientWidth returning different values on different browsers

This has to do with the browser's box model. Use something like jQuery or another JavaScript abstraction library to normalize the DOM model.

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

Try run this command it will create a *_limits.conf file under /etc/security/limits.d

echo "* soft nofile 102400" > /etc/security/limits.d/*_limits.conf && echo "* hard nofile 102400" >> /etc/security/limits.d/*_limits.conf

Just exit from terminal and login again and verify by ulimit -n it will set for * users

how to use List<WebElement> webdriver

Try the following code:

//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
  System.out.println(e.getText());
}

It will returns with the whole content of the <li> tags, like:

<a class="extra">Vše</a> (950)</li>

But you can easily get the number now from it, for example by using split() and/or substring().

How to write an inline IF statement in JavaScript?

<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>

parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );

Regarding 'main(int argc, char *argv[])'

argc is the number of command line arguments and argv is array of strings representing command line arguments.

This gives you the option to react to the arguments passed to the program. If you are expecting none, you might as well use int main.

Calling Oracle stored procedure from C#?

In .Net through version 4 this can be done the same way as for SQL Server Stored Procs but note that you need:

using System.Data.OracleClient;

There are some system requirements here that you should verify are OK in your scenario.

Microsoft is deprecating this namespace as of .Net 4 so third-party providers will be needed in the future. With this in mind, you may be better off using Oracle Data Provider for .Net (ODP.NET) from the word go - this has optimizations that are not in the Microsoft classes. There are other third-party options, but Oracle has a strong vested interest in keeping .Net developers on board so theirs should be good.

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Pyspark: Filter dataframe based on multiple conditions

You can also write like below (without pyspark.sql.functions):

df.filter('d<5 and (col1 <> col3 or (col1 = col3 and col2 <> col4))').show()

Result:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

Are there pointers in php?

You can simulate pointers to instantiated objects to some degree:

class pointer {
   var $child;

   function pointer(&$child) {
       $this->child = $child;
   }

   public function __call($name, $arguments) {
       return call_user_func_array(
           array($this->child, $name), $arguments);
   }
}

Use like this:

$a = new ClassA();

$p = new pointer($a);

If you pass $p around, it will behave like a C++ pointer regarding method calls (you can't touch object variables directly, but that's evil anyways :) ).

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Display more Text in fullcalendar

For some reason, I have to use

element.find('.fc-event-inner').empty();

to make it work, i guess i'm in day view.

VBA collection: list of keys

I don't thinks that possible with a vanilla collection without storing the key values in an independent array.

The easiest alternative to do this is to add a reference to the Microsoft Scripting Runtime & use a more capable Dictionary instead:

Dim dict As Dictionary
Set dict = New Dictionary

dict.Add "key1", "value1"
dict.Add "key2", "value2"

Dim key As Variant
For Each key In dict.Keys
    Debug.Print "Key: " & key, "Value: " & dict.Item(key)
Next

How to add a default "Select" option to this ASP.NET DropDownList control?

Although it is quite an old question, another approach is to change AppendDataBoundItems property. So the code will be:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                  OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                  AppendDataBoundItems="True">
     <asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
</asp:DropDownList>

how to use LIKE with column name

...
WHERE table1.x LIKE table2.y + '%'

Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

div.parent{
    position: relative;
    left: 0px;  /* stick it wherever it was positioned by default */
    top: 0px;
}

div.child{
    position: absolute;
    left: 10px;
    top: 10px;
}

Is it possible to decrypt MD5 hashes?

There is no way of "reverting" a hash function in terms of finding the inverse function for it. As mentioned before, this is the whole point of having a hash function. It should not be reversible and it should allow for fast hash value calculation. So the only way to find an input string which yields a given hash value is to try out all possible combinations. This is called brute force attack for that reason.

Trying all possible combinations takes a lot of time and this is also the reason why hash values are used to store passwords in a relatively safe way. If an attacker is able to access your database with all the user passwords inside, you loose in any case. If you have hash values and (idealistically speaking) strong passwords, it will be a lot harder to get the passwords out of the hash values for the attacker.

Storing the hash values is also no performance problem because computing the hash value is relatively fast. So what most systems do is computing the hash value of the password the user keyed in (which is fast) and then compare it to the stored hash value in their user database.

Viewing full output of PS command

It is likely that you're using a pager such as less or most since the output of ps aux is longer than a screenful. If so, the following options will cause (or force) long lines to wrap instead of being truncated.

ps aux | less -+S

ps aux | most -w

If you use either of the following commands, lines won't be wrapped but you can use your arrow keys or other movement keys to scroll left and right.

ps aux | less -S    # use arrow keys, or Esc-( and Esc-), or Alt-( and Alt-) 

ps aux | most       # use arrow keys, or < and > (Tab can also be used to scroll right)

Lines are always wrapped for more and pg.

When ps aux is used in a pipe, the w option is unnecessary since ps only uses screen width when output is to the terminal.

How can I load storyboard programmatically from class?

In attribute inspector give the identifier for that view controller and the below code works for me

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailViewController *detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
[self.navigationController pushViewController:detailViewController animated:YES];

Make the first character Uppercase in CSS

Note that the ::first-letter selector does not work with inline elements, so it must be either block or inline-block, as follows:

.m_title {display:inline-block}
.m_title:first-letter {text-transform: uppercase}

Difference between SelectedItem, SelectedValue and SelectedValuePath

SelectedItem is an object. SelectedValue and SelectedValuePath are strings.

for example using the ListBox:

if you say give me listbox1.SelectedValue it will return the text of the currently selected item.

string value = listbox1.SelectedValue;

if you say give me listbox1.SelectedItem it will give you the entire object.

ListItem item = listbox1.SelectedItem;
string value = item.value;

Click event on select option element in chrome

I've had simmilar issue. change event was not good for me because i've needed to refresh some data when user clicks on option. After few trials i've got this solution:

$('select').on('click',function(ev){
    if(ev.offsetY < 0){
      //user click on option  
    }else{
      //dropdown is shown
    }
});

I agree that this is very ugly and you should stick with change event where you can, but this solved my problem.

How do I get the currently-logged username from a Windows service in .NET?

Modified code of Tapas's answer:

Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
    username = oReturn("UserName")
Next

How to include an HTML page into another HTML page without frame/iframe?

If you are using NGINX over linux and want a pure bash/html, you can add a mask on your template and pipe the requests to use the sed command to do a replace by using a regullar expression.

Anyway I would rather have a bash script that takes from a templates folder and generate the final HTML.

Add objects to an array of objects in Powershell

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

$Target += $TargetObject

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

Templated check for the existence of a class member function?

This is a C++11 solution for the general problem if "If I did X, would it compile?"

template<class> struct type_sink { typedef void type; }; // consumes a type, and makes it `void`
template<class T> using type_sink_t = typename type_sink<T>::type;
template<class T, class=void> struct has_to_string : std::false_type {}; \
template<class T> struct has_to_string<
  T,
  type_sink_t< decltype( std::declval<T>().toString() ) >
>: std::true_type {};

Trait has_to_string such that has_to_string<T>::value is true if and only if T has a method .toString that can be invoked with 0 arguments in this context.

Next, I'd use tag dispatching:

namespace details {
  template<class T>
  std::string optionalToString_helper(T* obj, std::true_type /*has_to_string*/) {
    return obj->toString();
  }
  template<class T>
  std::string optionalToString_helper(T* obj, std::false_type /*has_to_string*/) {
    return "toString not defined";
  }
}
template<class T>
std::string optionalToString(T* obj) {
  return details::optionalToString_helper( obj, has_to_string<T>{} );
}

which tends to be more maintainable than complex SFINAE expressions.

You can write these traits with a macro if you find yourself doing it alot, but they are relatively simple (a few lines each) so maybe not worth it:

#define MAKE_CODE_TRAIT( TRAIT_NAME, ... ) \
template<class T, class=void> struct TRAIT_NAME : std::false_type {}; \
template<class T> struct TRAIT_NAME< T, type_sink_t< decltype( __VA_ARGS__ ) > >: std::true_type {};

what the above does is create a macro MAKE_CODE_TRAIT. You pass it the name of the trait you want, and some code that can test the type T. Thus:

MAKE_CODE_TRAIT( has_to_string, std::declval<T>().toString() )

creates the above traits class.

As an aside, the above technique is part of what MS calls "expression SFINAE", and their 2013 compiler fails pretty hard.

Note that in C++1y the following syntax is possible:

template<class T>
std::string optionalToString(T* obj) {
  return compiled_if< has_to_string >(*obj, [&](auto&& obj) {
    return obj.toString();
  }) *compiled_else ([&]{ 
    return "toString not defined";
  });
}

which is an inline compilation conditional branch that abuses lots of C++ features. Doing so is probably not worth it, as the benefit (of code being inline) is not worth the cost (of next to nobody understanding how it works), but the existence of that above solution may be of interest.

SQL Delete Records within a specific Range

DELETE FROM table_name 
WHERE id BETWEEN 79 AND 296;

How do I set GIT_SSL_NO_VERIFY for specific repos only?

If you have to disable SSL checks for one git server hosting several repositories, you can run :

git config --bool --add http.https://my.bad.server.sslverify false

This will add it to your user's configuration.

Command to check:

git config --bool --get-urlmatch http.sslverify https://my.bad.server 

(If you still use git < v1.8.5, run git config --global http.https://my.bad.server.sslVerify false)

Explanation from the documentation where the command is at the end, show the .gitconfig content looking like:

[http "https://my.bad.server"]
        sslVerify = false

It will ignore any certificate checks for this server, whatever the repository.

You also have some explanation in the code

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Using Spring 3 autowire in a standalone Java application

A nice solution would be to do following,

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware {

private static ApplicationContext context;

/**
 * Returns the Spring managed bean instance of the given class type if it exists.
 * Returns null otherwise.
 * @param beanClass
 * @return
 */
public static <T extends Object> T getBean(Class<T> beanClass) {
    return context.getBean(beanClass);
}

@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {

    // store ApplicationContext reference to access required beans later on
    SpringContext.context = context;
}
}

Then you can use it like:

YourClass yourClass = SpringContext.getBean(YourClass.class);

I found this very nice solution in the following website: https://confluence.jaytaala.com/pages/viewpage.action?pageId=18579463

TypeError: sequence item 0: expected string, int found

you can convert the integer dataframe into string first and then do the operation e.g.

df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))

How to extract string following a pattern with grep, regex or perl

If the structure of your xml (or text in general) is fixed, the easiest way is using cut. For your specific case:

echo '<table name="content_analyzer" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer2" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer_items" primary-key="id">
  <type="global" />
</table>' | grep name= | cut -f2 -d '"'

Iterate all files in a directory using a 'for' loop

To iterate over each file a for loop will work:

for %%f in (directory\path\*) do ( something_here )

In my case I also wanted the file content, name, etc.

This lead to a few issues and I thought my use case might help. Here is a loop that reads info from each '.txt' file in a directory and allows you do do something with it (setx for instance).

@ECHO OFF
setlocal enabledelayedexpansion
for %%f in (directory\path\*.txt) do (
  set /p val=<%%f
  echo "fullname: %%f"
  echo "name: %%~nf"
  echo "contents: !val!"
)

*Limitation: val<=%%f will only get the first line of the file.

How to check whether a str(variable) is empty or not?

How do i make an: if str(variable) == [contains text]: condition?

Perhaps the most direct way is:

if str(variable) != '':
  # ...

Note that the if not ... solutions test the opposite condition.

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

I faced this problem in a Framework7 & Cordova project. I tried all the solutions above. They did not solve my problem.

In my case, I was using 10+ css animations on the same page with infinite rotation (transform). I had to remove the animations. It is ok now with the lack of some visual features.

If the solutions above do not help you, you may start eliminating some animations.

How to update and order by using ms sql

As stated in comments below, you can use also the SET ROWCOUNT clause, but just for SQL Server 2014 and older.

SET ROWCOUNT 10

UPDATE messages
SET status = 10 
WHERE status = 0 

SET ROWCOUNT 0

More info: http://msdn.microsoft.com/en-us/library/ms188774.aspx

Or with a temp table

DECLARE @t TABLE (id INT)
INSERT @t (id)
SELECT TOP 10 id
FROM messages
WHERE status = 0
ORDER BY priority DESC

UPDATE messages
SET status = 10
WHERE id IN (SELECT id FROM @t)

NSRange from Swift Range?

My solution is a string extension that first gets the swift range then get's the distance from the start of the string to the start and end of the substring.

These values are then used to calculate the start and length of the substring. We can then apply these values to the NSMakeRange constructor.

This solution works with substrings that consist of multiple words, which a lot of the solutions here using enumerateSubstrings let me down on.

extension String {

    func NSRange(of substring: String) -> NSRange? {
        // Get the swift range 
        guard let range = range(of: substring) else { return nil }

        // Get the distance to the start of the substring
        let start = distance(from: startIndex, to: range.lowerBound) as Int
        //Get the distance to the end of the substring
        let end = distance(from: startIndex, to: range.upperBound) as Int

        //length = endOfSubstring - startOfSubstring
        //start = startOfSubstring
        return NSMakeRange(start, end - start)
    }

}

List of tables, db schema, dump etc using the Python sqlite3 API

Check out here for dump. It seems there is a dump function in the library sqlite3.

AngularJS directive does not update on scope variable changes

You should keep a watch on your scope.

Here is how you can do it:

<layout layoutId="myScope"></layout>

Your directive should look like

app.directive('layout', function($http, $compile){
    return {
        restrict: 'E',
        scope: {
            layoutId: "=layoutId"
        },
        link: function(scope, element, attributes) {
            var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
            $http.get(scope.constants.pathLayouts + layoutName + '.html')
                .success(function(layout){
                    var regexp = /^([\s\S]*?){{content}}([\s\S]*)$/g;
                    var result = regexp.exec(layout);

                    var templateWithLayout = result[1] + element.html() + result[2];
                    element.html($compile(templateWithLayout)(scope));
        });
    }
}

$scope.$watch('myScope',function(){
        //Do Whatever you want
    },true)

Similarly you can models in your directive, so if model updates automatically your watch method will update your directive.

html 5 audio tag width

You can use html and be a boss with simple things :

<embed src="music.mp3" width="3000" height="200" controls>

Replace comma with newline in sed on MacOS?

MacOS is different, there is two way to solve this problem with sed in mac

  • first ,use \'$'\n'' replace \n, it can work in MacOS:

    sed 's/,/\'$'\n''/g' file
    
  • the second, just use an empty line:

    sed 's/,/\
    /g' file
    
  • Ps. Pay attention the range separated by '

  • the third, use gnu-sed replace the mac-sed

React component initialize state from props

Update for React 16.3 alpha introduced static getDerivedStateFromProps(nextProps, prevState) (docs) as a replacement for componentWillReceiveProps.

getDerivedStateFromProps is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.

Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. You may want to compare new and previous values if you only want to handle changes.

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

It is static, therefore it does not have direct access to this (however it does have access to prevState, which could store things normally attached to this e.g. refs)

edited to reflect @nerfologist's correction in comments

I can't access http://localhost/phpmyadmin/

what you need to do is to add phpmyadmin to the apache configuration:

sudo nano /etc/apache2/apache2.conf

Add the phpmyadmin config to the file:

Include /etc/phpmyadmin/apache.conf

then restart apache:

sudo service apache2 restart

On windows, I think you can just navigate to the apache2 config file and include the phpmyadmin config file as shown above, then restart apache

How do I tell Python to convert integers into words

#This valid till 4 digit number
numbers={1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine',
10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen',
17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 
60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'thousand'}

def my_fun(num):
    list = []
    num_len = len(str(num)) - 1
    while num_len > 0 and num > 0:
       while num_len > 0 and num > 0:
        if num in numbers and num < 1000:
            list.append(numbers[num])
            num_len = 0
        elif num < 100:
            list.extend([numbers[num - num%10], numbers[num%10]])
            num_len = 0
        else:
            quotent = num//10**num_len # 4567//1000= 4
            num = num % 10**num_len #4567%1000 =567
            if quotent != 0 :
                list.append(numbers[quotent])
                list.append(numbers[10**num_len])
            else:
                list.append(numbers[num])
            num_len -= 1
    return ' '.join(list)

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

How to change screen resolution of Raspberry Pi

Just run the following simple command on Raspberry Pi 3 running Raspbian Jessie.

run terminal and type

sudo raspi-config

Go to: >Advanced Option > Resolution > just set your resolution compatible fit with your screen.

then

reboot

If you didn't found the menu on configuration, please update your raspberry pi software configuration tool (raspi-config).

That's all TQ.

Java SecurityException: signer information does not match

Based on @Mohit Phougat response, if you are running a Groovy with @Grab annotations, you could try to re-order such annotations.

How to convert NSData to byte array in iPhone?

Here's what I believe is the Swift equivalent:

if let data = NSData(contentsOfFile: filePath) {
   let length = data.length
   let byteData = malloc(length)
   memcmp(byteData, data.bytes, length)
}

How to change to an older version of Node.js

On windows 7 I used the general 'Uninstall Node.js' (just started typing in the search bottom left ,main menu field) followed by clicking the link to the older version which complies with the project, for instance: Windows 64-bit Installer: https://nodejs.org/dist/v4.4.6/node-v4.4.6-x64.msi

Date object to Calendar [Java]

Here is a full example on how to transform your date in different types:

Date date = Calendar.getInstance().getTime();

    // Display a date in day, month, year format
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with day name in a short format
    formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with a short day and month name
    formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Formatting date with full day and month name and show time up to
    // milliseconds with AM/PM
    formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    today = formatter.format(date);
    System.out.println("Today : " + today);

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

I got rid of this problem by deleting the Bin and Gen folder from project(which automatically come back when the project will build) and then cleaning the project from ->Menu -> Project -> clean.

Thanks.

Why doesn't java.io.File have a close method?

java.io.File doesn't represent an open file, it represents a path in the filesystem. Therefore having close method on it doesn't make sense.

Actually, this class was misnamed by the library authors, it should be called something like Path.

Python "expected an indented block"

#option = 1
#while option != 0:

print ("MENU")
print("please make a selection")
print("1. count")
print("0. quit")
option = int(input("MAKE Your Selection  "))
if option == 1:
    print("1. count up")
    print("2. count down")
    print("0. go back")
    option = int(input("MAKE Your Selection  "))
    if option == 1:
        x = int(input("please enter a number   "))
        for x in range(1, x, 1):
            print (x)

    elif option == 2:
        x = int(input("please enter a number   "))
        for x in range(x, 0, -1):
            print (x) 
    elif option == 0:
        print("hi")
    else:
        print("invalid command")
else:
    print ("H!111")
_________________________________________________________________________


You can try this code! It works.

Pandas DataFrame to List of Lists

We can use the DataFrame.iterrows() function to iterate over each of the rows of the given Dataframe and construct a list out of the data of each row:

# Empty list 
row_list =[] 

# Iterate over each row 
for index, rows in df.iterrows(): 
    # Create list for the current row 
    my_list =[rows.Date, rows.Event, rows.Cost] 

    # append the list to the final list 
    row_list.append(my_list) 

# Print 
print(row_list) 

We can successfully extract each row of the given data frame into a list

Maximum number of threads per process in Linux?

To set permanently,

vim /etc/sysctl.conf

and add

kernel.threads-max = "value"

Read the package name of an Android APK

Since its mentioned in Android documentation that AAPT has been deprecated, getting the package name using AAPT2 command in Linux is as follows:

./aapt2 dump packagename <path_to_apk>

Since I am using an older version of Gradle build, I had to download a newer version of AAPT2 as mentioned here :

Download AAPT2 from Google Maven

Using the build-tools in my sdk - 25.0.3, 26.0.1 and 27.0.3, executing the aapt2 command shows an error: Unable to open 'packagename': No such file or directory. That's why I went for the newer versions of AAPT2.

I used 3.3.0-5013011 for linux.

How do I fire an event when a iframe has finished loading in jQuery?

@Alex aw that's a bummer. What if in your iframe you had an html document that looked like:

<html>
  <head>
    <meta http-equiv="refresh" content="0;url=/pdfs/somepdf.pdf" />
  </head>
  <body>
  </body>
</html>

Definitely a hack, but it might work for Firefox. Although I wonder if the load event would fire too soon in that case.

Server.Mappath in C# classlibrary

Use this System.Web.Hosting.HostingEnvironment.MapPath().

HostingEnvironment.MapPath("~/file")

Wonder why nobody mentioned it here.

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

StringBuilder is a better option to concat a huge data string because the StringBuilder is a mutable string type and StringBuilder object is an immutable type, that means StringBuilder never create a new instance of object while concat the string.

If we are using string instead of StringBuilder to achieve for concatenation then it will create new instance in memory every time.

undefined reference to WinMain@16 (codeblocks)

You should create a new project in Code::Blocks, and make sure it's 'Console Application'.

Add your .cpp files into the project so they are all compiled and linked together.

malloc an array of struct pointers

There's a lot of typedef going on here. Personally I'm against "hiding the asterisk", i.e. typedef:ing pointer types into something that doesn't look like a pointer. In C, pointers are quite important and really affect the code, there's a lot of difference between foo and foo *.

Many of the answers are also confused about this, I think.

Your allocation of an array of Chess values, which are pointers to values of type chess (again, a very confusing nomenclature that I really can't recommend) should be like this:

Chess *array = malloc(n * sizeof *array);

Then, you need to initialize the actual instances, by looping:

for(i = 0; i < n; ++i)
  array[i] = NULL;

This assumes you don't want to allocate any memory for the instances, you just want an array of pointers with all pointers initially pointing at nothing.

If you wanted to allocate space, the simplest form would be:

for(i = 0; i < n; ++i)
  array[i] = malloc(sizeof *array[i]);

See how the sizeof usage is 100% consistent, and never starts to mention explicit types. Use the type information inherent in your variables, and let the compiler worry about which type is which. Don't repeat yourself.

Of course, the above does a needlessly large amount of calls to malloc(); depending on usage patterns it might be possible to do all of the above with just one call to malloc(), after computing the total size needed. Then you'd still need to go through and initialize the array[i] pointers to point into the large block, of course.

Difference between a script and a program?

A framework or other similar schema will run/interpret a script to do a task. A program is compiled and run by a machine to do a task

How to get time difference in minutes in PHP

This will help....

function get_time($date,$nosuffix=''){
    $datetime = new DateTime($date);
    $interval = date_create('now')->diff( $datetime );
    if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
    else $suffix='';
    //return $interval->y;
    if($interval->y >=1)        {$count = date(VDATE, strtotime($date)); $text = '';}
    elseif($interval->m >=1)    {$count = date('M d', strtotime($date)); $text = '';}
    elseif($interval->d >=1)    {$count = $interval->d; $text = 'day';} 
    elseif($interval->h >=1)    {$count = $interval->h; $text = 'hour';}
    elseif($interval->i >=1)    {$count = $interval->i; $text = 'minute';}
    elseif($interval->s ==0)    {$count = 'Just Now'; $text = '';}
    else                        {$count = $interval->s; $text = 'second';}
    if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
    return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;     
}

How to print time in format: 2009-08-10 18:17:54.811

None of the solutions on this page worked for me, I mixed them up and made them working with Windows and Visual Studio 2019, Here's How :

#include <Windows.h>
#include <time.h> 
#include <chrono>

static int gettimeofday(struct timeval* tp, struct timezone* tzp) {
    namespace sc = std::chrono;
    sc::system_clock::duration d = sc::system_clock::now().time_since_epoch();
    sc::seconds s = sc::duration_cast<sc::seconds>(d);
    tp->tv_sec = s.count();
    tp->tv_usec = sc::duration_cast<sc::microseconds>(d - s).count();
    return 0;
}

static char* getFormattedTime() {
    static char buffer[26];

    // For Miliseconds
    int millisec;
    struct tm* tm_info;
    struct timeval tv;

    // For Time
    time_t rawtime;
    struct tm* timeinfo;

    gettimeofday(&tv, NULL);

    millisec = lrint(tv.tv_usec / 1000.0);
    if (millisec >= 1000) 
    {
        millisec -= 1000;
        tv.tv_sec++;
    }

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", timeinfo);
    sprintf_s(buffer, 26, "%s.%03d", buffer, millisec);

    return buffer;
}

Result :

2020:08:02 06:41:59.107

2020:08:02 06:41:59.196

MySQL does not start when upgrading OSX to Yosemite or El Capitan

I’ve got a similar problem with MySQL on a Mac (Mac Os X Could not startup MySQL Server. Reason: 255 and also “ERROR! The server quit without updating PID file”). After a long trial and error process, finally in order to restore the file permissions, I’ve just do that:

* launch the Disk Utilities.app
* choose my drive on the left panel
* click on the “Repair disk permissions” button

This did the trick for me.

Hoping this can help someone else.

How to get an input text value in JavaScript

All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value; inside the function function kk().

What I suggest is, you may call that variable from another function fun_inside()

function fun_inside()
{    
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}

It can be useful when you built complex projects.

How do I make a transparent canvas in html5?

I believe you are trying to do exactly what I just tried to do: I want two stacked canvases... the bottom one has a static image and the top one contains animated sprites. Because of the animation, you need to clear the background of the top layer to transparent at the start of rendering every new frame. I finally found the answer: it's not using globalAlpha, and it's not using a rgba() color. The simple, effective answer is:

context.clearRect(0,0,width,height);

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

    public static void ExportToExcel(DataGridView dgView)
    {
        Microsoft.Office.Interop.Excel.Application excelApp = null;
        try
        {
            // instantiating the excel application class
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
            currentWorksheet.Columns.ColumnWidth = 18;


            if (dgView.Rows.Count > 0)
            {
                currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
                int i = 1;
                foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
                {
                    // Excel work sheet indexing starts with 1
                    currentWorksheet.Cells[2, i] = dgviewColumn.Name;
                    ++i;
                }
                Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
                headerColumnRange.Font.Bold = true;
                headerColumnRange.Font.Color = 0xFF0000;
                //headerColumnRange.EntireColumn.AutoFit();
                int rowIndex = 0;
                for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
                {
                    DataGridViewRow dgRow = dgView.Rows[rowIndex];
                    for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
                    {
                        currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
                    }
                }
                Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
                fullTextRange.WrapText = true;
                fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            }
            else
            {
                string timeStamp = DateTime.Now.ToString("s");
                timeStamp = timeStamp.Replace(':', '-');
                timeStamp = timeStamp.Replace("T", "__");
                currentWorksheet.Cells[1, 1] = timeStamp;
                currentWorksheet.Cells[1, 2] = "No error occured";
            }
            using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
            {
                exportSaveFileDialog.Title = "Select Excel File";
                exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";

                if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
                {
                    string fullFileName = exportSaveFileDialog.FileName;
                   // currentWorkbook.SaveCopyAs(fullFileName);
                    // indicating that we already saved the workbook, otherwise call to Quit() will pop up
                    // the save file dialogue box

                    currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                    currentWorkbook.Saved = true;
                    MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            if (excelApp != null)
            {
                excelApp.Quit();
            }
        }



    }

Running Node.js in apache?

You can always do something shell-scripty like:

#!/usr/bin/node

var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);

exit;

Commenting multiple lines in DOS batch file

@jeb

And after using this, the stderr seems to be inaccessible

No, try this:

@echo off 2>Nul 3>Nul 4>Nul

   ben ali  
   mubarak 2>&1
   gadeffi
   ..next ?

   echo hello Tunisia

  pause

But why it works?

sorry, i answer the question in frensh:

( la redirection par 3> est spécial car elle persiste, on va l'utiliser pour capturer le flux des erreurs 2> est on va le transformer en un flux persistant à l'ade de 3> ceci va nous permettre d'avoir une gestion des erreur pour tout notre environement de script..par la suite si on veux recuperer le flux 'stderr' il faut faire une autre redirection du handle 2> au handle 1> qui n'est autre que la console.. )

Passing properties by reference in C#

What you could try to do is create an object to hold the property value. That way you could pass the object and still have access to the property inside.

How do I use select with date condition?

select sysdate from dual
30-MAR-17

select count(1) from masterdata where to_date(inactive_from_date,'DD-MON-YY'
between '01-JAN-16' to '31-DEC-16'

12998 rows

How does "cat << EOF" work in bash?

POSIX 7

kennytm quoted man bash, but most of that is also POSIX 7: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_04 :

The redirection operators "<<" and "<<-" both allow redirection of lines contained in a shell input file, known as a "here-document", to the input of a command.

The here-document shall be treated as a single word that begins after the next and continues until there is a line containing only the delimiter and a , with no characters in between. Then the next here-document starts, if there is one. The format is as follows:

[n]<<word
    here-document
delimiter

where the optional n represents the file descriptor number. If the number is omitted, the here-document refers to standard input (file descriptor 0).

If any character in word is quoted, the delimiter shall be formed by performing quote removal on word, and the here-document lines shall not be expanded. Otherwise, the delimiter shall be the word itself.

If no characters in word are quoted, all lines of the here-document shall be expanded for parameter expansion, command substitution, and arithmetic expansion. In this case, the in the input behaves as the inside double-quotes (see Double-Quotes). However, the double-quote character ( '"' ) shall not be treated specially within a here-document, except when the double-quote appears within "$()", "``", or "${}".

If the redirection symbol is "<<-", all leading <tab> characters shall be stripped from input lines and the line containing the trailing delimiter. If more than one "<<" or "<<-" operator is specified on a line, the here-document associated with the first operator shall be supplied first by the application and shall be read first by the shell.

When a here-document is read from a terminal device and the shell is interactive, it shall write the contents of the variable PS2, processed as described in Shell Variables, to standard error before reading each line of input until the delimiter has been recognized.

Examples

Some examples not yet given.

Quotes prevent parameter expansion

Without quotes:

a=0
cat <<EOF
$a
EOF

Output:

0

With quotes:

a=0
cat <<'EOF'
$a
EOF

or (ugly but valid):

a=0
cat <<E"O"F
$a
EOF

Outputs:

$a

Hyphen removes leading tabs

Without hyphen:

cat <<EOF
<tab>a
EOF

where <tab> is a literal tab, and can be inserted with Ctrl + V <tab>

Output:

<tab>a

With hyphen:

cat <<-EOF
<tab>a
<tab>EOF

Output:

a

This exists of course so that you can indent your cat like the surrounding code, which is easier to read and maintain. E.g.:

if true; then
    cat <<-EOF
    a
    EOF
fi

Unfortunately, this does not work for space characters: POSIX favored tab indentation here. Yikes.

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

What helped for me was to use llvm-gcc instead:

ln -s $(which llvm-gcc) /usr/local/bin/gcc

Why is list initialization (using curly braces) better than the alternatives?

There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:

  • If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.
  • If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.
  • For default initialization I always use curly braces.
    For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.

In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).

It e.g. fits nicely with standard library-types like std::vector:

vector<int> a{10,20};   //Curly braces -> fills the vector with the arguments

vector<int> b(10,20);   //Parentheses -> uses arguments to parametrize some functionality,                          
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.

vector<int> d{};      //empty braces -> default constructs vector, which is equivalent
                      //to a vector that is filled with zero elements

Python: Removing list element while iterating over list

List comp:

results = [x for x in (do_action(element) for element in somelist) if check(element)]

Does Enter key trigger a click event?

<form (keydown)="someMethod($event)">
     <input type="text">
</form>
someMethod(event:any){
   if(event.keyCode == 13){
      alert('Entered Click Event!');
   }else{
   }
}

Create a basic matrix in C (input by user !)

need a

for(i=0;i<2;i++)
{
  for(j=0;j<2;j++)
  {
     printf("%d",mat[i][j]);
  }
  printf("\n");
}

How to add a search box with icon to the navbar in Bootstrap 3?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <meta name="description" content="">_x000D_
    <meta name="author" content="">_x000D_
_x000D_
    <title>3 Col Portfolio - Start Bootstrap Template</title>_x000D_
_x000D_
    <!-- Bootstrap Core CSS -->_x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>_x000D_
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>_x000D_
    <![endif]-->_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <!-- Navigation -->_x000D_
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
        <div class="container">_x000D_
            <!-- Brand and toggle get grouped for better mobile display -->_x000D_
            <div class="navbar-header">_x000D_
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
                <a class="navbar-brand" href="#">Start Bootstrap</a>_x000D_
            </div>_x000D_
            <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
                <ul class="nav navbar-nav">_x000D_
                    <li>_x000D_
                        <a href="#">About</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">Services</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">Contact</a>_x000D_
                    </li>_x000D_
                </ul>_x000D_
                <form class="navbar-form navbar-right">_x000D_
                    <div class="input-group">_x000D_
                        <input type="text" name="keyword" placeholder="search..." class="form-control">_x000D_
                        <span class="input-group-btn">_x000D_
                            <button class="btn btn-default">Go</button>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </form>_x000D_
            </div>_x000D_
            <!-- /.navbar-collapse -->_x000D_
        </div>_x000D_
        <!-- /.container -->_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content -->_x000D_
    <div class="container">_x000D_
_x000D_
        <!-- Page Header -->_x000D_
        <div class="row">_x000D_
            <div class="col-lg-12">_x000D_
                <h1 class="page-header">Page Heading_x000D_
                    <small>Secondary Text</small>_x000D_
                </h1>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <hr>_x000D_
_x000D_
        <!-- Pagination -->_x000D_
        <div class="row text-center">_x000D_
            <div class="col-lg-12">_x000D_
                <ul class="pagination">_x000D_
                    <li>_x000D_
                        <a href="#">&laquo;</a>_x000D_
                    </li>_x000D_
                    <li class="active">_x000D_
                        <a href="#">1</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">2</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">3</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">4</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">5</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">&raquo;</a>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
    </div>_x000D_
    <!-- Footer -->_x000D_
    <footer>_x000D_
        <div class="container">_x000D_
            <div class="row">_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>About</h3>_x000D_
                    <ul>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-home"></i> Your company address here_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-earphone"></i> 0982.808.065_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-envelope"></i> [email protected]_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-flag"></i> <a href="#">Fan page</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-time"></i> 08:00-18:00 Monday to Friday_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </div>_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>Support</h3>_x000D_
                    <ul>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Terms of Service</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Privacy policy</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Warranty commitment</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Site map</a>_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </div>_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>Other</h3>_x000D_
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod_x000D_
                    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo_x000D_
                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse_x000D_
                    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
                    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
    </footer>_x000D_
_x000D_
    <!-- /.container -->_x000D_
_x000D_
    <!-- jQuery -->_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
    <!-- Bootstrap Core JavaScript -->_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Undefined or null for AngularJS

@STEVER's answer is satisfactory. However, I thought it may be useful to post a slightly different approach. I use a method called isValue which returns true for all values except null, undefined, NaN, and Infinity. Lumping in NaN with null and undefined is the real benefit of the function for me. Lumping Infinity in with null and undefined is more debatable, but frankly not that interesting for my code because I practically never use Infinity.

The following code is inspired by Y.Lang.isValue. Here is the source for Y.Lang.isValue.

/**
 * A convenience method for detecting a legitimate non-null value.
 * Returns false for null/undefined/NaN/Infinity, true for other values,
 * including 0/false/''
 * @method isValue
 * @static
 * @param o The item to test.
 * @return {boolean} true if it is not null/undefined/NaN || false.
 */
angular.isValue = function(val) {
  return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
};

Or as part of a factory

.factory('lang', function () {
  return {
    /**
     * A convenience method for detecting a legitimate non-null value.
     * Returns false for null/undefined/NaN/Infinity, true for other values,
     * including 0/false/''
     * @method isValue
     * @static
     * @param o The item to test.
     * @return {boolean} true if it is not null/undefined/NaN || false.
     */
    isValue: function(val) {
      return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
  };
})

ImportError: No module named - Python

Your modification of sys.path assumes the current working directory is always in main/. This is not the case. Instead, just add the parent directory to sys.path:

import sys
import os.path

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import gen_py.lib

Don't forget to include a file __init__.py in gen_py and lib - otherwise, they won't be recognized as Python modules.

Daylight saving time and time zone best practices

I'm not sure what I can add to the answers above, but here are a few points from me:

Types of times

There are four different times you should consider:

  1. Event time: eg, the time when an international sporting event happens, or a coronation/death/etc. This is dependent on the timezone of the event and not of the viewer.
  2. Television time: eg, a particular TV show is broadcast at 9pm local time all around the world. Important when thinking about publishing the results (of say American Idol) on your website
  3. Relative time: eg: This question has an open bounty closing in 21 hours. This is easy to display
  4. Recurring time: eg: A TV show is on every Monday at 9pm, even when DST changes.

There is also Historic/alternate time. These are annoying because they may not map back to standard time. Eg: Julian dates, dates according to a Lunar calendar on Saturn, The Klingon calendar.

Storing start/end timestamps in UTC works well. For 1, you need an event timezone name + offset stored along with the event. For 2, you need a local time identifier stored with each region and a local timezone name + offset stored for every viewer (it's possible to derive this from the IP if you're in a crunch). For 3, store in UTC seconds and no need for timezones. 4 is a special case of 1 or 2 depending on whether it's a global or a local event, but you also need to store a created at timestamp so you can tell if a timezone definition changed before or after this event was created. This is necessary if you need to show historic data.

Storing times

  • Always store time in UTC
  • Convert to local time on display (local being defined by the user looking at the data)
  • When storing a timezone, you need the name, timestamp and the offset. This is required because governments sometimes change the meanings of their timezones (eg: the US govt changed DST dates), and your application needs to handle things gracefully... eg: The exact timestamp when episodes of LOST showed both before and after DST rules changed.

Offsets and names

An example of the above would be:

The soccer world cup finals game happened in South Africa (UTC+2--SAST) on July 11, 2010 at 19:00 UTC.

With this information, we can historically determine the exact time when the 2010 WCS finals took place even if the South African timezone definition changes, and be able to display that to viewers in their local timezone at the time when they query the database.

System Time

You also need to keep your OS, database and application tzdata files in sync, both with each other, and with the rest of the world, and test extensively when you upgrade. It's not unheard of that a third party app that you depend on did not handle a TZ change correctly.

Make sure hardware clocks are set to UTC, and if you're running servers around the world, make sure their OSes are configured to use UTC as well. This becomes apparent when you need to copy hourly rotated apache log files from servers in multiple timezones. Sorting them by filename only works if all files are named with the same timezone. It also means that you don't have to do date math in your head when you ssh from one box to another and need to compare timestamps.

Also, run ntpd on all boxes.

Clients

Never trust the timestamp you get from a client machine as valid. For example, the Date: HTTP headers, or a javascript Date.getTime() call. These are fine when used as opaque identifiers, or when doing date math during a single session on the same client, but don't try to cross-reference these values with something you have on the server. Your clients don't run NTP, and may not necessarily have a working battery for their BIOS clock.

Trivia

Finally, governments will sometimes do very weird things:

Standard time in the Netherlands was exactly 19 minutes and 32.13 seconds ahead of UTC by law from 1909-05-01 through 1937-06-30. This time zone cannot be represented exactly using the HH:MM format.

Ok, I think I'm done.

ORDER BY using Criteria API

For Hibernate 5.2 and above, use CriteriaBuilder as follows

CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Cat> query = builder.createQuery(Cat.class);
Root<Cat> rootCat = query.from(Cat.class);
Join<Cat,Mother> joinMother = rootCat.join("mother");  // <-attribute name
Join<Mother,Kind> joinMotherKind = joinMother.join("kind");
query.select(rootCat).orderBy(builder.asc(joinMotherKind.get("value")));
Query<Cat> q = sessionFactory.getCurrentSession().createQuery(query);
List<Cat> cats = q.getResultList();

Regex for allowing alphanumeric,-,_ and space

Try this regex

*Updated regex

/^[a-z0-9]+([-_\s]{1}[a-z0-9]+)*$/i

This will allow only single space or - or _ between the text

Ex: this-some abc123_regex

To learn : https://regexr.com

*Note: I have updated the regex based on Toto question

SQL alias for SELECT statement

Yes, but you can select only one column in your subselect

SELECT (SELECT id FROM bla) AS my_select FROM bla2

Why aren't python nested functions called closures?

Python has a weak support for closure. To see what I mean take the following example of a counter using closure with JavaScript:

function initCounter(){
    var x = 0;
    function counter  () {
        x += 1;
        console.log(x);
    };
    return counter;
}

count = initCounter();

count(); //Prints 1
count(); //Prints 2
count(); //Prints 3

Closure is quite elegant since it gives functions written like this the ability to have "internal memory". As of Python 2.7 this is not possible. If you try

def initCounter():
    x = 0;
    def counter ():
        x += 1 ##Error, x not defined
        print x
    return counter

count = initCounter();

count(); ##Error
count();
count();

You'll get an error saying that x is not defined. But how can that be if it has been shown by others that you can print it? This is because of how Python it manages the functions variable scope. While the inner function can read the outer function's variables, it cannot write them.

This is a shame really. But with just read-only closure you can at least implement the function decorator pattern for which Python offers syntactic sugar.

Update

As its been pointed out, there are ways to deal with python's scope limitations and I'll expose some.

1. Use the global keyword (in general not recommended).

2. In Python 3.x, use the nonlocal keyword (suggested by @unutbu and @leewz)

3. Define a simple modifiable class Object

class Object(object):
    pass

and create an Object scope within initCounter to store the variables

def initCounter ():
    scope = Object()
    scope.x = 0
    def counter():
        scope.x += 1
        print scope.x

    return counter

Since scope is really just a reference, actions taken with its fields do not really modify scope itself, so no error arises.

4. An alternative way, as @unutbu pointed out, would be to define each variable as an array (x = [0]) and modify it's first element (x[0] += 1). Again no error arises because x itself is not modified.

5. As suggested by @raxacoricofallapatorius, you could make x a property of counter

def initCounter ():

    def counter():
        counter.x += 1
        print counter.x

    counter.x = 0
    return counter

How to strip HTML tags from string in JavaScript?

Using the browser's parser is the probably the best bet in current browsers. The following will work, with the following caveats:

  • Your HTML is valid within a <div> element. HTML contained within <body> or <html> or <head> tags is not valid within a <div> and may therefore not be parsed correctly.
  • textContent (the DOM standard property) and innerText (non-standard) properties are not identical. For example, textContent will include text within a <script> element while innerText will not (in most browsers). This only affects IE <=8, which is the only major browser not to support textContent.
  • The HTML does not contain <script> elements.
  • The HTML is not null
  • The HTML comes from a trusted source. Using this with arbitrary HTML allows arbitrary untrusted JavaScript to be executed. This example is from a comment by Mike Samuel on the duplicate question: <img onerror='alert(\"could run arbitrary JS here\")' src=bogus>

Code:

var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";

Retrieving an element from array list in Android?

What I understand your question is that you want to fetch an element in an ArrayList at a specific location.

Suppose your list contains Integers 1,2,3,4,5 and you want to fetch the value 3. Then the following lines of code will work.

ArrayList<Integer> list = new ArrayList<Integer>();
        if(list.contains(3)){//check if the list contains the element
            list.get(list.indexOf(3));//get the element by passing the index of the element
        }

Either ways you could use list.get(list.lastIndexOf(3))

Read all contacts' phone numbers in android

I fixed my need belove

manifest permissions

        <uses-permission android:name="android.permission.READ_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
        <!-- Read Contacts from phone -->
        <uses-permission android:name="android.permission.read_contacts" />
        <uses-permission android:name="android.permission.read_phone_state" />
        <uses-permission android:name="android.permission.READ_CALL_LOG" />

Note: After giving permissions at manifest some mobile phones can deny if so you need to go Settings--> Applications--> find your application click on it and turn On the permissions needed

enter image description here

 btn_readallcontacks.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            List<User> userList = new ArrayList<User>();
            while (phones.moveToNext()) {
                User user = new User();
                user.setNamee(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
                user.setPhone(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                userList.add(user);
                Log.d(TAG, "Name : " + user.getNamee().toString());
                Log.d(TAG, "Phone : " + user.getPhone().toString());
            }
            phones.close();
        }
    });

Use of Finalize/Dispose method in C#

From what I know, it's highly recommended NOT to use the Finalizer / Destructor:

public ~MyClass() {
  //dont use this
}

Mostly, this is due to not knowing when or IF it will be called. The dispose method is much better, especially if you us using or dispose directly.

using is good. use it :)

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Pull "pulls" the div towards the left of the browser and and Push "pushes" the div away from left of browser.

Like: enter image description here

So basically in a 3 column layout of any web page the "Main Body" appears at the "Center" and in "Mobile" view the "Main Body" appears at the "Top" of the page. This is mostly desired by everyone with 3 column layout.

<div class="container">
    <div class="row">
        <div id="content" class="col-lg-4 col-lg-push-4 col-sm-12">
        <h2>This is Content</h2>
        <p>orem Ipsum ...</p>
        </div>

        <div id="sidebar-left" class="col-lg-4  col-sm-6 col-lg-pull-4">
        <h2>This is Left Sidebar</h2>
        <p>orem Ipsum...</p>
        </div>


        <div id="sidebar-right" class="col-lg-4 col-sm-6">
        <h2>This is Right Sidebar</h2>
        <p>orem Ipsum.... </p>
        </div>
    </div>
</div>

You can view it here: http://jsfiddle.net/DrGeneral/BxaNN/1/

Hope it helps

Making a Bootstrap table column fit to content

Tested on Bootstrap 4.5 and 5.0

None of the solution works for me. The td last column still takes the full width. So here's the solution works.

Add table-fit to your table

table.table-fit {
    width: auto !important;
    table-layout: auto !important;
}
table.table-fit thead th, table.table-fit tfoot th {
    width: auto !important;
}
table.table-fit tbody td, table.table-fit tfoot td {
    width: auto !important;
}

Here's the one for sass uses.

@mixin width {
    width: auto !important;
}

table {
    &.table-fit {
        @include width;
        table-layout: auto !important;
        thead th, tfoot th  {
            @include width;
        }
        tbody td, tfoot td {
            @include width;
        }
    }
}

Unused arguments in R

Change the definition of multiply to take additional unknown arguments:

multiply <- function(a, b, ...) {
  # Original code
}

Counting repeated characters in a string in Python

For counting a character in a string you have to use YOUR_VARIABLE.count('WHAT_YOU_WANT_TO_COUNT').

If summarization is needed you have to use count() function.

variable = 'turkiye'
print(variable.count('u'))

output: 1

Is it possible to read from a InputStream with a timeout?

Here is a way to get a NIO FileChannel from System.in and check for availability of data using a timeout, which is a special case of the problem described in the question. Run it at the console, don't type any input, and wait for the results. It was tested successfully under Java 6 on Windows and Linux.

import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;

public class Main {

    static final ByteBuffer buf = ByteBuffer.allocate(4096);

    public static void main(String[] args) {

        long timeout = 1000 * 5;

        try {
            InputStream in = extract(System.in);
            if (! (in instanceof FileInputStream))
                throw new RuntimeException(
                        "Could not extract a FileInputStream from STDIN.");

            try {
                int ret = maybeAvailable((FileInputStream)in, timeout);
                System.out.println(
                        Integer.toString(ret) + " bytes were read.");

            } finally {
                in.close();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /* unravels all layers of FilterInputStream wrappers to get to the
     * core InputStream
     */
    public static InputStream extract(InputStream in)
            throws NoSuchFieldException, IllegalAccessException {

        Field f = FilterInputStream.class.getDeclaredField("in");
        f.setAccessible(true);

        while( in instanceof FilterInputStream )
            in = (InputStream)f.get((FilterInputStream)in);

        return in;
    }

    /* Returns the number of bytes which could be read from the stream,
     * timing out after the specified number of milliseconds.
     * Returns 0 on timeout (because no bytes could be read)
     * and -1 for end of stream.
     */
    public static int maybeAvailable(final FileInputStream in, long timeout)
            throws IOException, InterruptedException {

        final int[] dataReady = {0};
        final IOException[] maybeException = {null};
        final Thread reader = new Thread() {
            public void run() {                
                try {
                    dataReady[0] = in.getChannel().read(buf);
                } catch (ClosedByInterruptException e) {
                    System.err.println("Reader interrupted.");
                } catch (IOException e) {
                    maybeException[0] = e;
                }
            }
        };

        Thread interruptor = new Thread() {
            public void run() {
                reader.interrupt();
            }
        };

        reader.start();
        for(;;) {

            reader.join(timeout);
            if (!reader.isAlive())
                break;

            interruptor.start();
            interruptor.join(1000);
            reader.join(1000);
            if (!reader.isAlive())
                break;

            System.err.println("We're hung");
            System.exit(1);
        }

        if ( maybeException[0] != null )
            throw maybeException[0];

        return dataReady[0];
    }
}

Interestingly, when running the program inside NetBeans 6.5 rather than at the console, the timeout doesn't work at all, and the call to System.exit() is actually necessary to kill the zombie threads. What happens is that the interruptor thread blocks (!) on the call to reader.interrupt(). Another test program (not shown here) additionally tries to close the channel, but that doesn't work either.

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

How do I move focus to next input with jQuery?

Use eq to get to specific element.

Documentation about index

_x000D_
_x000D_
$("input").keyup(function () {_x000D_
   var index = $(this).index("input");    _x000D_
   $("input:eq(" + (index +1) + ")").focus(); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />
_x000D_
_x000D_
_x000D_

How to disable the parent form when a child form is active?

While using the previously mentioned childForm.ShowDialog(this) will disable your main form, it still doesent look very disabled. However if you call Enabled = false before ShowDialog() and Enable = true after you call ShowDialog() the main form will even look like it is disabled.

var childForm = new Form();
Enabled = false;
childForm .ShowDialog(this);
Enabled = true;

Pretty printing XML with javascript

XMLSpectrum formats XML, supports attribute indentation and also does syntax-highlighting for XML and any embedded XPath expressions:

XMLSpectrum formatted XML

XMLSpectrum is an open source project, coded in XSLT 2.0 - so you can run this server-side with a processor such as Saxon-HE (recommended) or client-side using Saxon-CE.

XMLSpectrum is not yet optimised to run in the browser - hence the recommendation to run this server-side.

Redirect to new Page in AngularJS using $location

If you want to change ng-view you'll have to use the '#'

$window.location.href= "#operation";

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

day of the week to day number (Monday = 1, Tuesday = 2)

The date function can return this if you specify the format correctly:

$daynum = date("w", strtotime("wednesday"));

will return 0 for Sunday through to 6 for Saturday.

An alternative format is:

$daynum = date("N", strtotime("wednesday"));

which will return 1 for Monday through to 7 for Sunday (this is the ISO-8601 represensation).

How do I format date in jQuery datetimepicker?

This works for me. Since it "extends" datepicker we can still use dateFormat:'dd/mm/yy'.

$(function() {
    $('.jqueryui-marker-datepicker').datetimepicker({
        showSecond: true,
        dateFormat: 'dd/mm/yy',
      timeFormat: 'hh:mm:ss',
      stepHour: 2,
      stepMinute: 10,
      stepSecond: 10

     });
});

How do you make a HTTP request with C++?

CppRest SDK by MS is what I just found and after about 1/2 hour had my first simple web service call working. Compared that to others mentioned here where I was not able to get anything even installed after hours of looking, I'd say it is pretty impressive

https://github.com/microsoft/cpprestsdk

Scroll down and click on Documentation, then click on Getting Started Tutorial and you will have a simple app running in no time.

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

As per the DOM structure you can use below code:

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

How to bind a List to a ComboBox?

Try something like this:

yourControl.DataSource = countryInstance.Cities;

And if you are using WebForms you will need to add this line:

yourControl.DataBind();

Updating the list view when the adapter data changes

substitute:

mMyListView.invalidate();

for:

((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged(); 

If that doesnt work, refer to this thread: Android List view refresh

How to create a generic array?

Here is the implementation of LinkedList<T>#toArray(T[]):

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(
                            a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;

    if (a.length > size)
        a[size] = null;

    return a;
}

In short, you could only create generic arrays through Array.newInstance(Class, int) where int is the size of the array.

How do I add a library path in cmake?

might fail working with link_directories, then add each static library like following:

target_link_libraries(foo /path_to_static_library/libbar.a)

What is the difference between readonly="true" & readonly="readonly"?

I'm not sure how they're functionally different. My current batch of OS X browsers don't show any difference.

I would assume they are all functionally the same due to legacy HTML attribute handling. Back in the day, any flag (Boolean) attribute need only be present, sans value, eg

<input readonly>
<option selected>

When XHTML came along, this syntax wasn't valid and values were required. Whilst the W3 specified using the attribute name as the value, I'm guessing most browser vendors decided to simply check for attribute existence.

How to get the nth element of a python list or a default if not available

Using Python 3.4's contextlib.suppress(exceptions) to build a getitem() method similar to getattr().

import contextlib

def getitem(iterable, index, default=None):
    """Return iterable[index] or default if IndexError is raised."""
    with contextlib.suppress(IndexError):
        return iterable[index]
    return default

Display two fields side by side in a Bootstrap Form

How about using an input group to style it on the same line?

Here's the final HTML to use:

<div class="input-group">
    <input type="text" class="form-control" placeholder="Start"/>
    <span class="input-group-addon">-</span>
    <input type="text" class="form-control" placeholder="End"/>
</div>

Which will look like this:

screenshot

Here's a Stack Snippet Demo:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
    <input type="text" class="form-control" placeholder="Start"/>_x000D_
    <span class="input-group-addon">-</span>_x000D_
    <input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'll leave it as an exercise to the reader to translate it into an asp:textbox element

AngularJS: Service vs provider vs factory

For me, the revelation came when I realized that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through dependency injection.

Say we have:

app.factory('a', fn);
app.service('b', fn);
app.provider('c', fn);

The difference between the three is that:

  1. a's stored value comes from running fn.
  2. b’s stored value comes from newing fn.
  3. c’s stored value comes from first getting an instance by newing fn, and then running a $get method of the instance.

Which means there’s something like a cache object inside AngularJS, whose value of each injection is only assigned once, when they've been injected the first time, and where:

cache.a = fn()
cache.b = new fn()
cache.c = (new fn()).$get()

This is why we use this in services, and define a this.$get in providers.

How to run Java program in command prompt

All you need to do is:

  • Build the mainjava class using the class path if any (optional)

    javac *.java [ -cp "wb.jar;"]

  • Create Manifest.txt file with content is:

    Main-Class: mainjava

  • Package the jar file for mainjava class

    jar cfm mainjava.jar Manifest.txt *.class

Then you can run this .jar file from cmd with class path (optional) and put arguments for it.

java [-cp "wb.jar;"] mainjava arg0 arg1 

HTH.

How to do tag wrapping in VS code?

With VSCode 1.47+ you can simply use OPT-w for this.

Utilizing built-in functionality to trigger emmet, this is the easiest way:

  1. Select your text/html.
  2. Option+w
  3. In the emmet window opened in the command palette, type in the tag or wrapping code you need.
  4. Enter
  5. Voila

In Python, when to use a Dictionary, List or Set?

A list keeps order, dict and set don't: when you care about order, therefore, you must use list (if your choice of containers is limited to these three, of course;-).

dict associates with each key a value, while list and set just contain values: very different use cases, obviously.

set requires items to be hashable, list doesn't: if you have non-hashable items, therefore, you cannot use set and must instead use list.

set forbids duplicates, list does not: also a crucial distinction. (A "multiset", which maps duplicates into a different count for items present more than once, can be found in collections.Counter -- you could build one as a dict, if for some weird reason you couldn't import collections, or, in pre-2.7 Python as a collections.defaultdict(int), using the items as keys and the associated value as the count).

Checking for membership of a value in a set (or dict, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases. So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking, set is better than list.

Get MD5 hash of big files in Python

Break the file into 8192-byte chunks (or some other multiple of 128 bytes) and feed them to MD5 consecutively using update().

This takes advantage of the fact that MD5 has 128-byte digest blocks (8192 is 128×64). Since you're not reading the entire file into memory, this won't use much more than 8192 bytes of memory.

In Python 3.8+ you can do

import hashlib
with open("your_filename.txt", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

Javascript Src Path

As your clock.js is in the root, put your code as this to call your javascript in the index.html found in the folders you mentioned.

<SCRIPT LANGUAGE="JavaScript" SRC="../clock.js"></SCRIPT>

This will call the clock.js which you put in the root of your web site.

Python: Fetch first 10 results from a list

The itertools module has lots of great stuff in it. So if a standard slice (as used by Levon) does not do what you want, then try the islice function:

from itertools import islice
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
iterator = islice(l, 10)
for item in iterator:
    print item

Multi column forms with fieldsets

I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.

<div class="form-group">
    <div class="col-sm-12">
        <label for="user_login">Username</label>
        <input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
    </div>
</div>

Check out this demo.

Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.

<form action="#" method="post" class="form-horizontal">

Check out this demo.

When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.

How can I capitalize the first letter of each word in a string?

The suggested method str.title() does not work in all cases. For example:

string = "a b 3c"
string.title()
> "A B 3C"

instead of "A B 3c".

I think, it is better to do something like this:

def capitalize_words(string):
    words = string.split(" ") # just change the split(" ") method
    return ' '.join([word.capitalize() for word in words])

capitalize_words(string)
>'A B 3c'

Merge 2 arrays of objects

const extend = function*(ls,xs){
   yield* ls;
   yield* xs;
}

console.log( [...extend([1,2,3],[4,5,6])]  );

How to choose between Hudson and Jenkins?

From the Jenkins website, http://jenkins-ci.org, the following sums it up.

In a nutshell Jenkins CI is the leading open-source continuous integration server. Built with Java, it provides over 300 plugins to support building and testing virtually any project.

Oracle now owns the Hudson trademark, but has licensed it under the Eclipse EPL. Jenkins is on the MIT license. Both Hudson and Jenkins are open-source. Based on the combination of who you work for and personal preference for open-source, the decision is straightforward IMHO.

Hope this was helpful.

Clear the entire history stack and start a new activity on Android

I spent a few hours on this too ... and agree that FLAG_ACTIVITY_CLEAR_TOP sounds like what you'd want: clear the entire stack, except for the activity being launched, so the Back button exits the application. Yet as Mike Repass mentioned, FLAG_ACTIVITY_CLEAR_TOP only works when the activity you're launching is already in the stack; when the activity's not there, the flag doesn't do anything.

What to do? Put the activity being launching in the stack with FLAG_ACTIVITY_NEW_TASK, which makes that activity the start of a new task on the history stack. Then add the FLAG_ACTIVITY_CLEAR_TOP flag.

Now, when FLAG_ACTIVITY_CLEAR_TOP goes to find the new activity in the stack, it'll be there and be pulled up before everything else is cleared.

Here's my logout function; the View parameter is the button to which the function's attached.

public void onLogoutClick(final View view) {
    Intent i = new Intent(this, Splash.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
    finish();
}

Using a custom (ttf) font in CSS

This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this

enter image description here

How to find files modified in last x minutes (find -mmin does not work as expected)

This may work for you. I used it for cleaning folders during deployments for deleting old deployment files.

clean_anyfolder() {
    local temp2="$1/**"; //PATH
    temp3=( $(ls -d $temp2 -t | grep "`date | awk '{print $2" "$3}'`") )
    j=0;
    while [ $j -lt ${#temp3[@]} ]
    do
            echo "to be removed ${temp3[$j]}"
            delete_file_or_folder ${temp3[$j]} 0 //DELETE HERE
        fi
        j=`expr $j + 1`
    done
}

Reading a huge .csv file

I do a fair amount of vibration analysis and look at large data sets (tens and hundreds of millions of points). My testing showed the pandas.read_csv() function to be 20 times faster than numpy.genfromtxt(). And the genfromtxt() function is 3 times faster than the numpy.loadtxt(). It seems that you need pandas for large data sets.

I posted the code and data sets I used in this testing on a blog discussing MATLAB vs Python for vibration analysis.

CSS content property: is it possible to insert HTML instead of Text?

As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()) in combination with svg's <foreignObject> element.

You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup))

But note that it is mostly a hack and that there are a lot of limitations :

  • You can not load any external resources from this markup (no CSS, no images, no media etc.).
  • You can not execute script.
  • Since this won't be part of the DOM, the only way to alter it, is to pass the markup as a dataURI, and edit this dataURI in document.styleSheets. for this part, DOMParser and XMLSerializer may help.
  • While the same operation allows us to load url-encoded media in <img> tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).

Now, a small demo of some html markup in a pseudo element :

_x000D_
_x000D_
/* _x000D_
**  original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
*     xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
*  I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
  content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
_x000D_
_x000D_

Close Window from ViewModel

System.Environment.Exit(0); in view model would work.

How to set my phpmyadmin user session to not time out so quickly?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where <your_new_timeout> is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

Converting int to string in C

char string[something];
sprintf(string, "%d", 42);

Write to rails console

As other have said, you want to use either puts or p. Why? Is that magic?

Actually not. A rails console is, under the hood, an IRB, so all you can do in IRB you will be able to do in a rails console. Since for printing in an IRB we use puts, we use the same command for printing in a rails console.

You can actually take a look at the console code in the rails source code. See the require of irb? :)

How to add bootstrap to an angular-cli project

For Adding Bootstrap and Jquery both

npm install bootstrap@3 jquery --save

after running this command, please go ahead and check your node_modules folder you should be able to see bootstrap and jquery added into it.

adb not finding my device / phone (MacOS X)

Important Update : As @equiman points out, there are some USB cables that are for charging only and do not transmit data. Sometimes just swapping cables will help.

Update for some versions of adb, ~/.android/adb_usb.ini has to be removed.

Executive summary: Add the Vendor ID to ~/.android/adb_usb.ini and restart adb

Full Details: Most of the time nothing will need to be done to get the Mac to recognize the phone/device. Seriously, 99% of the time "it just works."

That being said, the quickest way to reset adb is to restart it with the following commands in sequence:

  adb kill-server
  adb devices

But every now and then the adb devices command just fails to find your device. Maybe if you're working with some experimental or prototype or out-of-the-ordinary device, maybe it's just unknown and won't show up.

You can help adb to find your device by telling it about your device's "Vendor ID," essentially providing it with a hint. This can be done by putting the hex Vendor ID in the file ~/.android/adb_usb.ini

But first you have to find the Vendor ID value. Fortunately on Mac this is pretty easy. Launch the System Information application. It is located in the /Applications/Utilities/ folder, or you can get to it via the Apple Menu in the top left corner of the screen, select "About this Mac", then click the "More Info..." button. Screen grab here:

System Information, Hardware USB tree

Expand the "Hardware" tree, select "USB", then look for your target device. In the above example, my device is named "SomeDevice" (I did that in photoshop to hide the real device manufacturer). Another example would be a Samsung tablet which shows up as "SAMSUNG_Android" (btw, I didn't have to do anything special to make the Samsung tablet work.) Anyway, click your device and the full details will display in the pane below. This is where it lists the Vendor ID. In my example from the screenshot the value is 0x9d17 -- use this value in the next command

echo 0x9d17 >> ~/.android/adb_usb.ini

It's okay if you didn't already have that adb_usb.ini file before this, most of the time it's just not needed for finding your device so it's not unusual for that file to not be present. The above command will create it or append to the bottom of it if it already exists. Now run the commands listed way above to restart adb and you should be good to go.

adb kill-server ; adb devices

* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached 
123ABC456DEF001 device

How to pretty print XML from the command line?

This simple(st) solution doesn't provide indentation, but it is nevertheless much easier on the human eye. Also it allows the xml to be handled more easily by simple tools like grep, head, awk, etc.

Use sed to replace '<' with itself preceeded with a newline.

And as mentioned by Gilles, it's probably not a good idea to use this in production.

# check you are getting more than one line out
sed 's/</\n</g' sample.xml | wc -l

# check the output looks generally ok
sed 's/</\n</g' sample.xml | head

# capture the pretty xml in a different file
sed 's/</\n</g' sample.xml > prettySample.xml

How can I check for NaN values?

I actually just ran into this, but for me it was checking for nan, -inf, or inf. I just used

if float('-inf') < float(num) < float('inf'):

This is true for numbers, false for nan and both inf, and will raise an exception for things like strings or other types (which is probably a good thing). Also this does not require importing any libraries like math or numpy (numpy is so damn big it doubles the size of any compiled application).

Can I pass an array as arguments to a method with variable arguments in Java?

It's ok to pass an array - in fact it amounts to the same thing

String.format("%s %s", "hello", "world!");

is the same as

String.format("%s %s", new Object[] { "hello", "world!"});

It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.

See

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.

How can I get table names from an MS Access Database?

Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.

See:

OpenSchema Method (ADO)

Supported Schema Rowsets

Using two values for one switch case statement

The fallthrough answers by others are good ones.

However another approach would be extract methods out of the contents of your case statements and then just call the appropriate method from each case.

In the example below, both case 'text1' and case 'text4' behave the same:

switch (name) {
        case text1: {
            method1();
            break;
        }
        case text2: {
            method2();
            break;
        }
        case text3: {
            method3();
            break;
        }
        case text4: {
            method1();
            break;
        }

I personally find this style of writing case statements more maintainable and slightly more readable, especially when the methods you call have good descriptive names.

bash: shortest way to get n-th column of output

Try the zsh. It supports suffix alias, so you can define X in your .zshrc to be

alias -g X="| cut -d' ' -f2"

then you can do:

cat file X

You can take it one step further and define it for the nth column:

alias -g X2="| cut -d' ' -f2"
alias -g X1="| cut -d' ' -f1"
alias -g X3="| cut -d' ' -f3"

which will output the nth column of file "file". You can do this for grep output or less output, too. This is very handy and a killer feature of the zsh.

You can go one step further and define D to be:

alias -g D="|xargs rm"

Now you can type:

cat file X1 D

to delete all files mentioned in the first column of file "file".

If you know the bash, the zsh is not much of a change except for some new features.

HTH Chris

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.

What I finally end up doing was replacing the single quote ' with it code &#39; using a regex after the stringify() method call the following way:

var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "&#39;");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.

Make Https call using HttpClient

I agree with felickz but also i want to add an example for clarifying the usage in c#. I use SSL in windows service as follows.

    var certificatePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");
    gateway = new GatewayService();
    gateway.PreAuthenticate = true;


    X509Certificate2 cert = new X509Certificate2(certificatePath + @"\Attached\my_certificate.pfx","certificate_password");
    gateway.ClientCertificates.Add(cert);

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    gateway.UserAgent = Guid.NewGuid().ToString();
    gateway.Timeout = int.MaxValue;

If I'm going to use it in a web application, I'm just changing the implementation on the proxy side like this:

public partial class GatewayService : System.Web.Services.Protocols.SoapHttpClientProtocol // to => Microsoft.Web.Services2.WebServicesClientProtocol

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

How do I update pip itself from inside my virtual environment?

Upgrading pip using 'pip install --upgrade pip' does not always work because of the dreaded cert issue: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version

I like to use the one line command for virtual envs:

curl https://bootstrap.pypa.io/get-pip.py | python -

Or if you want to install it box wide you will need

curl https://bootstrap.pypa.io/get-pip.py | sudo python -

you can give curl a -s flag if you want to silence the output when running in an automation script.

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

If you're instantiating an android.support.v4.app.Fragment class, the you have to call getActivity().getSupportFragmentManager() to get rid of the cannot-resolve problem. However the official Android docs on Fragment by Google tends to over look this simple problem and they still document it without the getActivity() prefix.

onChange and onSelect in DropDownList

hmm. why don't you use onClick()

<select id="mySelect" onChange="enable();">
   <option onClick="disable();">No</option>
   <option onClick="enable();">Yes</option>
</select>

What is process.env.PORT in Node.js?

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

stopPropagation vs. stopImmediatePropagation

event.stopPropagation will prevent handlers on parent elements from running.
Calling event.stopImmediatePropagation will also prevent other handlers on the same element from running.

Synchronous request in Node.js

As of 2018 and using ES6 modules and Promises, we can write a function like that :

import { get } from 'http';

export const fetch = (url) => new Promise((resolve, reject) => {
  get(url, (res) => {
    let data = '';
    res.on('end', () => resolve(data));
    res.on('data', (buf) => data += buf.toString());
  })
    .on('error', e => reject(e));
});

and then in another module

let data;
data = await fetch('http://www.example.com/api_1.php');
// do something with data...
data = await fetch('http://www.example.com/api_2.php');
// do something with data
data = await fetch('http://www.example.com/api_3.php');
// do something with data

The code needs to be executed in an asynchronous context (using async keyword)

ADB not recognising Nexus 4 under Windows 7

Changing USB mode from MTP to PTP worked for me.

Running java with JAVA_OPTS env variable has no effect

I don't know of any JVM that actually checks the JAVA_OPTS environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java command-line.

The key thing to understand here is that arguments to java that come before the -jar analyse.jar bit will only affect the JVM and won't be passed along to your program. So, modifying the java line in your script to:

java $JAVA_OPTS -jar analyse.jar $*

Should "just work".

Unit testing with Spring Security

I would take a look at Spring's abstract test classes and mock objects which are talked about here. They provide a powerful way of auto-wiring your Spring managed objects making unit and integration testing easier.

Why aren't variable-length arrays part of the C++ standard?

This was considered for inclusion in C++/1x, but was dropped (this is a correction to what I said earlier).

It would be less useful in C++ anyway since we already have std::vector to fill this role.

How to pass props to {this.props.children}

Render props is most accurate approach to this problem. Instead of passing the child component to parent component as children props, let parent render child component manually. Render is built-in props in react, which takes function parameter. In this function you can let parent component render whatever you want with custom parameters. Basically it does the same thing as child props but it is more customizable.

class Child extends React.Component {
  render() {
    return <div className="Child">
      Child
      <p onClick={this.props.doSomething}>Click me</p>
           {this.props.a}
    </div>;
  }
}

class Parent extends React.Component {
  doSomething(){
   alert("Parent talks"); 
  }

  render() {
    return <div className="Parent">
      Parent
      {this.props.render({
        anythingToPassChildren:1, 
        doSomething: this.doSomething})}
    </div>;
  }
}

class Application extends React.Component {
  render() {
    return <div>
      <Parent render={
          props => <Child {...props} />
        }/>
    </div>;
  }
}

Example at codepen

Angular 2.0 and Modal Dialog

  • Angular 2 and up
  • Bootstrap css (animation is preserved)
  • NO JQuery
  • NO bootstrap.js
  • Supports custom modal content (just like accepted answer)
  • Recently added support for multiple modals on top of each other.

`

@Component({
  selector: 'app-component',
  template: `
  <button type="button" (click)="modal.show()">test</button>
  <app-modal #modal>
    <div class="app-modal-header">
      header
    </div>
    <div class="app-modal-body">
      Whatever content you like, form fields, anything
    </div>
    <div class="app-modal-footer">
      <button type="button" class="btn btn-default" (click)="modal.hide()">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </app-modal>
  `
})
export class AppComponent {
}

@Component({
  selector: 'app-modal',
  template: `
  <div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
       [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <ng-content select=".app-modal-header"></ng-content>
        </div>
        <div class="modal-body">
          <ng-content select=".app-modal-body"></ng-content>
        </div>
        <div class="modal-footer">
          <ng-content select=".app-modal-footer"></ng-content>
        </div>
      </div>
    </div>
  </div>
  `
})
export class ModalComponent {

  public visible = false;
  public visibleAnimate = false;

  public show(): void {
    this.visible = true;
    setTimeout(() => this.visibleAnimate = true, 100);
  }

  public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 300);
  }

  public onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.hide();
    }
  }
}

To show the backdrop, you'll need something like this CSS:

.modal {
  background: rgba(0,0,0,0.6);
}

The example now allows for multiple modals at the same time. (see the onContainerClicked() method).

For Bootstrap 4 css users, you need to make 1 minor change (because a css class name was updated from Bootstrap 3). This line: [ngClass]="{'in': visibleAnimate}" should be changed to: [ngClass]="{'show': visibleAnimate}"

To demonstrate, here is a plunkr

PHP how to get value from array if key is in a variable

Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:

$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);

Output:

Array
(
    [0] => 4
)

Now:

$key = 4;
$value = $array[$key];
print $value;

Output:

Hello There

Getting unique values in Excel by using formulas only

Resorting to a PivotTable might not count as using formulas only but seems more practical that most other suggestions so far:

SO1429899 example

Not an enclosing class error Android Studio

It should be

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.

not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.

Katra_home.this is invalid construct

How to convert an OrderedDict into a regular dict in python3

Even though this is a year old question, I would like to say that using dict will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be

import json
from collections import OrderedDict
input_dict = OrderedDict([('method', 'constant'), ('recursive', OrderedDict([('m', 'c')]))])
output_dict = json.loads(json.dumps(input_dict))
print output_dict

Update R using RStudio

I would recommend using the Windows package installr to accomplish this. Not only will the package update your R version, but it will also copy and update all of your packages. There is a blog on the subject here. Simply run the following commands in R Studio and follow the prompts:

# installing/loading the package:
if(!require(installr)) {
install.packages("installr"); require(installr)} #load / install+load installr

# using the package:
updateR() # this will start the updating process of your R installation.  It will check for newer versions, and if one is available, will guide you through the decisions you'd need to make.

Hide keyboard in react-native

import {Keyboard} from 'react-native';

use Keyboard.dismiss() to hide your keyboard in any onClick or onPress event.

Check if a value is in an array or not with Excel VBA

Use Match() function in excel VBA to check whether the value exists in an array.

Sub test()
    Dim x As Long

    vars1 = Array("Abc", "Xyz", "Examples")
    vars2 = Array("Def", "IJK", "MNO")

    If IsNumeric(Application.Match(Range("A1").Value, vars1, 0)) Then
        x = 1
    ElseIf IsNumeric(Application.Match(Range("A1").Value, vars2, 0)) Then
        x = 1
    End If

    MsgBox x
End Sub

Origin is not allowed by Access-Control-Allow-Origin

This is because of same-origin policy. See more at Mozilla Developer Network or Wikipedia.

Basically, in your example, you need load the http://nqatalog.negroesquisso.pt/login.php page only from nqatalog.negroesquisso.pt, not localhost.

grep exclude multiple strings

You can use regular grep like this:

tail -f admin.log | grep -v "Nopaging the limit is\|keyword to remove is"

Configuring ObjectMapper in Spring

SOLUTION 1

First working solution (tested) useful especially when using @EnableWebMvc:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this won't add a 2nd MappingJackson2HttpMessageConverter 
        // as the SOLUTION 2 is doing but also might seem complicated
        converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
            // check default included objectMapper._registeredModuleTypes,
            // e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
            // without Jackson2ObjectMapperBuilder
            ((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
        });
    }

SOLUTION 2

Of course the common approach below works too (also working with @EnableWebMvc):

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this will add a 2nd MappingJackson2HttpMessageConverter 
        // (additional to the default one) but will work and you 
        // won't lose the default converters as you'll do when overwriting
        // configureMessageConverters(List<HttpMessageConverter<?>> converters)
        // 
        // you still have to check default included
        // objectMapper._registeredModuleTypes, e.g.
        // Jdk8Module, JavaTimeModule when creating the ObjectMapper
        // without Jackson2ObjectMapperBuilder
        converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
    }

Why @EnableWebMvc usage is a problem?

@EnableWebMvc is using DelegatingWebMvcConfiguration which extends WebMvcConfigurationSupport which does this:

if (jackson2Present) {
    Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
    if (this.applicationContext != null) {
        builder.applicationContext(this.applicationContext);
    }
    messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}

which means that there's no way of injecting your own ObjectMapper with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter when using @EnableWebMvc.

iPhone Safari Web App opens links in new window

One workaround i used for an iOS web app was that I made all links (which were buttons by CSS) form submit buttons. So I opened a form which posted to the destination link, then input type="submit" Not the best way, but it's what I figured out before I found this page.