Programs & Examples On #Groupbox

It is a container that displays a frame around a group of controls with an optional header.

How to get StackPanel's children to fill maximum space downward?

An alternative method is to use a Grid with one column and n rows. Set all the rows heights to Auto, and the bottom-most row height to 1*.

I prefer this method because I've found Grids have better layout performance than DockPanels, StackPanels, and WrapPanels. But unless you're using them in an ItemTemplate (where the layout is being performed for a large number of items), you'll probably never notice.

How to configure robots.txt to allow everything?

If you want to allow every bot to crawl everything, this is the best way to specify it in your robots.txt:

User-agent: *
Disallow:

Note that the Disallow field has an empty value, which means according to the specification:

Any empty value, indicates that all URLs can be retrieved.


Your way (with Allow: / instead of Disallow:) works, too, but Allow is not part of the original robots.txt specification, so it’s not supported by all bots (many popular ones support it, though, like the Googlebot). That said, unrecognized fields have to be ignored, and for bots that don’t recognize Allow, the result would be the same in this case anyway: if nothing is forbidden to be crawled (with Disallow), everything is allowed to be crawled.
However, formally (per the original spec) it’s an invalid record, because at least one Disallow field is required:

At least one Disallow field needs to be present in a record.

Fitting a histogram with python

Here you have an example working on py2.6 and py3.2:

from scipy.stats import norm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# read data from a text file. One number per line
arch = "test/Log(2)_ACRatio.txt"
datos = []
for item in open(arch,'r'):
    item = item.strip()
    if item != '':
        try:
            datos.append(float(item))
        except ValueError:
            pass

# best fit of data
(mu, sigma) = norm.fit(datos)

# the histogram of the data
n, bins, patches = plt.hist(datos, 60, normed=1, facecolor='green', alpha=0.75)

# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=2)

#plot
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma))
plt.grid(True)

plt.show()

enter image description here

Open a new tab on button click in AngularJS

I solved this question this way.

<a class="btn btn-primary" target="_blank" ng-href="{{url}}" ng-mousedown="openTab()">newTab</a>

$scope.openTab = function() {
    $scope.url = 'www.google.com';
}

How can I initialize base class member variables in derived class constructor?

Leaving aside the fact that they are private, since a and b are members of A, they are meant to be initialized by A's constructors, not by some other class's constructors (derived or not).

Try:

class A
{
    int a, b;

protected: // or public:
    A(int a, int b): a(a), b(b) {}
};

class B : public A
{
    B() : A(0, 0) {}
};

Setting up an MS-Access DB for multi-user access

i think Access is a best choice for your case. But you have to split database, see: http://accessblog.net/2005/07/how-to-split-database-into-be-and-fe.html

•How can we make sure that the write-user can make changes to the table data while other users use the data? Do the read-users put locks on tables? Does the write-user have to put locks on the table? Does Access do this for us or do we have to explicitly code this?

there are no read locks unless you put them explicitly. Just use "No Locks"

•Are there any common problems with "MS Access transactions" that we should be aware of?

should not be problems with 1-2 write users

•Can we work on forms, queries etc. while they are being used? How can we "program" without being in the way of the users?

if you split database - then no problem to work on FE design.

•Which settings in MS Access have an influence on how things are handled?

What do you mean?

•Our background is mostly in Oracle, where is Access different in handling multiple users? Is there such thing as "isolation levels" in Access?

no isolation levels in access. BTW, you can then later move data to oracle and keep access frontend, if you have lot of users and big database.

How to get current available GPUs in tensorflow?

In TensorFlow Core v2.3.0, the following code should work.

import tensorflow as tf
visible_devices = tf.config.get_visible_devices()
for devices in visible_devices:
  print(devices)

Depending on your environment, this code will produce flowing results.

PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU') PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')

JavaScript: Get image dimensions

Similar question asked and answered using JQuery here:

Get width height of remote image from url

function getMeta(url){
  $("<img/>").attr("src", url).load(function(){
     s = {w:this.width, h:this.height};
     alert(s.w+' '+s.h);      
  }); 
}

getMeta("http://page.com/img.jpg");

How do I auto-submit an upload form when a file is selected?

The shortest solution is

<input type="file" name="file" onchange="javascript:document.getElementById('form').submit();" />

AngularJS : Initialize service with asynchronous data

I had the same problem: I love the resolve object, but that only works for the content of ng-view. What if you have controllers (for top-level nav, let's say) that exist outside of ng-view and which need to be initialized with data before the routing even begins to happen? How do we avoid mucking around on the server-side just to make that work?

Use manual bootstrap and an angular constant. A naiive XHR gets you your data, and you bootstrap angular in its callback, which deals with your async issues. In the example below, you don't even need to create a global variable. The returned data exists only in angular scope as an injectable, and isn't even present inside of controllers, services, etc. unless you inject it. (Much as you would inject the output of your resolve object into the controller for a routed view.) If you prefer to thereafter interact with that data as a service, you can create a service, inject the data, and nobody will ever be the wiser.

Example:

//First, we have to create the angular module, because all the other JS files are going to load while we're getting data and bootstrapping, and they need to be able to attach to it.
var MyApp = angular.module('MyApp', ['dependency1', 'dependency2']);

// Use angular's version of document.ready() just to make extra-sure DOM is fully 
// loaded before you bootstrap. This is probably optional, given that the async 
// data call will probably take significantly longer than DOM load. YMMV.
// Has the added virtue of keeping your XHR junk out of global scope. 
angular.element(document).ready(function() {

    //first, we create the callback that will fire after the data is down
    function xhrCallback() {
        var myData = this.responseText; // the XHR output

        // here's where we attach a constant containing the API data to our app 
        // module. Don't forget to parse JSON, which `$http` normally does for you.
        MyApp.constant('NavData', JSON.parse(myData));

        // now, perform any other final configuration of your angular module.
        MyApp.config(['$routeProvider', function ($routeProvider) {
            $routeProvider
              .when('/someroute', {configs})
              .otherwise({redirectTo: '/someroute'});
          }]);

        // And last, bootstrap the app. Be sure to remove `ng-app` from your index.html.
        angular.bootstrap(document, ['NYSP']);
    };

    //here, the basic mechanics of the XHR, which you can customize.
    var oReq = new XMLHttpRequest();
    oReq.onload = xhrCallback;
    oReq.open("get", "/api/overview", true); // your specific API URL
    oReq.send();
})

Now, your NavData constant exists. Go ahead and inject it into a controller or service:

angular.module('MyApp')
    .controller('NavCtrl', ['NavData', function (NavData) {
        $scope.localObject = NavData; //now it's addressable in your templates 
}]);

Of course, using a bare XHR object strips away a number of the niceties that $http or JQuery would take care of for you, but this example works with no special dependencies, at least for a simple get. If you want a little more power for your request, load up an external library to help you out. But I don't think it's possible to access angular's $http or other tools in this context.

(SO related post)

Remove or uninstall library previously added : cocoapods

  1. Remove the library from your Podfile

  2. Run pod install on the terminal

Creating an array from a text file in Bash

Use mapfile or read -a

Always check your code using shellcheck. It will often give you the correct answer. In this case SC2207 covers reading a file that either has space separated or newline separated values into an array.

Don't do this

array=( $(mycommand) )

Files with values separated by newlines

mapfile -t array < <(mycommand)

Files with values separated by spaces

IFS=" " read -r -a array <<< "$(mycommand)"

The shellcheck page will give you the rationale why this is considered best practice.

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

How to set time zone in codeigniter?

In the application/config folder, get the file config.php and check for the below:

$config['time_reference'] = '';

Change the value to your preferred time zone. For example to set time zone to Nairobi Kenya: $config['time_reference'] = 'Africa/Nairobi';

Connecting to SQL Server Express - What is my server name?

If sql server is installed on your machine, you should check

Programs -> Microsoft SQL Server 20XX -> Configuration Tools -> SQL Server Configuration Manager -> SQL Server Services You'll see "SQL Server (MSSQLSERVER)"

Programs -> Microsoft SQL Server 20XX -> Configuration Tools -> SQL Server Configuration Manager -> SQL Server Network Configuration -> Protocols for MSSQLSERVER -> TCP/IP Make sure it's using port number 1433

If you want to see if the port is open and listening try this from your command prompt... telnet 127.0.0.1 1433

And yes, SQL Express installs use localhost\SQLEXPRESS as the instance name by default.

How to send POST request in JSON using HTTPClient in Android?

There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.

/**
 * This method is used to process GET requests to the server.
 * 
 * @param url 
 * @return String
 * @throws IOException
 */
public static String connect(String url) throws IOException {

    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    try {

        response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            //instream.close();
        }
    } 
    catch (ClientProtocolException e) {
        Utilities.showDLog("connect","ClientProtocolException:-"+e);
    } catch (IOException e) {
        Utilities.showDLog("connect","IOException:-"+e); 
    }
    return result;
}


 /**
 * This method is used to send POST requests to the server.
 * 
 * @param URL
 * @param paramenter
 * @return result of server response
 */
static public String postHTPPRequest(String URL, String paramenter) {       

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(URL);
    httppost.setHeader("Content-Type", "application/json");
    try {
        if (paramenter != null) {
            StringEntity tmp = null;
            tmp = new StringEntity(paramenter, "UTF-8");
            httppost.setEntity(tmp);
        }
        HttpResponse httpResponse = null;
        httpResponse = httpclient.execute(httppost);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            InputStream input = null;
            input = entity.getContent();
            String res = convertStreamToString(input);
            return res;
        }
    } 
     catch (Exception e) {
        System.out.print(e.toString());
    }
    return null;
}

How to remove border from specific PrimeFaces p:panelGrid?

As mentioned by BalusC, the border is set by PrimeFaces on the generated tr and td elements, not on the table. However when trying with PrimeFaces version 5, it looks like there is a more specific match from the PrimeFaces CSS .ui-panelgrid .ui-panelgrid-cell > solid which still result in black borders being shown when appyling the style suggested.

Try using following style in order to overide the Primefaces one without using the !important declaration:

.companyHeaderGrid tr, .companyHeaderGrid td.ui-panelgrid-cell {
    border: none;
}

As mention make sure your CSS is loaded after the PrimeFaces one.

How to use putExtra() and getExtra() for string data

It is very easy to implement intent in Android.. It takes you to move from one activity to another activity,we have to two method putExtra(); and getExtra();Now I am showing you the example..

    Intent intent = new Intent(activity_registration.this, activity_Login.class);
                intent.putExtra("AnyKeyName", Email.getText().toString());  // pass your values and retrieve them in the other Activity using AnyKeyName
                        startActivity(intent);

Now we have to get the value from AnyKeyName parameter,the below mentioned code will help in doing this

       String data = getIntent().getExtras().getString("AnyKeyName");
        textview.setText(data);

We can easily set the receiving value from Intent,wherever we required.

JavaScript associative array to JSON

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

Meaning of $? (dollar question mark) in shell scripts

From http://www.gnu.org/s/bash/manual/bash.html#Special-Parameters

?
Expands to the exit status of the most recently executed foreground pipeline. 

What is the proper REST response code for a valid request but an empty data?

After looking in question, you should not use 404 why?

Based on RFC 7231 the correct status code is 204

In the anwsers above I noticed 1 small missunderstanding:

1.- the resource is: /users

2.- /users/8 is not the resource, this is: the resource /users with route parameter 8, consumer maybe cannot notice it and does not know the difference, but publisher does and must know this!... so he must return an accurate response for consumers. period.

so:

Based on the RFC: 404 is incorrect because the resources /users is found, but the logic executed using the parameter 8 did not found any content to return as a response, so the correct answer is: 204

The main point here is: 404 not even the resource was found to process the internal logic

204 is a: I found the resource, the logic was executed but I did not found any data using your criteria given in the route parameter so I cant return anything to you. Im sorry, verify your criteria and call me again.

200: ok i found the resource, the logic was executed (even when Im not forced to return anything) take this and use it at your will.

205: (the best option of a GET response) I found the resource, the logic was executed, I have some content for you, use it well, oh by the way if your are going to share this in a view please refresh the view to display it.

Hope it helps.

How to disable "prevent this page from creating additional dialogs"?

You should better use jquery-confirm rather than trying to remove that checkbox.

$.confirm({
    title: 'Confirm!',
    content: 'Are you sure you want to refund invoice ?',
    confirm: function(){
       //do something 
    },
    cancel: function(){
       //do something
    }
}); 

How to run Java program in command prompt

You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.

Differences between strong and weak in Objective-C

Strong: Basically Used With Properties we used to get or send data from/into another classes. Weak: Usually all outlets, connections are of Weak type from Interface.

Nonatomic: Such type of properties are used in conditions when we don't want to share our outlet or object into different simultaneous Threads. In other words, Nonatomic instance make our properties to deal with one thread at a time. Hopefully it helpful for you.

How is a tag different from a branch in Git? Which should I use, here?

Branches are made of wood and grow from the trunk of the tree. Tags are made of paper (derivative of wood) and hang like Christmas Ornaments from various places in the tree.

Your project is the tree, and your feature that will be added to the project will grow on a branch. The answer is branch.

How to set environment variables from within package.json?

suddenly i found that actionhero is using following code, that solved my problem by just passing --NODE_ENV=production in start script command option.

if(argv['NODE_ENV'] != null){
  api.env = argv['NODE_ENV'];
} else if(process.env.NODE_ENV != null){
  api.env = process.env.NODE_ENV;
}

i would really appreciate to accept answer of someone else who know more better way to set environment variables in package.json or init script or something like, where app bootstrapped by someone else.

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

How do I set the rounded corner radius of a color drawable using xml?

mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.

Changing an element's ID with jQuery

Eran's answer is good, but I would append to that. You need to watch any interactivity that is not inline to the object (that is, if an onclick event calls a function, it still will), but if there is some javascript or jQuery event handling attached to that ID, it will be basically abandoned:

$("#myId").on("click", function() {});

If the ID is now changed to #myID123, the function attached above will no longer function correctly from my experience.

Adding click event for a button created dynamically using jQuery

Use

$(document).on("click", "#btn_a", function(){
  alert ('button clicked');
});

to add the listener for the dynamically created button.

alert($("#btn_a").val());

will give you the value of the button

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

Capture iframe load complete event

Neither of the above answers worked for me, however this did

UPDATE:

As @doppleganger pointed out below, load is gone as of jQuery 3.0, so here's an updated version that uses on. Please note this will actually work on jQuery 1.7+, so you can implement it this way even if you're not on jQuery 3.0 yet.

$('iframe').on('load', function() {
    // do stuff 
});

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

Installing ADB on macOS

Note that if you use Android Studio and download through its SDK Manager, the SDK is downloaded to ~/Library/Android/sdk by default, not ~/.android-sdk-macosx.

I would rather add this as a comment to @brismuth's excellent answer, but it seems I don't have enough reputation points yet.

What is a good way to handle exceptions when trying to read a file in python?

I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that.

So the answer is either: "Tim's way" or "No, you're doing it correctly.".


Previous unhelpful answer to which all the comments refer:

import os

if os.path.exists(fName):
   with open(fName, 'rb') as f:
       try:
           # do stuff
       except : # whatever reader errors you care about
           # handle error

Creating a List of Lists in C#

you should not use Nested List in List.

List<List<T>> 

is not legal, even if T were a defined type.

https://msdn.microsoft.com/en-us/library/ms182144.aspx

How to set Linux environment variables with Ansible

There are multiple ways to do this and from your question it's nor clear what you need.

1. If you need environment variable to be defined PER TASK ONLY, you do this:

- hosts: dev
  tasks:
    - name: Echo my_env_var
      shell: "echo $MY_ENV_VARIABLE"
      environment:
        MY_ENV_VARIABLE: whatever_value

    - name: Echo my_env_var again
      shell: "echo $MY_ENV_VARIABLE"

Note that MY_ENV_VARIABLE is available ONLY for the first task, environment does not set it permanently on your system.

TASK: [Echo my_env_var] ******************************************************* 
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": "whatever_value"}

TASK: [Echo my_env_var again] ************************************************* 
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": ""}

Hopefully soon using environment will also be possible on play level, not only task level as above. There's currently a pull request open for this feature on Ansible's GitHub: https://github.com/ansible/ansible/pull/8651

UPDATE: It's now merged as of Jan 2, 2015.

2. If you want permanent environment variable + system wide / only for certain user

You should look into how you do it in your Linux distribution / shell, there are multiple places for that. For example in Ubuntu you define that in files like for example:

  • ~/.profile
  • /etc/environment
  • /etc/profile.d directory
  • ...

You will find Ubuntu docs about it here: https://help.ubuntu.com/community/EnvironmentVariables

After all for setting environment variable in ex. Ubuntu you can just use lineinfile module from Ansible and add desired line to certain file. Consult your OS docs to know where to add it to make it permanent.

What is "overhead"?

You're tired and cant do any more work. You eat food. The energy spent looking for food, getting it and actually eating it consumes energy and is overhead!

Overhead is something wasted in order to accomplish a task. The goal is to make overhead very very small.

In computer science lets say you want to print a number, thats your task. But storing the number, the setting up the display to print it and calling routines to print it, then accessing the number from variable are all overhead.

Convert string in base64 to image and save on filesystem in Python

You can use Pillow.

pip install Pillow



image = base64.b64decode(str(base64String))       
fileName = 'test.jpeg'

imagePath = FILE_UPLOAD_DIR + fileName

img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
return fileName

reference for complete source code: https://abhisheksharma.online/convert-base64-blob-to-image-file-in-python/

How to dock "Tool Options" to "Toolbox"?

In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.

Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.

Force flushing of output to a file while bash script is still running

alternative to stdbuf is awk '{print} END {fflush()}' I wish there were a bash builtin to do this. Normally it shouldn't be necessary, but with older versions there might be bash synchronization bugs on file descriptors.

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

package com.copy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CopyArray {

    public static void main(String[] args) {
        List<Integer> list1, list2 = null;
        Integer[] intarr = { 3, 4, 2, 1 };
        list1 = new ArrayList<Integer>(Arrays.asList(intarr));
        list1.add(30);
        list2 = Arrays.asList(intarr);
        // list2.add(40); Here, we can't modify the existing list,because it's a wrapper
        System.out.println("List1");
        Iterator<Integer> itr1 = list1.iterator();
        while (itr1.hasNext()) {
            System.out.println(itr1.next());
        }
        System.out.println("List2");
        Iterator<Integer> itr2 = list2.iterator();
        while (itr2.hasNext()) {
            System.out.println(itr2.next());
        }
    }
}

Error: unable to verify the first certificate in nodejs

Another approach to solve this is to use the following module.

node_extra_ca_certs_mozilla_bundle

This module can work without any code modification by generating a PEM file that includes all root and intermediate certificates trusted by Mozilla. You can use the following environment variable (Works with Nodejs v7.3+),

NODE_EXTRA_CA_CERTS

To generate the PEM file to use with the above environment variable. You can install the module using:

npm install --save node_extra_ca_certs_mozilla_bundle

and then launch your node script with an environment variable.

NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js

Other ways to use the generated PEM file are available at:

https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle

NOTE: I am the author of the above module.

jQuery Mobile: Stick footer to bottom of page

You can add this in your css file:

[data-role=page]{height: 100% !important; position:relative !important;}
[data-role=footer]{bottom:0; position:absolute !important; top: auto !important; width:100%;}  

So the page data-role now have 100% height, and footer is in absolute position.

Also Yappo have wrote an excellent plugin that you can find here: jQuery Mobile in a iScroll plugin http://yappo.github.com/projects/jquery.mobile.iscroll/livedemo.html

hope you found the answer!

An answer update

You can now use the data-position="fixed" attribute to keep your footer element on the bottom.
Docs and demos: http://view.jquerymobile.com/master/demos/toolbar-fixed/

Formatting floats without trailing zeros

Handling %f and you should put

%.2f

, where: .2f == .00 floats.

Example:

print "Price: %.2f" % prices[product]

output:

Price: 1.50

Stop MySQL service windows

to stop the service:

sc stop mysql56

and to start it:

sc start mysql56

you might need to change the mysql56 to whatever your version is.

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

I tried opening my Credential Manager but could not find any credentials in there that has any relation to my TFS account.

So what I did instead I logout of my hotmail account in Internet Explorer and then clear all my Internet Explorer cookies and stored password as detailed in this blog: Changing TFS credentials in Visual Studio 2012

enter image description here

After clearing out the cookies and password, restart IE and then relogin to your hotmail (or windows live account).

Then start Visual Studio and try to reconnect to TFS, you should be prompted for a credential now.

Note: A reader said that you do not have to clear out all IE cookies, just these 3 cookies, but I didn't test this.

cookie:@login.live.com/
cookie:@visualstudio.com/
cookie:@tfs.app.visualstudio.com/

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

How to comment/uncomment in HTML code

/* (opener) */ (closer)

for example,

<html>
 /*<p>Commented P Tag </p>*/
<html>

PHP Curl And Cookies

You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.

How to hide "Showing 1 of N Entries" with the dataTables.js library

It is Work for me:

language:{"infoEmpty": "No records available",}

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

UPDATE: This question was the subject of my blog on May 12th 2011. Thanks for the great question!

Suppose you have an interface as you describe, and a hundred classes that implement it. Then you decide to make one of the parameters of one of the interface's methods optional. Are you suggesting that the right thing to do is for the compiler to force the developer to find every implementation of that interface method, and make the parameter optional as well?

Suppose we did that. Now suppose the developer did not have the source code for the implementation:


// in metadata:
public class B 
{ 
    public void TestMethod(bool b) {}
}

// in source code
interface MyInterface 
{ 
    void TestMethod(bool b = false); 
}
class D : B, MyInterface {}
// Legal because D's base class has a public method 
// that implements the interface method

How is the author of D supposed to make this work? Are they required in your world to call up the author of B on the phone and ask them to please ship them a new version of B that makes the method have an optional parameter?

That's not going to fly. What if two people call up the author of B, and one of them wants the default to be true and one of them wants it to be false? What if the author of B simply refuses to play along?

Perhaps in that case they would be required to say:

class D : B, MyInterface 
{
    public new void TestMethod(bool b = false)
    {
        base.TestMethod(b);
    }
}

The proposed feature seems to add a lot of inconvenience for the programmer with no corresponding increase in representative power. What's the compelling benefit of this feature which justifies the increased cost to the user?


UPDATE: In the comments below, supercat suggests a language feature that would genuinely add power to the language and enable some scenarios similar to the one described in this question. FYI, that feature -- default implementations of methods in interfaces -- will be added to C# 8.

Cross Browser Flash Detection in Javascript

Code for one liner isFlashExists variable:

<script type='text/javascript'
    src='//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'> </script>

<script type='text/javascript'>
   var isFlashExists = swfobject.hasFlashPlayerVersion('1') ? true : false ;
   if (isFlashExists) {
    alert ('flash exists');
   } else {
    alert ('NO flash');
   }
</script>

Note that there is an alternative like this: swfobject.getFlashPlayerVersion();

Recursive Fibonacci

int fib(int n) {
    if (n == 1 || n == 2) {
        return 1;
    } else {
        return fib(n - 1) + fib(n - 2);
    }
}

in fibonacci sequence first 2 numbers always sequels to 1 then every time the value became 1 or 2 it must return 1

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

How to read the post request parameters using JavaScript

Use sessionStorage!

_x000D_
_x000D_
$(function(){_x000D_
    $('form').submit{_x000D_
       document.sessionStorage["form-data"] =  $('this').serialize();_x000D_
       document.location.href = 'another-page.html';_x000D_
    }_x000D_
});
_x000D_
_x000D_
_x000D_

At another-page.html:

_x000D_
_x000D_
var formData = document.sessionStorage["form-data"];
_x000D_
_x000D_
_x000D_

Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

How to remove non UTF-8 characters from text file

Your method must read byte by byte and fully understand and appreciate the byte wise construction of characters. The simplest method is to use an editor which will read anything but only output UTF-8 characters. Textpad is one choice.

Compiling C++11 with g++

You can check your g++ by command:

which g++
g++ --version

this will tell you which complier is currently it is pointing.

To switch to g++ 4.7 (assuming that you have installed it in your machine),run:

sudo update-alternatives --config gcc

There are 2 choices for the alternative gcc (providing /usr/bin/gcc).

  Selection    Path              Priority   Status
------------------------------------------------------------
  0            /usr/bin/gcc-4.6   60        auto mode
  1            /usr/bin/gcc-4.6   60        manual mode
* 2            /usr/bin/gcc-4.7   40        manual mode

Then select 2 as selection(My machine already pointing to g++ 4.7,so the *)

Once you switch the complier then again run g++ --version to check the switching has happened correctly.

Now compile your program with

g++ -std=c++11 your_file.cpp -o main

multiple axis in matplotlib with different scales

If I understand the question, you may interested in this example in the Matplotlib gallery.

enter image description here

Yann's comment above provides a similar example.


Edit - Link above fixed. Corresponding code copied from the Matplotlib gallery:

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right", axes=par2,
                                        offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())

plt.draw()
plt.show()

#plt.savefig("Test")

Get jQuery version from inspecting the jQuery object

For older versions of jQuery

jQuery().jquery  (or)

jQuery().fn.jquery

For newer versions of jQuery

$().jquery  (or)

$().fn.jquery

How to skip the first n rows in sql query

I know it's quite late now to answer the query. But I have a little different solution than the others which I believe has better performance because no comparisons are performed in the SQL query only sorting is done. You can see its considerable performance improvement basically when value of SKIP is LARGE enough.

  1. Best performance but only for SQL Server 2012 and above. Originally from @Majid Basirati's answer which is worth mentioning again.

    DECLARE @Skip INT = 2, @Take INT = 2
    
    SELECT * FROM TABLE_NAME
    ORDER BY ID ASC
    OFFSET (@Skip) ROWS FETCH NEXT (@Take) ROWS ONLY
    
  2. Not as Good as the first one but compatible with SQL Server 2005 and above.

    DECLARE @Skip INT = 2, @Take INT = 2
    
    SELECT * FROM 
    (
        SELECT TOP (@Take) * FROM 
        (
            SELECT TOP (@Take + @Skip) * FROM TABLE_NAME
            ORDER BY ID ASC
        ) T1
        ORDER BY ID DESC
    ) T2
    ORDER BY ID ASC
    

Where can I find a list of escape characters required for my JSON ajax return type?

As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

Which @NotNull Java annotation should I use?

There are already too many answers here, but (a) it's 2019, and there's still no "standard" Nullable and (b) no other answer references Kotlin.

The reference to Kotlin is important, because Kotlin is 100% interoperable with Java and it has a core Null Safety feature. When calling Java libraries, it can take advantage of those annotations to let Kotlin tools know if a Java API can accept or return null.

As far as I know, the only Nullable packages compatible with Kotlin are org.jetbrains.annotations and android.support.annotation (now androidx.annotation). The latter is only compatible with Android so it can't be used in non-Android JVM/Java/Kotlin projects. However, the JetBrains package works everywhere.

So if you develop Java packages that should also work in Android and Kotlin (and be supported by Android Studio and IntelliJ), your best choice is probably the JetBrains package.

Maven:

<dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations-java5</artifactId>
    <version>15.0</version>
</dependency>

Gradle:

implementation 'org.jetbrains:annotations-java5:15.0'

how to change onclick event with jquery?

@Amirali

console.log(document.getElementById("SAVE_FOOTER"));
document.getElementById("SAVE_FOOTER").attribute("onclick","console.log('c')");

throws:

Uncaught TypeError: document.getElementById(...).attribute is not a function

in chrome.

Element exists and is dumped in console;

Android Studio - debug keystore

If you use Windows, probably the location is like this:

C:\User\YourUser\.android\debug.keystore

How to resolve symbolic links in a shell script

To work around the Mac incompatibility, I came up with

echo `php -r "echo realpath('foo');"`

Not great but cross OS

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

Find the IP address of the client in an SSH session

Check if there is an environment variable called:

$SSH_CLIENT 

OR

$SSH_CONNECTION

(or any other environment variables) which gets set when the user logs in. Then process it using the user login script.

Extract the IP:

$ echo $SSH_CLIENT | awk '{ print $1}'
1.2.3.4
$ echo $SSH_CONNECTION | awk '{print $1}'
1.2.3.4

Change select box option background color

Simply change bg color

select { background: #6ac17a; color:#fff; }

EPPlus - Read Excel Table

Working solution with validate email,mobile number

 public class ExcelProcessing
        {
            public List<ExcelUserData> ReadExcel()
            {
                string path = Config.folderPath + @"\MemberUploadFormat.xlsx";
    
                using (var excelPack = new ExcelPackage())
                {
                    //Load excel stream
                    using (var stream = File.OpenRead(path))
                    {
                        excelPack.Load(stream);
                    }
    
                    //Lets Deal with first worksheet.(You may iterate here if dealing with multiple sheets)
                    var ws = excelPack.Workbook.Worksheets[0];
    
                    List<ExcelUserData> userList = new List<ExcelUserData>();
    
                    int colCount = ws.Dimension.End.Column;  //get Column Count
                    int rowCount = ws.Dimension.End.Row;
                       
                    for (int row = 2; row <= rowCount; row++) // start from to 2 omit header
                    {
                       
                        bool IsValid = true;
                        ExcelUserData _user = new ExcelUserData();
    
                        for (int col = 1; col <= colCount; col++)
                        {
                            if (col == 1)
                            {
                                _user.FirstName = ws.Cells[row, col].Value?.ToString().Trim();
                                if (string.IsNullOrEmpty(_user.FirstName))
                                {
                                    _user.ErrorMessage += "Enter FirstName <br/>";
                                    IsValid = false;
                                }
                            }
                            else if (col == 2)
                            {
                                _user.Email = ws.Cells[row, col].Value?.ToString().Trim();
    
                                if (string.IsNullOrEmpty(_user.Email))
                                {
                                    _user.ErrorMessage += "Enter Email <br/>";
                                    IsValid = false;
                                }
                                else if (!IsValidEmail(_user.Email))
                                {
                                    _user.ErrorMessage += "Invalid Email Address <br/>";
                                    IsValid = false;
                                }
                            }
                            else if (col ==3)
                            {
                                _user.MobileNo = ws.Cells[row, col].Value?.ToString().Trim();
    
                                if (string.IsNullOrEmpty(_user.MobileNo))
                                {
                                    _user.ErrorMessage += "Enter Mobile No <br/>";
                                    IsValid = false;
                                }
                                else if (_user.MobileNo.Length != 10)
                                {
                                    _user.ErrorMessage += "Invalid Mobile No <br/>";
                                    IsValid = false;
                                }
    
                            }
                            else if (col == 4)
                            {
                                _user.IsAdmin = ws.Cells[row, col].Value?.ToString().Trim();
    
                                if (string.IsNullOrEmpty(_user.IsAdmin))
                                {
                                    _user.IsAdmin = "0";
                                }
                            }
    
                            _user.IsValid = IsValid;
                        }
                        userList.Add(_user);
                    }
                    return userList;
                }
            }
            public static bool IsValidEmail(string email)
            {
                Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                 RegexOptions.CultureInvariant | RegexOptions.Singleline);
    
                return regex.IsMatch(email);
            }
        }

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

Below solution is a clean work around.It does not compromises security because we are using same strict firewall.

The Steps for fixing is as below:

STEP 1 : Create a Class overriding StrictHttpFirewall as below.

package com.biz.brains.project.security.firewall;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpMethod;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;

public class CustomStrictHttpFirewall implements HttpFirewall {
    private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.unmodifiableSet(Collections.emptySet());

    private static final String ENCODED_PERCENT = "%25";

    private static final String PERCENT = "%";

    private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections.unmodifiableList(Arrays.asList("%2e", "%2E"));

    private static final List<String> FORBIDDEN_SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));

    private static final List<String> FORBIDDEN_FORWARDSLASH = Collections.unmodifiableList(Arrays.asList("%2f", "%2F"));

    private static final List<String> FORBIDDEN_BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));

    private Set<String> encodedUrlBlacklist = new HashSet<String>();

    private Set<String> decodedUrlBlacklist = new HashSet<String>();

    private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();

    public CustomStrictHttpFirewall() {
        urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);

        this.encodedUrlBlacklist.add(ENCODED_PERCENT);
        this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        this.decodedUrlBlacklist.add(PERCENT);
    }

    public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
        this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
    }

    public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
        if (allowedHttpMethods == null) {
            throw new IllegalArgumentException("allowedHttpMethods cannot be null");
        }
        if (allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            this.allowedHttpMethods = ALLOW_ANY_HTTP_METHOD;
        } else {
            this.allowedHttpMethods = new HashSet<>(allowedHttpMethods);
        }
    }

    public void setAllowSemicolon(boolean allowSemicolon) {
        if (allowSemicolon) {
            urlBlacklistsRemoveAll(FORBIDDEN_SEMICOLON);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        }
    }

    public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
        if (allowUrlEncodedSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        }
    }

    public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
        if (allowUrlEncodedPeriod) {
            this.encodedUrlBlacklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
        } else {
            this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        }
    }

    public void setAllowBackSlash(boolean allowBackSlash) {
        if (allowBackSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_BACKSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
        }
    }

    public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
        if (allowUrlEncodedPercent) {
            this.encodedUrlBlacklist.remove(ENCODED_PERCENT);
            this.decodedUrlBlacklist.remove(PERCENT);
        } else {
            this.encodedUrlBlacklist.add(ENCODED_PERCENT);
            this.decodedUrlBlacklist.add(PERCENT);
        }
    }

    private void urlBlacklistsAddAll(Collection<String> values) {
        this.encodedUrlBlacklist.addAll(values);
        this.decodedUrlBlacklist.addAll(values);
    }

    private void urlBlacklistsRemoveAll(Collection<String> values) {
        this.encodedUrlBlacklist.removeAll(values);
        this.decodedUrlBlacklist.removeAll(values);
    }

    @Override
    public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
        rejectForbiddenHttpMethod(request);
        rejectedBlacklistedUrls(request);

        if (!isNormalized(request)) {
            request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL was not normalized."));
        }

        String requestUri = request.getRequestURI();
        if (!containsOnlyPrintableAsciiCharacters(requestUri)) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The requestURI was rejected because it can only contain printable ASCII characters."));
        }
        return new FirewalledRequest(request) {
            @Override
            public void reset() {
            }
        };
    }

    private void rejectForbiddenHttpMethod(HttpServletRequest request) {
        if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            return;
        }
        if (!this.allowedHttpMethods.contains(request.getMethod())) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the HTTP method \"" +
                    request.getMethod() +
                    "\" was not included within the whitelist " +
                    this.allowedHttpMethods));
        }
    }

    private void rejectedBlacklistedUrls(HttpServletRequest request) {
        for (String forbidden : this.encodedUrlBlacklist) {
            if (encodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
        for (String forbidden : this.decodedUrlBlacklist) {
            if (decodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
    }

    @Override
    public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
        return new FirewalledResponse(response);
    }

    private static Set<String> createDefaultAllowedHttpMethods() {
        Set<String> result = new HashSet<>();
        result.add(HttpMethod.DELETE.name());
        result.add(HttpMethod.GET.name());
        result.add(HttpMethod.HEAD.name());
        result.add(HttpMethod.OPTIONS.name());
        result.add(HttpMethod.PATCH.name());
        result.add(HttpMethod.POST.name());
        result.add(HttpMethod.PUT.name());
        return result;
    }

    private static boolean isNormalized(HttpServletRequest request) {
        if (!isNormalized(request.getRequestURI())) {
            return false;
        }
        if (!isNormalized(request.getContextPath())) {
            return false;
        }
        if (!isNormalized(request.getServletPath())) {
            return false;
        }
        if (!isNormalized(request.getPathInfo())) {
            return false;
        }
        return true;
    }

    private static boolean encodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getContextPath(), value)) {
            return true;
        }
        return valueContains(request.getRequestURI(), value);
    }

    private static boolean decodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getServletPath(), value)) {
            return true;
        }
        if (valueContains(request.getPathInfo(), value)) {
            return true;
        }
        return false;
    }

    private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
        int length = uri.length();
        for (int i = 0; i < length; i++) {
            char c = uri.charAt(i);
            if (c < '\u0020' || c > '\u007e') {
                return false;
            }
        }

        return true;
    }

    private static boolean valueContains(String value, String contains) {
        return value != null && value.contains(contains);
    }

    private static boolean isNormalized(String path) {
        if (path == null) {
            return true;
        }

        if (path.indexOf("//") > -1) {
            return false;
        }

        for (int j = path.length(); j > 0;) {
            int i = path.lastIndexOf('/', j - 1);
            int gap = j - i;

            if (gap == 2 && path.charAt(i + 1) == '.') {
                // ".", "/./" or "/."
                return false;
            } else if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
                return false;
            }

            j = i;
        }

        return true;
    }

}

STEP 2 : Create a FirewalledResponse class

package com.biz.brains.project.security.firewall;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

class FirewalledResponse extends HttpServletResponseWrapper {
    private static final Pattern CR_OR_LF = Pattern.compile("\\r|\\n");
    private static final String LOCATION_HEADER = "Location";
    private static final String SET_COOKIE_HEADER = "Set-Cookie";

    public FirewalledResponse(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void sendRedirect(String location) throws IOException {
        // TODO: implement pluggable validation, instead of simple blacklisting.
        // SEC-1790. Prevent redirects containing CRLF
        validateCrlf(LOCATION_HEADER, location);
        super.sendRedirect(location);
    }

    @Override
    public void setHeader(String name, String value) {
        validateCrlf(name, value);
        super.setHeader(name, value);
    }

    @Override
    public void addHeader(String name, String value) {
        validateCrlf(name, value);
        super.addHeader(name, value);
    }

    @Override
    public void addCookie(Cookie cookie) {
        if (cookie != null) {
            validateCrlf(SET_COOKIE_HEADER, cookie.getName());
            validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
            validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
            validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
            validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
        }
        super.addCookie(cookie);
    }

    void validateCrlf(String name, String value) {
        if (hasCrlf(name) || hasCrlf(value)) {
            throw new IllegalArgumentException(
                    "Invalid characters (CR/LF) in header " + name);
        }
    }

    private boolean hasCrlf(String value) {
        return value != null && CR_OR_LF.matcher(value).find();
    }
}

STEP 3: Create a custom Filter to suppress the RejectedException

package com.biz.brains.project.security.filter;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestRejectedExceptionFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            try {
                RequestRejectedException requestRejectedException=(RequestRejectedException) servletRequest.getAttribute("isNormalized");
                if(Objects.nonNull(requestRejectedException)) {
                    throw requestRejectedException;
                }else {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } catch (RequestRejectedException requestRejectedException) {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                log
                    .error(
                            "request_rejected: remote={}, user_agent={}, request_url={}",
                            httpServletRequest.getRemoteHost(),  
                            httpServletRequest.getHeader(HttpHeaders.USER_AGENT),
                            httpServletRequest.getRequestURL(), 
                            requestRejectedException
                    );

                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
}

STEP 4: Add the custom filter to spring filter chain in security configuration

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.addFilterBefore(new RequestRejectedExceptionFilter(),
             ChannelProcessingFilter.class);
}

Now using above fix, we can handle RequestRejectedException with Error 404 page.

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

According to this SO answer, it occurs due to an AWS SDK bug that appears to be solved in version 2.6.30 of the SDK, so updating the version to a newer, can help you fixing the problem.

How long is the SHA256 hash?

Encoding options for SHA256's 256 bits:

  1. Base64: 6 bits per char = CHAR(44) including padding character
  2. Hex: 4 bits per char = CHAR(64)
  3. Binary: 8 bits per byte = BINARY(32)

What are the differences in die() and exit() in PHP?

Functionality-wise they are identical but I use them in the following scenarios to make code readable:

Use die() when there is an error and have to stop the execution.

e.g. die( 'Oops! Something went wrong' );

Use exit() when there is not an error and have to stop the execution.

e.g. exit( 'Request has been processed successfully!' );

Align text to the bottom of a div

You now can do this with Flexbox justify-content: flex-end now:

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
  align-items: flex-end;_x000D_
  width: 150px;_x000D_
  height: 150px;_x000D_
  border: solid 1px red;_x000D_
}_x000D_
  
_x000D_
<div>_x000D_
  Something to align_x000D_
</div>
_x000D_
_x000D_
_x000D_

Consult your Caniuse to see if Flexbox is right for you.

ssh script returns 255 error

I was stumped by this. Once I got passed the 255 problem... I ended up with a mysterious error code 1. This is the foo to get that resolved:

 pssh -x '-tt' -h HOSTFILELIST -P "sudo yum -y install glibc"

-P means write the output out as you go and is optional. But the -x '-tt' trick is what forces a psuedo tty to be allocated.

You can get a clue what the error code 1 means this if you try:

ssh AHOST "sudo yum -y install glibc"

You may see:

[slc@bastion-ci ~]$ ssh MYHOST "sudo yum -y install glibc"
sudo: sorry, you must have a tty to run sudo
[slc@bastion-ci ~]$ echo $?
1

Notice the return code for this is 1, which is what pssh is reporting to you.

I found this -x -tt trick here. Also note that turning on verbose mode (pssh --verbose) for these cases does nothing to help you.

How to find path of active app.config file?

I tried one of the previous answers in a web app (actually an Azure web role running locally) and it didn't quite work. However, this similar approach did work:

var map = new ExeConfigurationFileMap { ExeConfigFilename = "MyComponent.dll.config" };
var path = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None).FilePath;

The config file turned out to be in C:\Program Files\IIS Express\MyComponent.dll.config. Interesting place for it.

Java HTTPS client certificate authentication

I think the fix here was the keystore type, pkcs12(pfx) always have private key and JKS type can exist without private key. Unless you specify in your code or select a certificate thru browser, the server have no way of knowing it is representing a client on the other end.

How to replace a hash key with another key

Answering exactly what was asked:

hash = {"_id"=>"4de7140772f8be03da000018"}
hash.transform_keys { |key| key[1..] }
# => {"id"=>"4de7140772f8be03da000018"}

The method transform_keys exists in the Hash class since Ruby version 2.5.

https://blog.bigbinary.com/2018/01/09/ruby-2-5-adds-hash-transform_keys-method.html

Converting String Array to an Integer Array

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class MultiArg {

    Scanner sc;
    int n;
    String as;
    List<Integer> numList = new ArrayList<Integer>();

    public void fun() {
        sc = new Scanner(System.in);
        System.out.println("enter value");
        while (sc.hasNextInt())
            as = sc.nextLine();
    }

    public void diplay() {
        System.out.println("x");
        Integer[] num = numList.toArray(new Integer[numList.size()]);
        System.out.println("show value " + as);
        for (Integer m : num) {
            System.out.println("\t" + m);
        }
    }
}

but to terminate the while loop you have to put any charecter at the end of input.

ex. input:

12 34 56 78 45 67 .

output:

12 34 56 78 45 67

What is the --save option for npm install?

–npm install --save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give the desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.

npm install --save

What does "to stub" mean in programming?

RPC Stubs

  • Basically, a client-side stub is a procedure that looks to the client as if it were a callable server procedure.
  • A server-side stub looks to the server as if it's a calling client.
  • The client program thinks it is calling the server; in fact, it's calling the client stub.
  • The server program thinks it's called by the client; in fact, it's called by the server stub.
  • The stubs send messages to each other to make the RPC happen.

Source

How to use PowerShell select-string to find more than one pattern in a file?

To search for multiple matches in each file, we can sequence several Select-String calls:

Get-ChildItem C:\Logs |
  where { $_ | Select-String -Pattern 'VendorEnquiry' } |
  where { $_ | Select-String -Pattern 'Failed' } |
  ...

At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.

Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:

filter MultiSelect-String( [string[]]$Patterns ) {
  # Check the current item against all patterns.
  foreach( $Pattern in $Patterns ) {
    # If one of the patterns does not match, skip the item.
    $matched = @($_ | Select-String -Pattern $Pattern)
    if( -not $matched ) {
      return
    }
  }

  # If all patterns matched, pass the item through.
  $_
}

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...


Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:

function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
  $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}

PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True

Left function in c#

It sounds like you're asking about a function

string Left(string s, int left)

that will return the leftmost left characters of the string s. In that case you can just use String.Substring. You can write this as an extension method:

public static class StringExtensions
{
    public static string Left(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        maxLength = Math.Abs(maxLength);

        return ( value.Length <= maxLength 
               ? value 
               : value.Substring(0, maxLength)
               );
    }
}

and use it like so:

string left = s.Left(number);

For your specific example:

string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);

How can I parse a YAML file in Python

To access any element of a list in a YAML file like this:

global:
  registry:
    url: dtr-:5000/
    repoPath:
  dbConnectionString: jdbc:oracle:thin:@x.x.x.x:1521:abcd

You can use following python script:

import yaml

with open("/some/path/to/yaml.file", 'r') as f:
    valuesYaml = yaml.load(f, Loader=yaml.FullLoader)

print(valuesYaml['global']['dbConnectionString'])

Using a dictionary to select function to execute

You are wasting your time:

  1. You are about to write a lot of useless code and introduce new bugs.
  2. To execute the function, your user will need to know the P1 name anyway.
  3. Etc., etc., etc.

Just put all your functions in the .py file:

# my_module.py

def f1():
    pass

def f2():
    pass

def f3():
    pass

And use them like this:

import my_module

my_module.f1()
my_module.f2()
my_module.f3()

or:

from my_module import f1
from my_module import f2
from my_module import f3

f1()
f2()
f3()

This should be enough for starters.

How to convert int to float in C?

Integer division truncates, so (50/100) results in 0. You can cast to float (better double) or multiply with 100.0 (for double precision, 100.0f for float precision) first,

double percentage;
// ...
percentage = 100.0*number/total;
// percentage = (double)number/total * 100;

or

float percentage;
// ...
percentage = (float)number/total * 100;
// percentage = 100.0f*number/total;

Since floating point arithmetic is not associative, the results of 100.0*number/total and (double)number/total * 100 may be slightly different (the same holds for float), but it's extremely unlikely to influence the first two places after the decimal point, so it probably doesn't matter which way you choose.

Importing CSV with line breaks in Excel 2007

If anyone stumbling across this thread and is looking for a definitive answer here goes (credit to the person mentioning LibreOffice:

1) Install LibreOffice 2) Open Calc and import file 3) My txt file had the fields separated by , and character fields enclosed in " 4) save as ODS file 5) Open ODS file in Excel 6) Save as .xls(x) 7) Done. 8) This worked perfectly for me and saved me BIGTIME!

Visual Studio Code Automatic Imports

If you are using angular, check that the tsconfig.json does not contain errors. (in the problems terminal)

For some reason I doubled these lines, and it didn't work for me

{
  "module": "esnext",
  "moduleResolution": "node",
}

Best practices for styling HTML emails

'Fraid so. I'd make an HTML page with a stylesheet, then use jQuery to apply the stylesheet to the style attr of each element. Something like this:

var styleAttributes = ['color','font-size']; // all the attributes you've applied in your stylesheet
for (i in styleAttributes) {
    $('body *').css(styleAttributes[i],function () {
        $(this).css(styleAttributes[i]);
    });
}

Then copy the DOM and use that in the email.

How to remove the last character from a string?

Why not just one liner?

public static String removeLastChar(String str) {
    return removeLastChars(str, 1);
}

public static String removeLastChars(String str, int chars) {
    return str.substring(0, str.length() - chars);
}

Full Code

public class Main {
    public static void main (String[] args) throws java.lang.Exception {
        String s1 = "Remove Last CharacterY";
        String s2 = "Remove Last Character2";
        System.out.println("After removing s1==" + removeLastChar(s1) + "==");
        System.out.println("After removing s2==" + removeLastChar(s2) + "==");
    }
    
    public static String removeLastChar(String str) {
        return removeLastChars(str, 1);
    }

    public static String removeLastChars(String str, int chars) {
        return str.substring(0, str.length() - chars);
    }
}

Demo

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

fatal: could not read Username for 'https://github.com': No such file or directory

I found my answer here:

edit ~/.gitconfig and add the following:

[url "[email protected]:"]
 insteadOf = https://github.com/

Although it solves a different problem, the error code is the same...

overlay two images in android to set an imageview

Its a bit late answer, but it covers merging images from urls using Picasso

MergeImageView

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.List;

public class MergeImageView extends ImageView {

    private SparseArray<Bitmap> bitmaps = new SparseArray<>();
    private Picasso picasso;
    private final int DEFAULT_IMAGE_SIZE = 50;
    private int MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE;
    private int MAX_WIDTH = DEFAULT_IMAGE_SIZE * 2, MAX_HEIGHT = DEFAULT_IMAGE_SIZE * 2;
    private String picassoRequestTag = null;

    public MergeImageView(Context context) {
        super(context);
    }

    public MergeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public boolean isInEditMode() {
        return true;
    }

    public void clearResources() {
        if (bitmaps != null) {
            for (int i = 0; i < bitmaps.size(); i++)
                bitmaps.get(i).recycle();
            bitmaps.clear();
        }
        // cancel picasso requests
        if (picasso != null && AppUtils.ifNotNullEmpty(picassoRequestTag))
            picasso.cancelTag(picassoRequestTag);
        picasso = null;
        bitmaps = null;
    }

    public void createMergedBitmap(Context context, List<String> imageUrls, String picassoTag) {
        picasso = Picasso.with(context);
        int count = imageUrls.size();
        picassoRequestTag = picassoTag;

        boolean isEven = count % 2 == 0;
        // if url size are not even make MIN_IMAGE_SIZE even
        MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE + (isEven ? count / 2 : (count / 2) + 1);
        // set MAX_WIDTH and MAX_HEIGHT to twice of MIN_IMAGE_SIZE
        MAX_WIDTH = MAX_HEIGHT = MIN_IMAGE_SIZE * 2;
        // in case of odd urls increase MAX_HEIGHT
        if (!isEven) MAX_HEIGHT = MAX_WIDTH + MIN_IMAGE_SIZE;

        // create default bitmap
        Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wallpaper),
                MIN_IMAGE_SIZE, MIN_IMAGE_SIZE, false);

        // change default height (wrap_content) to MAX_HEIGHT
        int height = Math.round(AppUtils.convertDpToPixel(MAX_HEIGHT, context));
        setMinimumHeight(height * 2);

        // start AsyncTask
        for (int index = 0; index < count; index++) {
            // put default bitmap as a place holder
            bitmaps.put(index, bitmap);
            new PicassoLoadImage(index, imageUrls.get(index)).execute();
            // if you want parallel execution use
            // new PicassoLoadImage(index, imageUrls.get(index)).(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    private class PicassoLoadImage extends AsyncTask<String, Void, Bitmap> {

        private int index = 0;
        private String url;

        PicassoLoadImage(int index, String url) {
            this.index = index;
            this.url = url;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                // synchronous picasso call
                return picasso.load(url).resize(MIN_IMAGE_SIZE, MIN_IMAGE_SIZE).tag(picassoRequestTag).get();
            } catch (IOException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap output) {
            super.onPostExecute(output);
            if (output != null)
                bitmaps.put(index, output);

            // create canvas
            Bitmap.Config conf = Bitmap.Config.RGB_565;
            Bitmap canvasBitmap = Bitmap.createBitmap(MAX_WIDTH, MAX_HEIGHT, conf);
            Canvas canvas = new Canvas(canvasBitmap);
            canvas.drawColor(Color.WHITE);

            // if height and width are equal we have even images
            boolean isEven = MAX_HEIGHT == MAX_WIDTH;
            int imageSize = bitmaps.size();
            int count = imageSize;

            // we have odd images
            if (!isEven) count = imageSize - 1;
            for (int i = 0; i < count; i++) {
                Bitmap bitmap = bitmaps.get(i);
                canvas.drawBitmap(bitmap, bitmap.getWidth() * (i % 2), bitmap.getHeight() * (i / 2), null);
            }
            // if images are not even set last image width to MAX_WIDTH
            if (!isEven) {
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmaps.get(count), MAX_WIDTH, MIN_IMAGE_SIZE, false);
                canvas.drawBitmap(scaledBitmap, scaledBitmap.getWidth() * (count % 2), scaledBitmap.getHeight() * (count / 2), null);
            }
            // set bitmap
            setImageBitmap(canvasBitmap);
        }
    }
}

xml

<com.example.MergeImageView
    android:id="@+id/iv_thumb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Example

List<String> urls = new ArrayList<>();
String picassoTag = null;
// add your urls
((MergeImageView)findViewById(R.id.iv_thumb)).
        createMergedBitmap(MainActivity.this, urls,picassoTag);

How to monitor network calls made from iOS Simulator

Personally, I use Charles for that kind of stuff.
When enabled, it will monitor every network request, displaying extended request details, including support for SSL and various request/reponse format, like JSON, etc...

You can also configure it to sniff only requests to specific servers, not the whole traffic.

It's commercial software, but there is a trial, and IMHO it's definitively a great tool.

How do you obtain a Drawable object from a resource id in android package?

As of API 21, you should use the getDrawable(int, Theme) method instead of getDrawable(int), as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int) method is equivalent to calling getDrawable(int, null).

You should use the following code from the support library instead:

ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

Using this method is equivalent to calling:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}

How to set locale in DatePipe in Angular 2?

This might be a little bit late, but in my case (angular 6), I created a simple pipe on top of DatePipe, something like this:

private _regionSub: Subscription;
private _localeId: string;

constructor(private _datePipe: DatePipe, private _store: Store<any>) {
  this._localeId = 'en-AU';
  this._regionSub = this._store.pipe(select(selectLocaleId))
    .subscribe((localeId: string) => {
      this._localeId = localeId || 'en-AU';
    });
}

ngOnDestroy() { // Unsubscribe }

transform(value: string | number, format?: string): string {
  const dateFormat = format || getLocaleDateFormat(this._localeId, FormatWidth.Short);
  return this._datePipe.transform(value, dateFormat, undefined, this._localeId);
}

May not be the best solution, but simple and works.

In android how to set navigation drawer header image and name programmatically in class file?

First you need to access the navigation drawer in your MainActivity(or the calling activity) like this:

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

Then you need to remove the header layout from the activity_main.xml because the layout will be inflated programatically in the MainActivity. Your activity_main.xml should look like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout            

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/activity_main_drawer" />

    </android.support.v4.widget.DrawerLayout>

Then in your MainActivity, we inflate the nav_header_main layout and get access to its views, in this case the ImageView and TextView

//inflate header layout
View navView =  navigationView.inflateHeaderView(R.layout.nav_header_main);
//reference to views
ImageView imgvw = (ImageView)navView.findViewById(R.id.imageView);
TextView tv = (TextView)navView.findViewById(R.id.textview);
//set views
imgvw.setImageResource(R.drawable.your_image);
tv.setText("new text");

navigationView.setNavigationItemSelectedListener(this);

You can read more here

How to run a PowerShell script without displaying a window?

When you scheduled task, just select "Run whether user is logged on or not" under the "General" tab.

Alternate way is to let the task run as another user.

Iterating Over Dictionary Key Values Corresponding to List in Python

List comprehension can shorten things...

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]

Multiline TextView in Android?

Why don't you declare a string instead of writing a long lines into the layout file. For this you have to declare a line of code into layout file 'android:text="@string/text"' and go to the \\app\src\main\res\values\strings.xml and add a line of code ' Your multiline text here' Also use '\n' to break the line from any point else the line will automatically be adjusted.

python how to "negate" value : if true return false, if false return true

In python, not is a boolean operator which gets the opposite of a value:

>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False

And True == 1 and False == 0 (if you need to convert it to an integer, you can use int())

Setting the classpath in java using Eclipse IDE

Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project

Creating columns in listView and add items

You need to set property for the control:

listView1.View = View.Details;

How to make lists contain only distinct element in Python?

Let me explain to you by an example:

if you have Python list

>>> randomList = ["a","f", "b", "c", "d", "a", "c", "e", "d", "f", "e"]

and you want to remove duplicates from it.

>>> uniqueList = []

>>> for letter in randomList:
    if letter not in uniqueList:
        uniqueList.append(letter)

>>> uniqueList
['a', 'f', 'b', 'c', 'd', 'e']

This is how you can remove duplicates from the list.

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

Had the same problem, thanks mikej.

In WLS 10.3 this configuration can be found in Services > JTA menu, or if you click on the domain name (first item in the menu) - on the Configuration > JTA tabs.

alt text

Reverse a string in Python

original = "string"

rev_index = original[::-1]
rev_func = list(reversed(list(original))) #nsfw

print(original)
print(rev_index)
print(''.join(rev_func))

Splitting a string into chunks of a certain size

Here's my 2 cents:

  IEnumerable<string> Split(string str, int chunkSize)
  {
     while (!string.IsNullOrWhiteSpace(str))
     {
        var chunk = str.Take(chunkSize).ToArray();
        str = str.Substring(chunk.Length);
        yield return new string(chunk);

     }

  }//Split

How to override application.properties during production in Spring-Boot?

I know you asked how to do this, but the answer is you should not do this.

Instead, have a application.properties, application-default.properties application-dev.properties etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev

You can also override some things at test time using @TestPropertySource

Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?

Spring Boot is already giving you enough ways to do this right.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

MySQL, Concatenate two columns

In php, we have two option to concatenate table columns.

First Option using Query

In query, CONCAT keyword used to concatenate two columns

SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;

Second Option using symbol ( . )

After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values

$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;

Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc

Deserialize JSON into C# dynamic object?

The simplest way is:

Just include this DLL file.

Use the code like this:

dynamic json = new JDynamic("{a:'abc'}");
// json.a is a string "abc"

dynamic json = new JDynamic("{a:3.1416}");
// json.a is 3.1416m

dynamic json = new JDynamic("{a:1}");
// json.a is

dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
// And you can use json[0]/ json[2] to get the elements

dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
// And you can use  json.a[0]/ json.a[2] to get the elements

dynamic json = new JDynamic("[{b:1},{c:1}]");
// json.Length/json.Count is 2.
// And you can use the  json[0].b/json[1].c to get the num.

Custom CSS Scrollbar for Firefox

As of late 2018, there is now limited customization available in Firefox!

See these answers:

And this for background info: https://bugzilla.mozilla.org/show_bug.cgi?id=1460109


There's no Firefox equivalent to ::-webkit-scrollbar and friends.

You'll have to stick with JavaScript.

Plenty of people would like this feature, see: https://bugzilla.mozilla.org/show_bug.cgi?id=77790


As far as JavaScript replacements go, you can try:

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

css 100% width div not taking up full width of parent

The problem is caused by your #grid having a width:1140px.

You need to set a min-width:1140px on the body.

This will stop the body from getting smaller than the #grid. Remove width:100% as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/

html, body{
    margin:0;
    padding:0;
    min-width: 1140px; /* this is the important part*/
}
#grid-container{
    background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
    width:1140px;
    margin:0px auto;
}

Populate unique values into a VBA array from Excel

The VBA script below looks for all unique values from cell B5 all the way down to the very last cell in column B… $B$1048576. Once it is found, they are stored in the array (objDict).

Private Const SHT_MASTER = “MASTER”
Private Const SHT_INST_INDEX = “InstrumentIndex”

Sub UniqueList()
    Dim Xyber
    Dim objDict As Object
    Dim lngRow As Long

    Sheets(SHT_MASTER).Activate
    Xyber = Application.Transpose(Sheets(SHT_MASTER).Range([b5], Cells(Rows.count, “B”).End(xlUp)))
    Sheets(SHT_INST_INDEX).Activate
    Set objDict = CreateObject(“Scripting.Dictionary”)
    For lngRow = 1 To UBound(Xyber, 1)
    If Len(Xyber(lngRow)) > 0 Then objDict(Xyber(lngRow)) = 1
    Next
    Sheets(SHT_INST_INDEX).Range(“B1:B” & objDict.count) = Application.Transpose(objDict.keys)
End Sub

I have tested and documented with some screenshots of the this solution. Here is the link where you can find it....

http://xybernetics.com/techtalk/excelvba-getarrayofuniquevaluesfromspecificcolumn/

How to diff a commit with its parent?

Use git show $COMMIT. It'll show you the log message for the commit, and the diff of that particular commit.

How to get just numeric part of CSS property with jQuery?

The simplest way to get the element width without units is :

target.width()

Source : https://api.jquery.com/width/#width2

How to install Android SDK on Ubuntu?

Android SDK Manager

Get it from the Snap Store

sudo snap install androidsdk

Usage

You can use the sdkmanager to perform the following tasks.

List installed and available packages

androidsdk --list [options]

Install packages

androidsdk packages [options]

The packages argument is an SDK-style path as shown with the --list command, wrapped in quotes (for example, "build-tools;29.0.0" or "platforms;android-28"). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.

For example, here's how to install the latest platform tools (which includes adb and fastboot) and the SDK tools for API level 28:

androidsdk "platform-tools" "platforms;android-28"

Alternatively, you can pass a text file that specifies all packages:

androidsdk --package_file=package_file [options]

The package_file argument is the location of a text file in which each line is an SDK-style path of a package to install (without quotes).

To uninstall, simply add the --uninstall flag:

androidsdk --uninstall packages [options]
androidsdk --uninstall --package_file=package_file [options]

Update all installed packages

androidsdk --update [options]

Note

androidsdk it is snap wraper of sdkmanager all options of sdkmanager work with androidsdk

Location of installed android sdk files : /home/user/AndroidSDK

See all sdkmanager options in google documentation

Equation for testing if a point is inside a circle

Moving into the world of 3D if you want to check if a 3D point is in a Unit Sphere you end up doing something similar. All that is needed to work in 2D is to use 2D vector operations.

    public static bool Intersects(Vector3 point, Vector3 center, float radius)
    {
        Vector3 displacementToCenter = point - center;

        float radiusSqr = radius * radius;

        bool intersects = displacementToCenter.magnitude < radiusSqr;

        return intersects;
    }

How do I use IValidatableObject?

First off, thanks to @paper1337 for pointing me to the right resources...I'm not registered so I can't vote him up, please do so if anybody else reads this.

Here's how to accomplish what I was trying to do.

Validatable class:

public class ValidateMe : IValidatableObject
{
    [Required]
    public bool Enable { get; set; }

    [Range(1, 5)]
    public int Prop1 { get; set; }

    [Range(1, 5)]
    public int Prop2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();
        if (this.Enable)
        {
            Validator.TryValidateProperty(this.Prop1,
                new ValidationContext(this, null, null) { MemberName = "Prop1" },
                results);
            Validator.TryValidateProperty(this.Prop2,
                new ValidationContext(this, null, null) { MemberName = "Prop2" },
                results);

            // some other random test
            if (this.Prop1 > this.Prop2)
            {
                results.Add(new ValidationResult("Prop1 must be larger than Prop2"));
            }
        }
        return results;
    }
}

Using Validator.TryValidateProperty() will add to the results collection if there are failed validations. If there is not a failed validation then nothing will be add to the result collection which is an indication of success.

Doing the validation:

    public void DoValidation()
    {
        var toValidate = new ValidateMe()
        {
            Enable = true,
            Prop1 = 1,
            Prop2 = 2
        };

        bool validateAllProperties = false;

        var results = new List<ValidationResult>();

        bool isValid = Validator.TryValidateObject(
            toValidate,
            new ValidationContext(toValidate, null, null),
            results,
            validateAllProperties);
    }

It is important to set validateAllProperties to false for this method to work. When validateAllProperties is false only properties with a [Required] attribute are checked. This allows the IValidatableObject.Validate() method handle the conditional validations.

Reducing video size with same format and reducing frame size

If you want to keep same screen size, you can consider using crf factor: https://trac.ffmpeg.org/wiki/Encode/H.264

Here is the command which works for me: (on mac you need to add -strict -2 to be able to use aac audio codec.

ffmpeg -i input.mp4 -c:v libx264 -crf 24 -b:v 1M -c:a aac output.mp4

How can I prevent a window from being resized with tkinter?

You can use the minsize and maxsize to set a minimum & maximum size, for example:

def __init__(self,master):
    master.minsize(width=666, height=666)
    master.maxsize(width=666, height=666)

Will give your window a fixed width & height of 666 pixels.

Or, just using minsize

def __init__(self,master):
    master.minsize(width=666, height=666)

Will make sure your window is always at least 666 pixels large, but the user can still expand the window.

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

How to access the first property of a Javascript object?

This has been covered here before.

The concept of first does not apply to object properties, and the order of a for...in loop is not guaranteed by the specs, however in practice it is reliably FIFO except critically for chrome (bug report). Make your decisions accordingly.

Joining Spark dataframes on the key

One way

// join type can be inner, left, right, fullouter
val mergedDf = df1.join(df2, Seq("keyCol"), "inner")
// keyCol can be multiple column names seperated by comma
val mergedDf = df1.join(df2, Seq("keyCol1", "keyCol2"), "left")

Another way

import spark.implicits._ 
val mergedDf = df1.as("d1").join(df2.as("d2"), ($"d1.colName" === $"d2.colName"))
// to select specific columns as output
val mergedDf = df1.as("d1").join(df2.as("d2"), ($"d1.colName" === $"d2.colName")).select($"d1.*", $"d2.anotherColName")

How to add an Android Studio project to GitHub

If you are using the latest version of Android studio. then you don't need to install additional software for Git other than GIT itself - https://git-scm.com/downloads

Steps

  1. Create an account on Github - https://github.com/join
  2. Install Git
  3. Open your working project in Android studio
  4. GoTo - File -> Settings -> Version Controll -> GitHub
  5. Enter Login and Password which you have created just on Git Account and click on test
  6. Once all credentials are true - it shows Success message. o.w Invalid Cred.
  7. Now click on VCS in android studio menu bar
  8. Select Import into Version Control -> Share Project on GitHub
  9. The popup dialog will occure contains all your files with check mark, do ok or commit all
  10. At next time whenever you want to push your project just click on VCS - > Commit Changes -> Commmit and Push.

That's it. You can find your project on your github now

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

Best way to change font colour halfway through paragraph?

<span> will allow you to style text, but it adds no semantic content.

As you're emphasizing some text, it sounds like you'd be better served by wrapping the text in <em></em> and using CSS to change the color of the <em> element. For example:

CSS

.description {
  color: #fff;
}

.description em {
  color: #ffa500;
}

Markup

<p class="description">Lorem ipsum dolor sit amet, consectetur 
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat 
massa, <em>eget vulputate tellus fermentum.</em></p>

In fact, I'd go to great pains to avoid the <span> element, as it's completely meaningless to everything that doesn't render your style sheet (bots, screen readers, luddites who disable styles, parsers, etc.) or renders it in unexpected ways (personal style sheets). In many ways, it's no better than using the <font> element.

_x000D_
_x000D_
.description {_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.description em {_x000D_
  color: #ffa500;_x000D_
}
_x000D_
<p class="description">Lorem ipsum dolor sit amet, consectetur _x000D_
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat _x000D_
massa, <em>eget vulputate tellus fermentum.</em></p>
_x000D_
_x000D_
_x000D_

git: can't push (unpacker error) related to permission issues

For me, this error occurred when I was out of space on my remote.

I just needed to read the rest of the error message:

error: file write error (No space left on device)
fatal: unable to write sha1 file
error: unpack failed: unpack-objects abnormal exit

MVC 3 file upload and model binding

For multiple files; note the newer "multiple" attribute for input:

Form:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    <label for="files">Filename:</label>
    <input type="file" name="files" multiple="true" id="files" />
    <input type="submit"  />
}

Controller:

[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
    return View();
}

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

I use the xcopy command with the /L option to get the file names. So if you want to get either a directory or all the files in the subdirectory you could do something like this:

for /f "delims=" %%a IN ('xcopy "D:\*.pdf" c:\ /l') do echo %%a

I just use the c:\ as the destination because it always exists on windows systems and it is not copying so it does not matter. if you want the subdirectories too just use /s option on the end. You can also use the other switches of xcopy if you need them for other reasons.

How to pass a variable to the SelectCommand of a SqlDataSource?

You need to define a valid type of SelectParameter. This MSDN article describes the various types and how to use them.

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

Grep only the first match and stop

A single liner, using find:

find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit

Is it possible to modify a string of char in C?

All are good answers explaining why you cannot modify string literals because they are placed in read-only memory. However, when push comes to shove, there is a way to do this. Check out this example:

#include <sys/mman.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int take_me_back_to_DOS_times(const void *ptr, size_t len);

int main()
{
    const *data = "Bender is always sober.";
    printf("Before: %s\n", data);
    if (take_me_back_to_DOS_times(data, sizeof(data)) != 0)
        perror("Time machine appears to be broken!");
    memcpy((char *)data + 17, "drunk!", 6);
    printf("After: %s\n", data);

    return 0;
}

int take_me_back_to_DOS_times(const void *ptr, size_t len)
{
    int pagesize;
    unsigned long long pg_off;
    void *page;

    pagesize = sysconf(_SC_PAGE_SIZE);
    if (pagesize < 0)
        return -1;
    pg_off = (unsigned long long)ptr % (unsigned long long)pagesize;
    page = ((char *)ptr - pg_off);
    if (mprotect(page, len + pg_off, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
        return -1;
    return 0;
}

I have written this as part of my somewhat deeper thoughts on const-correctness, which you might find interesting (I hope :)).

Hope it helps. Good Luck!

How to get current timestamp in milliseconds since 1970 just the way Java gets

If using gettimeofday you have to cast to long long otherwise you will get overflows and thus not the real number of milliseconds since the epoch: long int msint = tp.tv_sec * 1000 + tp.tv_usec / 1000; will give you a number like 767990892 which is round 8 days after the epoch ;-).

int main(int argc, char* argv[])
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
    std::cout << mslong << std::endl;
}

Selecting rows where remainder (modulo) is 1 after division by 2?

MySQL, SQL Server, PostgreSQL, SQLite support using the percent sign as the modulus:

WHERE column % 2 = 1

For Oracle, you have to use the MOD function:

WHERE MOD(column, 2) = 1

Moment.js - two dates difference in number of days

const FindDate = (date, allDate) => {
        
    // moment().diff only works on moment(). Make sure both date and elements in allDate array are in moment format
    let nearestDate = -1; 
    
    allDate.some(d => {
        const currentDate = moment(d)
        const difference = currentDate.diff(d); // Or d.diff(date) depending on what you're trying to find
        if(difference >= 0){
            nearestDate = d
        }
    });
    
    console.log(nearestDate)
}

How to strip HTML tags from string in JavaScript?

I know this question has an accepted answer, but I feel that it doesn't work in all cases.

For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):

http://phpjs.org/functions/strip_tags:535

It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script /> tag above.

Ruby combining an array into one string

While a bit more cryptic than join, you can also multiply the array by a string.

@arr * " "

How can I pass a username/password in the header to a SOAP WCF Service

Suppose you have service reference of the name localhost in your web.config so you can go as follows

localhost.Service objWebService = newlocalhost.Service();
localhost.AuthSoapHd objAuthSoapHeader = newlocalhost.AuthSoapHd();
string strUsrName =ConfigurationManager.AppSettings["UserName"];
string strPassword =ConfigurationManager.AppSettings["Password"];

objAuthSoapHeader.strUserName = strUsrName;
objAuthSoapHeader.strPassword = strPassword;

objWebService.AuthSoapHdValue =objAuthSoapHeader;
string str = objWebService.HelloWorld();

Response.Write(str);

Unsupported Media Type in postman

Thanks for all Contributions;

that is happening with me in XML; I just Change application/XML to be text/XML which solve my Problem

Android: Pass data(extras) to a fragment

great answer by @Rarw. Try using a bundle to pass information from one fragment to another

What is PostgreSQL equivalent of SYSDATE from Oracle?

The following functions are available to obtain the current date and/or time in PostgreSQL:

CURRENT_TIME

CURRENT_DATE

CURRENT_TIMESTAMP

Example

SELECT CURRENT_TIME;
08:05:18.864750+05:30

SELECT CURRENT_DATE;
2020-05-14

SELECT CURRENT_TIMESTAMP;
2020-05-14 08:04:51.290498+05:30

postgresql docs

How to store a list in a column of a database table

I'd just store it as CSV, if it's simple values then it should be all you need (XML is very verbose and serializing to/from it would probably be overkill but that would be an option as well).

Here's a good answer for how to pull out CSVs with LINQ.

@class vs. #import

Think of @class as telling the compiler "trust me, this exists".

Think of #import as copy-paste.

You want to minimize the number of imports you have for a number of reasons. Without any research, the first thing that comes to mind is it reduces compile time.

Notice that when you inherit from a class, you can't simply use a forward declaration. You need to import the file, so that the class you're declaring knows how it's defined.

Setting up maven dependency for SQL Server

I believe you are looking for the Microsoft SQL Server JDBC driver: http://msdn.microsoft.com/en-us/sqlserver/aa937724

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

Efficient way to apply multiple filters to pandas DataFrame or Series

e can also select rows based on values of a column that are not in a list or any iterable. We will create boolean variable just like before, but now we will negate the boolean variable by placing ~ in the front.

For example

list = [1, 0]
df[df.col1.isin(list)]

How to implement a confirmation (yes/no) DialogPreference?

Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.

Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).

Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).

You can then add it to your preferences.xml like any other Preference. Example:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />

Which looks like this:

screenshot

Using Pairs or 2-tuples in Java

Android Tuple Utils

This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.

java.lang.UnsupportedClassVersionError

This was a fresh linux Mint xfce machine

I have been battling this for a about a week. I'm trying to learn Java on Netbeans IDE and so naturally I get the combo file straight from Oracle. Which is a package of the JDK and the Netbeans IDE together in a tar file located here.

located http://www.oracle.com/technetwork/java/javase/downloads/index.html file name JDK 8u25 with NetBeans 8.0.1

after installing them (or so I thought) I would make/compile a simple program like "hello world" and that would spit out a jar file that you would be able to run in a terminal. Keep in mind that the program ran in the Netbeans IDE.

I would end up with this error: java.lang.UnsupportedClassVersionError:

Even though I ran the file from oracle website I still had the old version of the Java runtime which was not compatible to run my jar file which was compiled with the new java runtime.

After messing with stuff that was mostly over my head from setting Paths to editing .bashrc with no remedy.

I came across a solution that was easy enough for even me. I have come across something that auto installs java and configures it on your system and it works with the latest 1.8.*

One of the steps is adding a PPA wasn't sure about this at first but seems ok as it has worked for me


sudo add-apt-repository ppa:webupd8team/java

sudo apt-get update

sudo apt-get install oracle-java8-installer


domenic@domenic-AO532h ~ $ java -version java version "1.8.0_25" Java(TM) SE Runtime Environment (build 1.8.0_25-b17) Java HotSpot(TM) Server VM (build 25.25-b02, mixed mode)

I think it also configures the browser java as well.

I hope this helps others.

JavaScript Editor Plugin for Eclipse

Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.

How to compile and run a C/C++ program on the Android system

if you have installed NDK succesfully then start with it sample application

http://developer.android.com/sdk/ndk/overview.html#samples

if you are interested another ways of this then may this will help

http://shareprogrammingtips.blogspot.com/2018/07/cross-compile-cc-based-programs-and-run.html

I also want to know is it possible to push the compiled binary into android device or AVD and run using the terminal of the android device or AVD?

here you can see NestedVM

NestedVM provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes.


Example: Cross compile Hello world C program and run it on android

Including a css file in a blade template?

<link rel="stylesheet" href="{{ URL::asset('css/styles.css') }}">

It will search for the file in your project public folder

Detect page change on DataTable

In my case, the 'page.dt' event did not do the trick.

I used 'draw.dt' event instead, and it works!, some code:

$(document).on('draw.dt', function () {
    //Do something
});

'Draw.dt' event is fired everytime the datatable page change by searching, ordering or page changing.

/***** Aditional Info *****/

There are some diferences in the way we can declare the event listener. You can asign it to the 'document' or to a 'html object'. The 'document' listeners will always exist in the page and the 'html object' listener will exist only if the object exist in the DOM in the moment of the declaration. Some code:

//Document event listener

$(document).on('draw.dt', function () {
    //This will also work with objects loaded by ajax calls
});

//HTML object event listener

$("#some-id").on('draw.dt', function () {
    //This will work with existing objects only
});

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

I have encountered similar mistakes, and later found that my password is wrong.

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

What does 'low in coupling and high in cohesion' mean

I think you have red so many definitions but in the case you still have doubts or In case you are new to programming and want to go deep into this then I will suggest you to watch this video, https://youtu.be/HpJTGW9AwX0 It's just reference to get more info about polymorphism... Hope you get better understanding with this

Is Java's assertEquals method reliable?

You should always use .equals() when comparing Strings in Java.

JUnit calls the .equals() method to determine equality in the method assertEquals(Object o1, Object o2).

So, you are definitely safe using assertEquals(string1, string2). (Because Strings are Objects)

Here is a link to a great Stackoverflow question regarding some of the differences between == and .equals().

What is Gradle in Android Studio?

In Android Studio, Gradle is a custom build tool used to build android packages (apk files) by managing dependencies and providing custom build logic.

APK file (Android Application package) is a specially formatted zip file which contains

  • Byte code
  • Resources (images, UI, xml etc)
  • Manifest file

An apk file gets signed and pushed to the device using ADB(Android Debug Bridge) where it gets executed.

Spark - repartition() vs coalesce()

To all the great answers I would like to add that repartition is one the best option to take advantage of data parallelization. While coalesce gives a cheap option to reduce the partitions and it is very useful when writing data to HDFS or some other sink to take advantage of big writes.

I have found this useful when writing data in parquet format to get full advantage.

In Go's http package, how do I get the query string on a POST request?

Here's a simple, working example:

package main

import (
    "io"
    "net/http"
)
func queryParamDisplayHandler(res http.ResponseWriter, req *http.Request) {
    io.WriteString(res, "name: "+req.FormValue("name"))
    io.WriteString(res, "\nphone: "+req.FormValue("phone"))
}

func main() {
    http.HandleFunc("/example", func(res http.ResponseWriter, req *http.Request) {
        queryParamDisplayHandler(res, req)
    })
    println("Enter this in your browser:  http://localhost:8080/example?name=jenny&phone=867-5309")
    http.ListenAndServe(":8080", nil)
}

enter image description here

python replace single backslash with double backslash

Use escape characters: "full\\path\\here", "\\" and "\\\\"

Difference between / and /* in servlet mapping url pattern

<url-pattern>/*</url-pattern>

The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().

<url-pattern>/</url-pattern>

The / doesn't override any other servlet. It only replaces the servletcontainer's builtin default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's builtin default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's builtin JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.

<url-pattern></url-pattern>

Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.

Front Controller

In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a builtin static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?

Write HTML string in JSON

in json everything is string between double quote ", so you need escape " if it happen in value (only in direct writing) use backslash \

and everything in json file wrapped in {} change your json to

_x000D_
_x000D_
{_x000D_
  [_x000D_
    {_x000D_
      "id": "services.html",_x000D_
      "img": "img/SolutionInnerbananer.jpg",_x000D_
      "html": "<h2 class=\"fg-white\">AboutUs</h2><p class=\"fg-white\">developing and supporting complex IT solutions.Touching millions of lives world wide by bringing in innovative technology</p>"_x000D_
    }_x000D_
  ]_x000D_
}
_x000D_
_x000D_
_x000D_

how to use font awesome in own css?

Try this way. In your css file change font-family: FontAwesome into font-family: "FontAwesome"; or font-family: 'FontAwesome';. I've solved the same problem using this method.

Best database field type for a URL

VARCHAR(512) (or similar) should be sufficient. However, since you don't really know the maximum length of the URLs in question, I might just go direct to TEXT. The danger with this is of course loss of efficiency due to CLOBs being far slower than a simple string datatype like VARCHAR.

Ruby function to remove all white spaces?

Related answer:

"   clean up my edges    ".strip

returns

"clean up my edges"

Android Device not recognized by adb

Check that the USB cable is indeed capable of transferring data. Some cheaper ones, especially those meant to charge non-phone/computer devices, might only support charging.

You can verify this by checking if the device shows up as mountable file system. In Linux, you can also use the command lsusb to check if it's being detected.

How to create an array of object literals in a loop?

In the same idea of Nick Riggs but I create a constructor, and a push a new object in the array by using it. It avoid the repetition of the keys of the class:

var arr = [];
var columnDefs = function(key, sortable, resizeable){
    this.key = key; 
    this.sortable = sortable; 
    this.resizeable = resizeable;
    };

for (var i = 0; i < len; i++) {
    arr.push((new columnDefs(oFullResponse.results[i].label,true,true)));
}

How to limit text width

<style>
     p{
         width:     70%
         word-wrap: break-word;
     }
</style>

This wasn't working in my case. It worked fine after adding following style.

<style>
     p{
        width:     70%
        word-break: break-all;
     }
</style>

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Android simple alert dialog

You would simply need to do this in your onClick:

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
alertDialog.show();

I don't know from where you saw that you need DialogFragment for simply showing an alert.

Hope this helps.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

You're doing a few things wrong.

  1. First, browserHistory isn't a thing in V4, so you can remove that.

  2. Second, you're importing everything from react-router, it should be react-router-dom.

  3. Third, react-router-dom doesn't export a Router, instead, it exports a BrowserRouter so you need to import { BrowserRouter as Router } from 'react-router-dom.

Looks like you just took your V3 app and expected it to work with v4, which isn't a great idea.

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

The download from java.com which installs in /Library/Internet Plug-Ins is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home which you can then add to Eclipse via Preferences -> Java -> Installed JREs.

Handling the window closing event with WPF / MVVM Light Toolkit

We use AttachedCommandBehavior for this. You can attach any event to a command on your view model avoiding any code behind.

We use it throughout our solution and have almost zero code behind

http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/

Return datetime object of previous month

I Used the following code to go back n Months from a specific Date:

your_date =  datetime.strptime(input_date, "%Y-%m-%d")  #to convert date(2016-01-01) to timestamp
start_date=your_date    #start from current date

#Calculate Month
for i in range(0,n):    #n = number of months you need to go back
    start_date=start_date.replace(day=1)    #1st day of current month
    start_date=start_date-timedelta(days=1) #last day of previous month

#Calculate Day
if(start_date.day>your_date.day):   
    start_date=start_date.replace(day=your_date.day)            

print start_date

For eg: input date = 28/12/2015 Calculate 6 months previous date.

I) CALCULATE MONTH: This step will give you the start_date as 30/06/2015.
Note that after the calculate month step you will get the last day of the required month.

II)CALCULATE DAY: Condition if(start_date.day>your_date.day) checks whether the day from input_date is present in the required month. This handles condition where input date is 31(or 30) and the required month has less than 31(or 30 in case of feb) days. It handles leap year case as well(For Feb). After this step you will get result as 28/06/2015

If this condition is not satisfied, the start_date remains the last date of the previous month. So if you give 31/12/2015 as input date and want 6 months previous date, it will give you 30/06/2015

Adding hours to JavaScript Date object?

Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.

No internet on Android emulator - why and how to fix?

I have searched long and hard for an answer to this question. From what I gather Google did that on purpose once people used the internet connection to add spam comments to the market. However, I did find a guy who had done it and was willing to share the required images. The linked AVD runs(for me) both the market and browser internet.

NOTE: It looks like it's just going to fix the market. But the market won't run without internet, so if the market is fixed, the browser internet will work too. I downloaded the linked files myself and it showed the internet in the browser perfectly.

Entity Framework : How do you refresh the model when the db changes?

I've been working on a project, not too large, that incorporates Entity Framework, about a dozen tables, and about 15 stored procs and functions. After weeks of development, attempting to refresh my tables and stored procs has yielded mixed results as far as successfully updating the model. Sometimes the changes are effective, most times they are not. Simple column changes (changing order, adding, removing, or renaming) sometimes works, most times does not. Visual Studio seems to have more problems with refreshing than just adding new. It also exhibits more problems with stored proc changes not being reflected, especially when columns are added or deleted or renamed. I have not detected any consistent behavior so i can't say "This type of change will always be updated and this type of change will not".

End result, if you want 100% effective solution, delete the EDMX file from the project, "Add new" item to project (ADO.NET Entity Data Model), and make sure you use the same name for the Model Name. This works every time.

What's the difference between "Layers" and "Tiers"?

When you talk about presentation, service, data, network layer, you are talking about layers. When you "deploy them separately", you talk about tiers.

Tiers is all about deployment. Take it this way: We have an application which has a frontend created in Angular, it has a backend as MongoDB and a middle layer which interacts between the frontend and the backend. So, when this frontend application, database application, and the middle layer is all deployed separately, we say it's a 3 tier application.

Benefit: If we need to scale our backend in the future, we only need to scale the backend independently and there's no need to scale up the frontend.

Rails ActiveRecord date between

I would personally created a scope to make it more readable and re-usable:

In you Comment.rb, you can define a scope:

scope :created_between, lambda {|start_date, end_date| where("created_at >= ? AND created_at <= ?", start_date, end_date )}

Then to query created between:

@comment.created_between(1.year.ago, Time.now)

Hope it helps.

Address already in use: JVM_Bind java

The quick answer on how to prevent it is that you most likely need to stop JBoss before starting it again.

You should be able to call the "Terminate" button in the Console view to shutdown the server.

Hex transparency in colors

Color hexadecimal notation is like following: #AARRGGBB

  • A : alpha
  • R : red
  • G : green
  • B : blue

You should first look at how hexadecimal works. You can write at most FF.

adding noise to a signal in python

For those trying to make the connection between SNR and a normal random variable generated by numpy:

[1] SNR ratio, where it's important to keep in mind that P is average power.

Or in dB:
[2] SNR dB2

In this case, we already have a signal and we want to generate noise to give us a desired SNR.

While noise can come in different flavors depending on what you are modeling, a good start (especially for this radio telescope example) is Additive White Gaussian Noise (AWGN). As stated in the previous answers, to model AWGN you need to add a zero-mean gaussian random variable to your original signal. The variance of that random variable will affect the average noise power.

For a Gaussian random variable X, the average power Ep, also known as the second moment, is
[3] Ex

So for white noise, Ex and the average power is then equal to the variance Ex.

When modeling this in python, you can either
1. Calculate variance based on a desired SNR and a set of existing measurements, which would work if you expect your measurements to have fairly consistent amplitude values.
2. Alternatively, you could set noise power to a known level to match something like receiver noise. Receiver noise could be measured by pointing the telescope into free space and calculating average power.

Either way, it's important to make sure that you add noise to your signal and take averages in the linear space and not in dB units.

Here's some code to generate a signal and plot voltage, power in Watts, and power in dB:

# Signal Generation
# matplotlib inline

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(1, 100, 1000)
x_volts = 10*np.sin(t/(2*np.pi))
plt.subplot(3,1,1)
plt.plot(t, x_volts)
plt.title('Signal')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()

x_watts = x_volts ** 2
plt.subplot(3,1,2)
plt.plot(t, x_watts)
plt.title('Signal Power')
plt.ylabel('Power (W)')
plt.xlabel('Time (s)')
plt.show()

x_db = 10 * np.log10(x_watts)
plt.subplot(3,1,3)
plt.plot(t, x_db)
plt.title('Signal Power in dB')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()

Generated Signal

Here's an example for adding AWGN based on a desired SNR:

# Adding noise using target SNR

# Set a target SNR
target_snr_db = 20
# Calculate signal power and convert to dB 
sig_avg_watts = np.mean(x_watts)
sig_avg_db = 10 * np.log10(sig_avg_watts)
# Calculate noise according to [2] then convert to watts
noise_avg_db = sig_avg_db - target_snr_db
noise_avg_watts = 10 ** (noise_avg_db / 10)
# Generate an sample of white noise
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(noise_avg_watts), len(x_watts))
# Noise up the original signal
y_volts = x_volts + noise_volts

# Plot signal with noise
plt.subplot(2,1,1)
plt.plot(t, y_volts)
plt.title('Signal with noise')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
# Plot in dB
y_watts = y_volts ** 2
y_db = 10 * np.log10(y_watts)
plt.subplot(2,1,2)
plt.plot(t, 10* np.log10(y_volts**2))
plt.title('Signal with noise (dB)')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()

Signal with target SNR

And here's an example for adding AWGN based on a known noise power:

# Adding noise using a target noise power

# Set a target channel noise power to something very noisy
target_noise_db = 10

# Convert to linear Watt units
target_noise_watts = 10 ** (target_noise_db / 10)

# Generate noise samples
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(target_noise_watts), len(x_watts))

# Noise up the original signal (again) and plot
y_volts = x_volts + noise_volts

# Plot signal with noise
plt.subplot(2,1,1)
plt.plot(t, y_volts)
plt.title('Signal with noise')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
# Plot in dB
y_watts = y_volts ** 2
y_db = 10 * np.log10(y_watts)
plt.subplot(2,1,2)
plt.plot(t, 10* np.log10(y_volts**2))
plt.title('Signal with noise')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()

Signal with target noise level

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

Created Button Click Event c#

    public MainWindow()
    {
        // This button needs to exist on your form.
        myButton.Click += myButton_Click;
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Message here");
        this.Close();
    }

Programmatically change UITextField Keyboard type

_textField .keyboardType = UIKeyboardTypeAlphabet;
_textField .keyboardType = UIKeyboardTypeASCIICapable;
_textField .keyboardType = UIKeyboardTypeDecimalPad;
_textField .keyboardType = UIKeyboardTypeDefault;
_textField .keyboardType = UIKeyboardTypeEmailAddress;
_textField .keyboardType = UIKeyboardTypeNamePhonePad;
_textField .keyboardType = UIKeyboardTypeNumberPad;
_textField .keyboardType = UIKeyboardTypeNumbersAndPunctuation;
_textField .keyboardType = UIKeyboardTypePhonePad;
_textField .keyboardType = UIKeyboardTypeTwitter;
_textField .keyboardType = UIKeyboardTypeURL;
_textField .keyboardType = UIKeyboardTypeWebSearch;

Looping through a DataTable

foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          Console.WriteLine(row[col.ColumnName].ToString());           
     }
} 

Fit website background image to screen size

You can do it like what I did with my website:

background-repeat: no-repeat;

background-size: cover;

How to display count of notifications in app launcher icon

It works in samsung touchwiz launcher

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {

    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}

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

while using Google App Engine, i had this problem. For some reason i did following since then Google App Engine was never starting.

$ echo '' > /tmp/appengine.apprtc.root/*.db

To fix it i required to do manually:

$ sqlite3 datastore.db
sqlite> begin immediate;
<press CTRL+Z>
$ cp datastore.db logs.db

And then run the Google App Engine with flag:

$ dev_appserver.py --clear_datastore --clear_search_index

after that it finally worked.

Create Table from View

SQL Server does not support CREATE TABLE AS SELECT.

Use this:

SELECT  *
INTO    A
FROM    myview

or

SELECT  TOP 10
        *
INTO    A
FROM    myview
ORDER BY
        id

How can I see function arguments in IPython Notebook Server 3?

Shift-Tab works for me to view the dcoumentation