Programs & Examples On #Python bindings

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

php var_dump() vs print_r()

The var_dump function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.

The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.

Example:

$obj = (object) array('qualitypoint', 'technologies', 'India');

var_dump($obj) will display below output in the screen.

object(stdClass)#1 (3) {
 [0]=> string(12) "qualitypoint"
 [1]=> string(12) "technologies"
 [2]=> string(5) "India"
}

And, print_r($obj) will display below output in the screen.

stdClass Object ( 
 [0] => qualitypoint
 [1] => technologies
 [2] => India
)

More Info

Setting a divs background image to fit its size?

You can achieve this with the background-size property, which is now supported by most browsers.

To scale the background image to fit inside the div:

background-size: contain;

To scale the background image to cover the whole div:

background-size: cover;

Android: I lost my android key store, what should I do?

I want to refine this a little bit because down-votes indicate to me that people don't understand that these suggestions are like "last hope" approach for someone who got into the state described in the question.

Check your console input history and/or ant scripts you have been using if you have them. Keep in mind that the console history will not be saved if you were promoted for password but if you entered it within for example signing command you can find it.

You mentioned you have a zip with a password in which your certificate file is stored, you could try just brute force opening that with many tools available. People will say "Yea but what if you used strong password, you should bla,bla,bla..." Unfortunately in that case tough-luck. But people are people and they sometimes use simple passwords. For you any tool that can provide dictionary attacks in which you can enter your own words and set them to some passwords you suspect might help you. Also if password is short enough with today CPUs even regular brute force guessing might work since your zip file does not have any limitation on number of guesses so you will not get blocked as if you tried to brute force some account on a website.

Safari 3rd party cookie iframe trick no longer working?

I have also been suffering from this problem, but finally got the solution, Initially directly the load the iframe url in browser like small popup then only access the session values inside the iframe.

Sending email from Azure

I know this is an old post but I've just signed up for Azure and I get 25,000 emails a month for free via SendGrid. These instructions are excellent, I was up and running in minutes:

How to Send Email Using SendGrid with Azure

Azure customers can unlock 25,000 free emails each month.

Eliminating NAs from a ggplot

You can use the function subset inside ggplot2. Try this

library(ggplot2)

data("iris")
iris$Sepal.Length[5:10] <- NA # create some NAs for this example

ggplot(data=subset(iris, !is.na(Sepal.Length)), aes(x=Sepal.Length)) + 
geom_bar(stat="bin")

Install a Nuget package in Visual Studio Code

Example for .csproj file

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
    <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="7.0.7-m61" />
  </ItemGroup>

Just get package name and version number from NuGet and add to .csproj then save. You will be prompted to run restore that will import new packages.

PHP/MySQL insert row then get 'id'

Another possible answer will be:

When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.

By this method, you don't have to worry about the id, it'll be made automatically.

For example (taken from w3schools )

CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)

Hope this will be helpful for someone.

Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

How do you format code on save in VS Code

If you would like to auto format on save just with Javascript source, add this one into Users Setting (press Cmd, or Ctrl,):

"[javascript]": { "editor.formatOnSave": true }

How to set value to variable using 'execute' in t-sql?

You can use output parameters with sp_executesql.

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int 
DECLARE @SQL nvarchar(max) = N'SELECT TOP 1 @siteId = Id FROM ' + quotename(@dbName) + N'..myTbl'
exec sp_executesql @SQL, N'@siteId int out', @siteId out
select @siteId

Figuring out whether a number is a Double in Java

Try this:

if (items.elementAt(1) instanceof Double) {
   sum.add( i, items.elementAt(1));
}

How to create a sleep/delay in nodejs that is Blocking?

It's pretty trivial to implement with native addon, so someone did that: https://github.com/ErikDubbelboer/node-sleep.git

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/

Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.

 import numpy as np
 s = pd.Series(['apple', np.nan, 'banana'])
 s.apply(lambda x: x!=x)
 out[252]
 0    False
 1     True
 2    False
 dtype: bool

How to automatically select all text on focus in WPF TextBox?

Taken from here:

Register global event handler in App.xaml.cs file:

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox),TextBox.GotFocusEvent,
    new RoutedEventHandler(TextBox_GotFocus));

    base.OnStartup(e);
}

Then the handler is as simple as:

private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    (sender as TextBox).SelectAll();
}

What is attr_accessor in Ruby?

It is just a method that defines getter and setter methods for instance variables. An example implementation would be:

def self.attr_accessor(*names)
  names.each do |name|
    define_method(name) {instance_variable_get("@#{name}")} # This is the getter
    define_method("#{name}=") {|arg| instance_variable_set("@#{name}", arg)} # This is the setter
  end
end

How to check if a std::string is set or not?

The default constructor for std::string always returns an object that is set to a null string.

Modify XML existing content in C#

The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.

Just update the node you have selected and .Save() that XmlDocument.

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

How do I use extern to share variables between source files?

First off, the extern keyword is not used for defining a variable; rather it is used for declaring a variable. I can say extern is a storage class, not a data type.

extern is used to let other C files or external components know this variable is already defined somewhere. Example: if you are building a library, no need to define global variable mandatorily somewhere in library itself. The library will be compiled directly, but while linking the file, it checks for the definition.

click() event is calling twice in jquery

I had the same problem, but you can try changing this code

$("#link_button")
.button()
.click(function () {
   $("#attachmentForm").slideToggle("fast");
});

to this:

$("#link_button").button();
$("#link_button").unbind("click").click(function () {
   $("#attachmentForm").slideToggle("fast");
});

For me, this code solved the problem. But take care not to accidentally include your script twice in your HTML page. I think that if you are doing these two things correctly, your code will work correctly. Thanks

How do I concatenate two strings in Java?

So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.

Different ways by which Strings could be concatenated in Java

  1. By using + operator (20 + "")
  2. By using concat method in String class
  3. Using StringBuffer
  4. By using StringBuilder

Method 1:

This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.

String temp = "" + 200 + 'B';

//This is translated internally into,

new StringBuilder().append( "" ).append( 200 ).append('B').toString();

Method 2:

This is the inner concat method's implementation

_x000D_
_x000D_
public String concat(String str) {_x000D_
    int olen = str.length();_x000D_
    if (olen == 0) {_x000D_
        return this;_x000D_
    }_x000D_
    if (coder() == str.coder()) {_x000D_
        byte[] val = this.value;_x000D_
        byte[] oval = str.value;_x000D_
        int len = val.length + oval.length;_x000D_
        byte[] buf = Arrays.copyOf(val, len);_x000D_
        System.arraycopy(oval, 0, buf, val.length, oval.length);_x000D_
        return new String(buf, coder);_x000D_
    }_x000D_
    int len = length();_x000D_
    byte[] buf = StringUTF16.newBytesFor(len + olen);_x000D_
    getBytes(buf, 0, UTF16);_x000D_
    str.getBytes(buf, len, UTF16);_x000D_
    return new String(buf, UTF16);_x000D_
}
_x000D_
_x000D_
_x000D_

This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.

Method 3:

This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.

_x000D_
_x000D_
    private int newCapacity(int minCapacity) {_x000D_
        // overflow-conscious code_x000D_
        int oldCapacity = value.length >> coder;_x000D_
        int newCapacity = (oldCapacity << 1) + 2;_x000D_
        if (newCapacity - minCapacity < 0) {_x000D_
            newCapacity = minCapacity;_x000D_
        }_x000D_
        int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;_x000D_
        return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)_x000D_
            ? hugeCapacity(minCapacity)_x000D_
            : newCapacity;_x000D_
    }_x000D_
_x000D_
    private int hugeCapacity(int minCapacity) {_x000D_
        int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;_x000D_
        int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;_x000D_
        if (UNSAFE_BOUND - minCapacity < 0) { // overflow_x000D_
            throw new OutOfMemoryError();_x000D_
        }_x000D_
        return (minCapacity > SAFE_BOUND)_x000D_
            ? minCapacity : SAFE_BOUND;_x000D_
    }
_x000D_
_x000D_
_x000D_

Method 4

StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.

In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.

How to set the locale inside a Debian/Ubuntu Docker container?

I used this (after RUN apt-get install -y python3):

RUN apt-get install -y locales
RUN apt-get install -y language-pack-en
ENV LANG en_US.UTF-8 
ENV LANGUAGE en_US:en 
ENV LC_ALL en_US.UTF-8
RUN python3 -c "print('UTF8 works nice! ')"

And it prints UTF8 works nice! correctly.

Encode URL in JavaScript?

What is URL encoding:

A URL should be encoded when there are special characters located inside the URL. For example:

_x000D_
_x000D_
console.log(encodeURIComponent('?notEncoded=&+'));
_x000D_
_x000D_
_x000D_

We can observe in this example that all characters except the string notEncoded are encoded with % signs. URL encoding is also known as percentage encoding because it escapes all special characters with a %. Then after this % sign every special character has a unique code

Why do we need URL encoding:

Certain characters have a special value in a URL string. For example, the ? character denotes the beginning of a query string. In order to succesfully locate a resource on the web, it is necesarry to distinguish between when a character is meant as a part of string or part of the url structure.

How can we achieve URL encoding in JS:

JS offers a bunch of build in utility function which we can use to easily encode URL's. These are two convenient options:

  1. encodeURIComponent(): Takes a component of a URI as an argument and returns the encoded URI string.
  2. encodeURI(): Takes a URI as an argument and returns the encoded URI string.

Example and caveats:

Be aware of not passing in the whole URL (including scheme, e.g https://) into encodeURIComponent(). This can actually transform it into a not functional URL. For example:

_x000D_
_x000D_
// for a whole URI don't use encodeURIComponent it will transform_x000D_
// the / characters and the URL won't fucntion properly_x000D_
console.log(encodeURIComponent("http://www.random.com/specials&char.html"));_x000D_
_x000D_
// instead use encodeURI for whole URL's_x000D_
console.log(encodeURI("http://www.random.com/specials&char.html"));
_x000D_
_x000D_
_x000D_

We can observe f we put the whole URL in encodeURIComponent that the foward slashes (/) are also converted to special characters. This will cause the URL to not function properly anymore.

Therefore (as the name implies) use:

  1. encodeURIComponent on a certain part of a URL which you want to encode.
  2. encodeURI on a whole URL which you want to encode.

java.net.SocketException: Software caused connection abort: recv failed

I too had this problem. My solution was:

sc.setSoLinger(true, 10);

COPY FROM A WEBSITE -->By using the setSoLinger() method, you can explicitly set a delay before a reset is sent, giving more time for data to be read or send.

Maybe it is not the answer to everybody but to some people.

What is mod_php?

mod_php means PHP, as an Apache module.

Basically, when loading mod_php as an Apache module, it allows Apache to interpret PHP files (those are interpreted by mod_php).


EDIT : There are (at least) two ways of running PHP, when working with Apache :

  • Using CGI : a PHP process is launched by Apache, and it is that PHP process that interprets PHP code -- not Apache itself
  • Using PHP as an Apache module (called mod_php) : the PHP interpreter is then kind of "embedded" inside the Apache process : there is no external PHP process -- which means that Apache and PHP can communicate better.


And re-edit, after the comment : using CGI or mod_php is up to you : it's only a matter of configuration of your webserver.

To know which way is currently used on your server, you can check the output of phpinfo() : there should be something indicating whether PHP is running via mod_php (or mod_php5), or via CGI.

You might also want to take a look at the php_sapi_name() function : it returns the type of interface between web server and PHP.


If you check in your Apache's configuration files, when using mod_php, there should be a LoadModule line looking like this :

LoadModule php5_module        modules/libphp5.so

(The file name, on the right, can be different -- on Windows, for example, it should be a .dll)

Change Image of ImageView programmatically in Android

You can use

val drawableCompat = ContextCompat.getDrawable(context, R.drawable.ic_emoticon_happy)

or in java java

Drawable drawableCompat = ContextCompat.getDrawable(getContext(), R.drawable.ic_emoticon_happy)

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

How to debug stored procedures with print statements?

Here is an example of print statement use. They should appear under the messages tab as a previous person indicated.

    Declare @TestVar int = 5;

    print 'this is a test message';
    print @TestVar;
    print 'test-' + Convert(varchar(50), @TestVar);

Print Messages

Reverse engineering from an APK file to a project

Yes, you can get your project back. Just rename the yourproject.apk file to yourproject.zip, and you will get all the files inside that ZIP file. We are changing the file extension from .apk to .zip. From that ZIP file, extract the classes.dex file and decompile it by following way.

First, you need a tool to extract all the (compiled) classes on the DEX to a JAR. There's one called dex2jar, which is made by a Chinese student.

Then, you can use JD-GUI to decompile the classes in the JAR to source code. The resulting source code should be quite readable, as dex2jar applies some optimizations.

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

Get index of a key/value pair in a C# dictionary based on the value

If searching for a value, you will have to loop through all the data. But to minimize code involved, you can use LINQ.

Example:

Given Dictionary defined as following:

Dictionary<Int32, String> dict;

You can use following code :

// Search for all keys with given value
Int32[] keys = dict.Where(kvp => kvp.Value.Equals("SomeValue")).Select(kvp => kvp.Key).ToArray();
        
// Search for first key with given value
Int32 key = dict.First(kvp => kvp.Value.Equals("SomeValue")).Key;

where is gacutil.exe?

You can use the version in Windows SDK but sometimes it might not be the same version of the .NET Framework your using, getting you the following error:

Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

In .NET 4.0 you'll need to search inside Microsoft SDK v8.0A, e.g.: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools (in my case I only have the 32 bit version installed by Visual Studio 2012).

How to write MySQL query where A contains ( "a" or "b" )

Two options:

  1. Use the LIKE keyword, along with percent signs in the string

    select * from table where field like '%a%' or field like '%b%'.
    

    (note: If your search string contains percent signs, you'll need to escape them)

  2. If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):

    See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Of these, using LIKE is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.

Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.

If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

I got the same error

Could not connect to the Magento WebService API: SOAP-ERROR: Parsing WSDL: Couldn't load from 'example.com/api/soap/?wsdl' : failed to load external entity "example.com/api/soap/?wsdl"

and my issue resolved once I update my Magento Root URL to

example.com/index.php/api/soap/?wsdl

Yes, I was missing index.php that causes the error.

What is the size of column of int(11) in mysql in bytes?

What is the size of column of int(11) in mysql in bytes?

(11) - this attribute of int data type has nothing to do with size of column. It is just the display width of the integer data type. From 11.1.4.5. Numeric Type Attributes:

MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type. For example, INT(4) specifies an INT with a display width of four digits.

Is there a cross-domain iframe height auto-resizer that works?

You have three alternatives:

1. Use iFrame-resizer

This is a simple library for keeping iFrames sized to their content. It uses the PostMessage and MutationObserver APIs, with fall backs for IE8-10. It also has options for the content page to request the containing iFrame is a certain size and can also close the iFrame when your done with it.

https://github.com/davidjbradshaw/iframe-resizer

2. Use Easy XDM (PostMessage + Flash combo)

Easy XDM uses a collection of tricks for enabling cross-domain communication between different windows in a number of browsers, and there are examples for using it for iframe resizing:

http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/

http://kinsey.no/blog/index.php/2010/02/19/resizing-iframes-using-easyxdm/

Easy XDM works by using PostMessage on modern browsers and a Flash based solution as fallback for older browsers.

See also this thread on Stackoverflow (there are also others, this is a commonly asked question). Also, Facebook would seem to use a similar approach.

3. Communicate via a server

Another option would be to send the iframe height to your server and then poll from that server from the parent web page with JSONP (or use a long poll if possible).

Excel formula to display ONLY month and year?

There are a number of ways to go about this. One way would be to enter the date 8/1/2013 manually in the first cell (say A1 for example's sake) and then in B1 type the following formula (and then drag it across):

=DATE(YEAR(A1),MONTH(A1)+1,1)

Since you only want to see month and year, you can format accordingly using the different custom date formats available.

The format you're looking for is YY-Mmm.

avrdude: stk500v2_ReceiveMessage(): timeout

I've connected to USB port directly in my laptop and timeout issue has been resolved.

Previously tried by port replicator, but it did not even recognized arduino, thus I chosen wrong port - resulting in timeout message.

So make sure that it is visible by your OS.

Spring Boot - How to log all requests and responses with exceptions in single place?

If you dont mind trying Spring AOP, this is something I have been exploring for logging purposes and it works pretty well for me. It wont log requests that have not been defined and failed request attempts though.

Add these three dependencies

spring-aop, aspectjrt, aspectjweaver

Add this to your xml config file <aop:aspectj-autoproxy/>

Create an annotation which can be used as a pointcut

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface EnableLogging {
ActionType actionType();
}

Now annotate all your rest API methods which you want to log

@EnableLogging(actionType = ActionType.SOME_EMPLOYEE_ACTION)
@Override
public Response getEmployees(RequestDto req, final String param) {
...
}

Now on to the Aspect. component-scan the package which this class is in.

@Aspect
@Component
public class Aspects {

@AfterReturning(pointcut = "execution(@co.xyz.aspect.EnableLogging * *(..)) && @annotation(enableLogging) && args(reqArg, reqArg1,..)", returning = "result")
public void auditInfo(JoinPoint joinPoint, Object result, EnableLogging enableLogging, Object reqArg, String reqArg1) {

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();

    if (result instanceof Response) {
        Response responseObj = (Response) result;

    String requestUrl = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + request.getContextPath() + request.getRequestURI()
                + "?" + request.getQueryString();

String clientIp = request.getRemoteAddr();
String clientRequest = reqArg.toString();
int httpResponseStatus = responseObj.getStatus();
responseObj.getEntity();
// Can log whatever stuff from here in a single spot.
}


@AfterThrowing(pointcut = "execution(@co.xyz.aspect.EnableLogging * *(..)) && @annotation(enableLogging) && args(reqArg, reqArg1,..)", throwing="exception")
public void auditExceptionInfo(JoinPoint joinPoint, Throwable exception, EnableLogging enableLogging, Object reqArg, String reqArg1) {

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();

    String requestUrl = request.getScheme() + "://" + request.getServerName()
    + ":" + request.getServerPort() + request.getContextPath() + request.getRequestURI()
    + "?" + request.getQueryString();

    exception.getMessage();
    exception.getCause();
    exception.printStackTrace();
    exception.getLocalizedMessage();
    // Can log whatever exceptions, requests, etc from here in a single spot.
    }
}

@AfterReturning advice runs when a matched method execution returns normally.

@AfterThrowing advice runs when a matched method execution exits by throwing an exception.

If you want to read in detail read through this. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

IIS error, Unable to start debugging on the webserver

Check your web config, if there are problems, you may get this error. I had a HTTP to HTTPS redirect in the web config but the application was set to launch as http.

To fix (Local IIS):

  1. Configure a https binding for your application in IIS.
  2. Right click the web project then Properties > Web. Under Servers, set the URL to your https URL.

ROW_NUMBER() in MySQL

There is no funtion like rownum, row_num() in MySQL but the way around is like below:

select 
      @s:=@s+1 serial_no, 
      tbl.* 
from my_table tbl, (select @s:=0) as s;

Python: read all text file lines in loop

You can stop the 2-line separation in the output by using

    with open('t.ini') as f:
       for line in f:
           print line.strip()
           if 'str' in line:
              break

Where does the .gitignore file belong?

When in doubt just place it in the root of your repository. See https://help.github.com/articles/ignoring-files/ for more information.

Passing environment-dependent variables in webpack

Just another option, if you want to use only a cli interface, just use the define option of webpack. I add the following script in my package.json :

"build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"

So I just have to run npm run build-production.

Npm install failed with "cannot run in wd"

!~~ For Docker ~~!

@Alexander Mills answer - just to make it easier to find:

RUN npm set unsafe-perm true

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Building on Joan-Diego Rodriguez's routine with Jordi's approach and some of Jacek Kotowski's code - This function converts any table name for the active workbook into a usable address for SQL queries.

Note to MikeL: Addition of "[#All]" includes headings avoiding problems you reported.

Function getAddress(byVal sTableName as String) as String 

    With Range(sTableName & "[#All]")
        getAddress= "[" & .Parent.Name & "$" & .Address(False, False) & "]"
    End With

End Function

Styling every 3rd item of a list using CSS?

Yes, you can use what's known as :nth-child selectors.

In this case you would use:

li:nth-child(3n) {
// Styling for every third element here.
}

:nth-child(3n):

3(0) = 0
3(1) = 3
3(2) = 6
3(3) = 9
3(4) = 12

:nth-child() is compatible in Chrome, Firefox, and IE9+.

For a work around to use :nth-child() amongst other pseudo-classes/attribute selectors in IE6 through to IE8, see this link.

How to get IP address of running docker container

For my case, below worked on Mac:

I could not access container IPs directly on Mac. I need to use localhost with port forwarding, e.g. if the port is 8000, then http://localhost:8000

See https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds

The original answer was from: https://github.com/docker/for-mac/issues/2670#issuecomment-371249949

Jackson Vs. Gson

I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)

Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

How do we check if a pointer is NULL pointer?

I always think simply if(p != NULL){..} will do the job.

It will.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

Note about bug of MySQL Connector/C on macOS (my current version is 10.13.2), fix the mysql_config and reinstall mysqlclient or MySQL-python, here is the detail

How to add an object to an array

var years = [];
for (i= 2015;i<=2030;i=i+1)
{
years.push({operator : i})
}

here array years is having values like

years[0]={operator:2015}
years[1]={operator:2016}

it continues like this.

How to send emails from my Android application?

I've been using this since long time ago and it seems good, no non-email apps showing up. Just another way to send a send email intent:

Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of email");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:[email protected]")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);

Distinct by property of class with LINQ

You can use grouping, and get the first car from each group:

List<Car> distinct =
  cars
  .GroupBy(car => car.CarCode)
  .Select(g => g.First())
  .ToList();

Unioning two tables with different number of columns

for any extra column if there is no mapping then map it to null like the following SQL query

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2````

iOS change navigation bar title font and color

Swift:-

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name:"Love Nature", size: 40)!]

Proper way to initialize C++ structs

From what you've told us it does appear to be a false positive in valgrind. The new syntax with () should value-initialize the object, assuming it is POD.

Is it possible that some subpart of your struct isn't actually POD and that's preventing the expected initialization? Are you able to simplify your code into a postable example that still flags the valgrind error?

Alternately perhaps your compiler doesn't actually value-initialize POD structures.

In any case probably the simplest solution is to write constructor(s) as needed for the struct/subparts.

Simple Random Samples from a Sql database

In certain dialects like Microsoft SQL Server, PostgreSQL, and Oracle (but not MySQL or SQLite), you can do something like

select distinct top 10000 customer_id from nielsen.dbo.customer TABLESAMPLE (20000 rows) REPEATABLE (123);

The reason for not just doing (10000 rows) without the top is that the TABLESAMPLE logic gives you an extremely inexact number of rows (like sometimes 75% that, sometimes 1.25% times that), so you want to oversample and select the exact number you want. The REPEATABLE (123) is for providing a random seed.

How to change font in ipython notebook

I would also suggest that you explore the options offered by the jupyter themer. For more modest interface changes you may be satisfied with running the syntax:

jupyter-themer [-c COLOR, --color COLOR]
                      [-l LAYOUT, --layout LAYOUT]
                      [-t TYPOGRAPHY, --typography TYPOGRAPHY]

where the options offered by themer would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the .css files if the changes you want to apply are elaborate.

How to check if a service is running on Android?

You can use this (I didn't try this yet, but I hope this works):

if(startService(someIntent) != null) {
    Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
else {
    Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
}

The startService method returns a ComponentName object if there is an already running service. If not, null will be returned.

See public abstract ComponentName startService (Intent service).

This is not like checking I think, because it's starting the service, so you can add stopService(someIntent); under the code.

Know relationships between all the tables of database in SQL Server

select * from information_schema.REFERENTIAL_CONSTRAINTS where 
UNIQUE_CONSTRAINT_SCHEMA = 'TABLE_NAME' 

This will list the column with TABLE_NAME and REFERENCED_COLUMN_NAME.

jQuery - What are differences between $(document).ready and $(window).load?

The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.


$(document).ready(function(){

}) 

and

$(function(){

});

and

jQuery(document).ready(function(){

});

There are not difference between the above 3 codes.

They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.

jQuery.noConflict();
jQuery.ready(function($){
 //Code using $ as alias to jQuery
});

Find Item in ObservableCollection without using a loop

Here comes Linq:

var listItem = list.Single(i => i.Title == title);

It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault.

If you want a collection of items matching the title, there's:

var listItems = list.Where(i => i.Title ==  title);

How to clamp an integer to some range?

sorted((minval, value, maxval))[1]

for example:

>>> minval=3
>>> maxval=7
>>> for value in range(10):
...   print sorted((minval, value, maxval))[1]
... 
3
3
3
3
4
5
6
7
7
7

Can you autoplay HTML5 videos on the iPad?

In this Safari HTML5 reference, you can read

To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.

How to include js and CSS in JSP with spring MVC

First you need to declare your resources in dispatcher-servlet file like this :

<mvc:resources mapping="/resources/**" location="/resources/folder/" />

Any request with url mapping /resources/** will directly look for /resources/folder/.

Now in jsp file you need to include your css file like this :

<link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">

Similarly you can include js files.

Hope this solves your problem.

How to show multiline text in a table cell

the below code works like magic to me >>

td { white-space:pre-line }

jQuery input button click event listener

$("#filter").click(function(){
    //Put your code here
});

Unzip All Files In A Directory

for file in 'ls *.zip'; do unzip "${file}" -d "${file:0:-4}"; done

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

You are confusing 'sets' and 'lists'. A set does not guarantee order, but lists do.

Sets are declared using curly brackets: {}. In contrast, lists are declared using square brackets: [].

mySet = {a, b, c, c}

Does not guarantee order, but list does:

myList = [a, b, c]

How to reference static assets within vue javascript

For anyone looking to refer images from template, You can refer images directly using '@'

Example:

<img src="@/assets/images/home.png"/>

DataTrigger where value is NOT null?

You can use a converter or create new property in your ViewModel like that:

public bool CanDoIt
{
    get
    {
        return !string.IsNullOrEmpty(SomeField);
    }
}

and use it:

<DataTrigger Binding="{Binding SomeField}" Value="{Binding CanDoIt}">

How to append strings using sprintf?

You can use the simple line shown below to append strings in one buffer:

sprintf(Buffer,"%s %s %s","Hello World","Good Morning","Good Afternoon");

how to make a div to wrap two float divs inside?

This should do it:

<div id="wrap">
  <div id="nav"></div>
  <div id="content"></div>
  <div style="clear:both"></div>
</div>

Package name does not correspond to the file path - IntelliJ

I created a package under folder src which resolved this problem.

project structure

How to perform a for loop on each character in a string in Bash?

I believe there is still no ideal solution that would correctly preserve all whitespace characters and is fast enough, so I'll post my answer. Using ${foo:$i:1} works, but is very slow, which is especially noticeable with large strings, as I will show below.

My idea is an expansion of a method proposed by Six, which involves read -n1, with some changes to keep all characters and work correctly for any string:

while IFS='' read -r -d '' -n 1 char; do
        # do something with $char
done < <(printf %s "$string")

How it works:

  • IFS='' - Redefining internal field separator to empty string prevents stripping of spaces and tabs. Doing it on a same line as read means that it will not affect other shell commands.
  • -r - Means "raw", which prevents read from treating \ at the end of the line as a special line concatenation character.
  • -d '' - Passing empty string as a delimiter prevents read from stripping newline characters. Actually means that null byte is used as a delimiter. -d '' is equal to -d $'\0'.
  • -n 1 - Means that one character at a time will be read.
  • printf %s "$string" - Using printf instead of echo -n is safer, because echo treats -n and -e as options. If you pass "-e" as a string, echo will not print anything.
  • < <(...) - Passing string to the loop using process substitution. If you use here-strings instead (done <<< "$string"), an extra newline character is appended at the end. Also, passing string through a pipe (printf %s "$string" | while ...) would make the loop run in a subshell, which means all variable operations are local within the loop.

Now, let's test the performance with a huge string. I used the following file as a source:
https://www.kernel.org/doc/Documentation/kbuild/makefiles.txt
The following script was called through time command:

#!/bin/bash

# Saving contents of the file into a variable named `string'.
# This is for test purposes only. In real code, you should use
# `done < "filename"' construct if you wish to read from a file.
# Using `string="$(cat makefiles.txt)"' would strip trailing newlines.
IFS='' read -r -d '' string < makefiles.txt

while IFS='' read -r -d '' -n 1 char; do
        # remake the string by adding one character at a time
        new_string+="$char"
done < <(printf %s "$string")

# confirm that new string is identical to the original
diff -u makefiles.txt <(printf %s "$new_string")

And the result is:

$ time ./test.sh

real    0m1.161s
user    0m1.036s
sys     0m0.116s

As we can see, it is quite fast.
Next, I replaced the loop with one that uses parameter expansion:

for (( i=0 ; i<${#string}; i++ )); do
    new_string+="${string:$i:1}"
done

The output shows exactly how bad the performance loss is:

$ time ./test.sh

real    2m38.540s
user    2m34.916s
sys     0m3.576s

The exact numbers may very on different systems, but the overall picture should be similar.

How to open child forms positioned within MDI parent in VB.NET?

Try adding a button on mdi parent and add this code' to set your mdi child inside the mdi parent. change the yourchildformname to your MDI Child's form name and see if this works.

    Dim NewMDIChild As New yourchildformname()
    'Set the Parent Form of the Child window.
    NewMDIChild.MdiParent = Me
    'Display the new form.
    NewMDIChild.Show()

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.

Python, compute list difference

One liner:

diff = lambda l1,l2: [x for x in l1 if x not in l2]
diff(A,B)
diff(B,A)

Or:

diff = lambda l1,l2: filter(lambda x: x not in l2, l1)
diff(A,B)
diff(B,A)

Tomcat Server Error - Port 8080 already in use

For Ubuntu/Linux

Step 1: Find the process id that is using the port 8080

netstat -lnp | grep 8080
or
ps -aef | grep tomcat

Step 2: Kill the process using process id in above result

kill -9 process_id

For Windows

Step 1: Find the process id

netstat -ano | findstr 8080

Step 2: Open command prompt as administrator and kill the process

taskkill /F /pid 1088

In my case port 8005 was already in use so I used the same above steps.

enter image description here

Error inflating when extending a class

in my case I added such cyclic resource:

<drawable name="above_shadow">@drawable/above_shadow</drawable>

then changed to

<drawable name="some_name">@drawable/other_name</drawable>

and it worked

Why do we use $rootScope.$broadcast in AngularJS?

$rootScope.$broadcast is a convenient way to raise a "global" event which all child scopes can listen for. You only need to use $rootScope to broadcast the message, since all the descendant scopes can listen for it.

The root scope broadcasts the event:

$rootScope.$broadcast("myEvent");

Any child Scope can listen for the event:

$scope.$on("myEvent",function () {console.log('my event occurred');} );

Why we use $rootScope.$broadcast? You can use $watch to listen for variable changes and execute functions when the variable state changes. However, in some cases, you simply want to raise an event that other parts of the application can listen for, regardless of any change in scope variable state. This is when $broadcast is helpful.

Create Table from View

If you just want to snag the schema and make an empty table out of it, use a false predicate, like so:

SELECT * INTO myNewTable FROM myView WHERE 1=2

Numpy, multiply array with scalar

Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])

How to fix "Attempted relative import in non-package" even with __init__.py

Try this

import components
from components import *

PHP header(Location: ...): Force URL change in address bar

In your form element add data-ajax="false". I had the same problem using jquery mobile.

How can I get Apache gzip compression to work?

Enable compression via .htaccess

For most people reading this, compression is enabled by adding some code to a file called .htaccess on their web host/server. This means going to the file manager (or wherever you go to add or upload files) on your webhost.

The .htaccess file controls many important things for your site.

The code below should be added to your .htaccess file...

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

Save the .htaccess file and then refresh your webpage.

Check to see if your compression is working using the Gzip compression tool.

mysql delete under safe mode

Turning off safe mode in Mysql workbench 6.3.4.0

Edit menu => Preferences => SQL Editor : Other section: click on "Safe updates" ... to uncheck option

Workbench Preferences

Adding a Button to a WPF DataGrid

First create a DataGridTemplateColumn to contain the button:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
      <Button Click="ShowHideDetails">Details</Button> 
    </DataTemplate> 
  </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn>

When the button is clicked, update the containing DataGridRow's DetailsVisibility:

void ShowHideDetails(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
    if (vis is DataGridRow)
    {
        var row = (DataGridRow)vis;
        row.DetailsVisibility = 
        row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        break;
    }
}

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

Error connecting Redis on Apple Silicon( Macbook Pro M1 - Dec 2020), you have to just know 2 things:

  1. Run the redis-server using a sudo will remove the server starting error

shell% sudo redis-server

  1. For running it as a service "daemonize" it will allow you to run in the background

shell% sudo redis-server --daemonize yes

Verify using below steps: shell% redis-cli ping

Hope this helps all Macbook Pro M1 users who are really worried about lack of documentation on this.

Create parameterized VIEW in SQL Server 2008

in fact there exists one trick:

create view view_test as

select
  * 
from 
  table 
where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
where
spid = @@spid)

... in sql-query:

set context_info 2
select * from view_test

will be the same with

select * from table where id = 2

but using udf is more acceptable

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

This should do the trick!

// convert object => json
$json = json_encode($myObject);

// convert json => object
$obj = json_decode($json);

Here's an example

$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";

$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}

print_r(json_decode($json));
// stdClass Object
// (
//   [hello] => world
//   [bar] => baz
// )

If you want the output as an Array instead of an Object, pass true to json_decode

print_r(json_decode($json, true));
// Array
// (
//   [hello] => world
//   [bar] => baz
// )    

More about json_encode()

See also: json_decode()

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject method that just makes a plain object. You can then use reflection to get at the properties you need.

If your controller takes a FormCollection, and you didn't add anything else to the data the json should be in form[0]:

public ActionResult Save(FormCollection forms) {
  string json = forms[0];
  // do your thing here.
}

What is the maximum size of a web browser's cookie's key?

Actually, RFC 2965, the document that defines how cookies work, specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. Each browser's implementation maximum will necessarily be different, so consult individual browser documentation.

See section 5.3, "Implementation Limits", in the RFC.

Running Tensorflow in Jupyter Notebook

You will need to add a "kernel" for it. Run your enviroment:

>activate tensorflow

Then add a kernel by command (after --name should follow your env. with tensorflow):

>python -m ipykernel install --user --name tensorflow --display-name "TensorFlow-GPU"

After that run jupyter notebook from your tensorflow env.

>jupyter notebook

And then you will see the following enter image description here

Click on it and then in the notebook import packages. It will work out for sure.

Convert Date format into DD/MMM/YYYY format in SQL Server

Try this

select convert(varchar,getdate(),100)

third parameter is format, range is from 100 to 114, any one should work for you.

If you need date in dd/mmm/yyyy use this:

replace(convert(char(11),getdate(),113),' ','-')

Replace getdate() with your column name. This worked for me.

Reading file input from a multipart/form-data POST

I open-sourced a C# Http form parser here.

This is slightly more flexible than the other one mentioned which is on CodePlex, since you can use it for both Multipart and non-Multipart form-data, and also it gives you other form parameters formatted in a Dictionary object.

This can be used as follows:

non-multipart

public void Login(Stream stream)
{
    string username = null;
    string password = null;

    HttpContentParser parser = new HttpContentParser(stream);
    if (parser.Success)
    {
        username = HttpUtility.UrlDecode(parser.Parameters["username"]);
        password = HttpUtility.UrlDecode(parser.Parameters["password"]);
    }
}

multipart

public void Upload(Stream stream)
{
    HttpMultipartParser parser = new HttpMultipartParser(stream, "image");

    if (parser.Success)
    {
        string user = HttpUtility.UrlDecode(parser.Parameters["user"]);
        string title = HttpUtility.UrlDecode(parser.Parameters["title"]);

        // Save the file somewhere
        File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
    }
}

If hasClass then addClass to parent

The reason that does not work is because this has no specific meaning inside of an if statement, you will have to go back to a level of scope where this is defined (a function).

For example:

$('#element1').click(function() {
    console.log($(this).attr('id')); // logs "element1"

    if ($('#element2').hasClass('class')) {
        console.log($(this).attr('id')); // still logs "element1"
    }
});

Updating user data - ASP.NET Identity

The OWIN context allows you to get the db context. Seems to be working fine so far me, and after all, I got the idea from the ApplciationUserManager class which does the same thing.

    internal void UpdateEmail(HttpContext context, string userName, string email)
    {
        var manager = context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var user = manager.FindByName(userName);
        user.Email = email;
        user.EmailConfirmed = false;
        manager.Update(user);
        context.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();
    }

Remove trailing comma from comma-separated string

You can use this:

String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));

When creating a service with sc.exe how to pass in context parameters?

Parameters for created services have some peculiar formating issues, in particular if the command includes spaces or quotes:

If you want to enter command line parameters for the service, you have to enclose the whole command line in quotes. (And always leave a space after binPath= and before the first quote, as mrswadge pointed out)

So, to create a service for the command PATH\COMMAND.EXE --param1=xyz you would use the following binPath parameter:

binPath= "PATH\COMMAND.EXE --param1=xyz"
        ^^                             ^
        ||                             |
  space    quote                     quote

If the path to the executable contains spaces, you have to enclose the path in quotes.

So for a command that has both parameters and a path with spaces, you need nested quotes. You have to escape the inner quotes with backslashes \". The same holds if the parameters themselves contain quotes, you will need to escape those too.

Despite using backslashes as escape characters, you do not have to escape the regular backslashes contained in the path. This is contrary to how you normally use backslashes as escape characters.

So for a command like
"PATH WITH SPACES \COMMAND.EXE" --param-with-quotes="a b c" --param2:

binPath= "\"PATH WITH SPACES \COMMAND.EXE\" --param-with-quotes=\"a b c\" --param2"
         ^ ^                 ^           ^                      ^       ^         ^
         | |                 |           |                      |       |         | 
 opening     escaped      regular     escaped                    escaped       closing
   quote     quote       backslash    closing                    quotes          quote
     for     for            in         quote                      for              for
   whole     path          path       for path                  parameter        whole
 command                                                                       command

Here is a concrete example from the SVNserve documentation, which shows all special cases:

sc create svnserve 
   binpath= "\"C:\Program Files\CollabNet Subversion Server\svnserve.exe\" --service -r \"C:\my repositories\"  "
   displayname= "Subversion Server" depend= Tcpip start= auto 

(linebreaks are added for readability, do not include them)

This would add a new service with the command line "C:\Program Files\CollabNet Subversion Server\svnserve.exe" --service -r "C:\my repositories".

So in summary

  • space after each sc parameter: binpath=_, displayname=_ and depend=_
  • each sc parameter that contains spaces must be enclosed in quotes
  • all additional quotes inside the binpath are escaped with backslashes: \"
  • all backslashes inside the binpath are not escaped

Getting Excel to refresh data on sheet from within VBA

This should do the trick...

'recalculate all open workbooks
Application.Calculate

'recalculate a specific worksheet
Worksheets(1).Calculate

' recalculate a specific range
Worksheets(1).Columns(1).Calculate

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

Create a txt file using batch file in a specific folder

You have it almost done. Just explicitly say where to create the file

@echo off
  echo.>"d:\testing\dblank.txt"

This creates a file containing a blank line (CR + LF = 2 bytes).

If you want the file empty (0 bytes)

@echo off
  break>"d:\testing\dblank.txt"

How can I style even and odd elements?

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1).

this is what you want:

<html>
    <head>
        <style>
            li { color: blue }<br>
            li:nth-child(even) { color:red }
            li:nth-child(odd) { color:green}
        </style>
    </head>
    <body>
        <ul>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
        </ul>
    </body>
</html>

Swift - encode URL

Swift 3

In Swift 3 there is addingPercentEncoding

let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(escapedString!)

Output:

test%2Ftest

Swift 1

In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters

var originalString = "test/test"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")

Output:

test%2Ftest

The following are useful (inverted) character sets:

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

If you want a different set of characters to be escaped create a set:
Example with added "=" character:

var originalString = "test/test=42"
var customAllowedSet =  NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")

Output:

test%2Ftest%3D42

Example to verify ascii characters not in the set:

func printCharactersInSet(set: NSCharacterSet) {
    var characters = ""
    let iSet = set.invertedSet
    for i: UInt32 in 32..<127 {
        let c = Character(UnicodeScalar(i))
        if iSet.longCharacterIsMember(i) {
            characters = characters + String(c)
        }
    }
    print("characters not in set: \'\(characters)\'")
}

React Router v4 - How to get current route?

Add

import {withRouter} from 'react-router-dom';

Then change your component export

export default withRouter(ComponentName)

Then you can access the route directly within the component itself (without touching anything else in your project) using:

window.location.pathname

Tested March 2020 with: "version": "5.1.2"

TypeScript: Interfaces vs Types

When it comes to compilation speed, composed interfaces perform better than type intersections:

[...] interfaces create a single flat object type that detects property conflicts. This is in contrast with intersection types, where every constituent is checked before checking against the effective type. Type relationships between interfaces are also cached, as opposed to intersection types.

Source: https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections

wp_nav_menu change sub-menu class name?

You can just use a Hook

add_filter( 'nav_menu_submenu_css_class', 'some_function', 10, 3 );
function some_function( $classes, $args, $depth ){
    foreach ( $classes as $key => $class ) {
    if ( $class == 'sub-menu' ) {
        $classes[ $key ] = 'my-sub-menu';
    }
}

return $classes;
}

where

$classes(array) - The CSS classes that are applied to the menu <ul> element.
$args(stdClass) - An object of wp_nav_menu() arguments.
$depth(int) - Depth of menu item. Used for padding.

What is the difference between a web API and a web service?

Difference between Web Service and Web API nicely explained here:

https://softwareengineering.stackexchange.com/questions/38691/difference-between-web-api-and-web-service

Text from the link:

Web Services - that's standard defined by W3C, so they can be accessed semi-automatically or automatically (WSDL / UDDI). The whole thing is based on XML, so anyone can call it. And every aspect of the service is very well defined. There's parameters description standard, parameter passing standard, response standard, discovery standard, etc. etc. You could probably write 2000 pages book that'd describe the standard. There are even some "additional" standards for doing "standard" things, like authentication.

Despite the fact that automatic invoking and discovery is barely working because clients are rather poor, and you have no real guarantee that any service can be called from any client.

Web API is typically done as HTTP/REST, nothing is defined, output can be for eg. JSON/XML, input can be XML/JSON/or plain data. There are no standards for anything => no automatic calling and discovery. You can provide some description in text file or PDF, you can return the data in Windows-1250 instead of unicode, etc. For describing the standard it'd be 2 pages brochure with some simple info and you'll define everything else.

Web is switching towards Web API / REST. Web Services are really no better than Web API. Very complicated to develop and they eat much more resources (bandwidth and RAM)... and because of all data conversions (REQUEST->XML->DATA->RESPONSE->XML->VALIDATION->CONVERSION->DATA) are very slow.

Eg. In WebAPI you can pack the data, send it compressed and un-compress+un-pack on the client. In SOAP you could only compress HTML request.

Sending JSON to PHP using ajax

just remove:

...
//dataType: "json",
url: "index.php",
data: {myData:postData},
//contentType: "application/json; charset=utf-8",
...

Sort ObservableCollection<string> through C#

If performance is your main concern and you dont mind listening to different events, then this is the way to go for a stable sort:

public static void Sort<T>(this ObservableCollection<T> list) where T : IComparable<T>
{
    int i = 0;
    foreach (var item in list.OrderBy(x => x))
    {
        if (!item.Equals(list[i]))
        {
            list[i] = item;
        }

        i++;
    }
}

I am not sure if there is anything simpler and faster (at least theoretically), as far as stable sorts go. Doing a ToArray on the ordered list might make the enumeration faster but at worse space complexity. You could also do away with the Equals check to go even faster, but I guess reducing change notification is a welcome thing.

Also this doesn't break any bindings.

Mind you this raises a bunch of Replace events rather than Move (which is more expected for a Sort operation), and also the number of events raised will be most likely more when compared to other Move approaches in this thread but it is unlikely it matters for performance, I think.. Most UI elements must have implemented IList and doing a replace on ILists should be faster than Moves. But more changed events means more screen refreshes. You will have to test it out to see the implications.


For a Move answer, see this. Haven't seen a more correct implementation that works even when you have duplicates in the collection.

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Creating SubString (prefix and suffix) from String using Swift 4:

let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}

Output

prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix : 

If you want to generate a substring between 2 indices , use :

let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex

How do I install cygwin components from the command line?

First, download installer at: https://cygwin.com/setup-x86_64.exe (Windows 64bit), then:

# move installer to cygwin folder
mv C:/Users/<you>/Downloads/setup-x86_64.exe C:/cygwin64/

# add alias to bash_aliases
echo "alias cygwin='C:/cygwin64/setup-x86_64.exe -q -P'" >> ~/.bash_aliases
source ~/.bash_aliases

# add bash_aliases to bashrc if missing
echo "source ~/.bash_aliases" >> ~/.profile

e.g.

# install vim
cygwin vim

# see other options
cygwin --help

How do I write a correct micro-benchmark in Java?

Tips about writing micro benchmarks from the creators of Java HotSpot:

Rule 0: Read a reputable paper on JVMs and micro-benchmarking. A good one is Brian Goetz, 2005. Do not expect too much from micro-benchmarks; they measure only a limited range of JVM performance characteristics.

Rule 1: Always include a warmup phase which runs your test kernel all the way through, enough to trigger all initializations and compilations before timing phase(s). (Fewer iterations is OK on the warmup phase. The rule of thumb is several tens of thousands of inner loop iterations.)

Rule 2: Always run with -XX:+PrintCompilation, -verbose:gc, etc., so you can verify that the compiler and other parts of the JVM are not doing unexpected work during your timing phase.

Rule 2.1: Print messages at the beginning and end of timing and warmup phases, so you can verify that there is no output from Rule 2 during the timing phase.

Rule 3: Be aware of the difference between -client and -server, and OSR and regular compilations. The -XX:+PrintCompilation flag reports OSR compilations with an at-sign to denote the non-initial entry point, for example: Trouble$1::run @ 2 (41 bytes). Prefer server to client, and regular to OSR, if you are after best performance.

Rule 4: Be aware of initialization effects. Do not print for the first time during your timing phase, since printing loads and initializes classes. Do not load new classes outside of the warmup phase (or final reporting phase), unless you are testing class loading specifically (and in that case load only the test classes). Rule 2 is your first line of defense against such effects.

Rule 5: Be aware of deoptimization and recompilation effects. Do not take any code path for the first time in the timing phase, because the compiler may junk and recompile the code, based on an earlier optimistic assumption that the path was not going to be used at all. Rule 2 is your first line of defense against such effects.

Rule 6: Use appropriate tools to read the compiler's mind, and expect to be surprised by the code it produces. Inspect the code yourself before forming theories about what makes something faster or slower.

Rule 7: Reduce noise in your measurements. Run your benchmark on a quiet machine, and run it several times, discarding outliers. Use -Xbatch to serialize the compiler with the application, and consider setting -XX:CICompilerCount=1 to prevent the compiler from running in parallel with itself. Try your best to reduce GC overhead, set Xmx(large enough) equals Xms and use UseEpsilonGC if it is available.

Rule 8: Use a library for your benchmark as it is probably more efficient and was already debugged for this sole purpose. Such as JMH, Caliper or Bill and Paul's Excellent UCSD Benchmarks for Java.

Read XML Attribute using XmlDocument

If your XML contains namespaces, then you can do the following in order to obtain the value of an attribute:

var xmlDoc = new XmlDocument();

// content is your XML as string
xmlDoc.LoadXml(content);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

// make sure the namespace identifier, URN in this case, matches what you have in your XML 
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:SAML:2.0:protocol");

// get the value of Destination attribute from within the Response node with a prefix who's identifier is "urn:oasis:names:tc:SAML:2.0:protocol" using XPath
var str = xmlDoc.SelectSingleNode("/ns:Response/@Destination", nsmgr);
if (str != null)
{
    Console.WriteLine(str.Value);
}

More on XML namespaces here and here.

FIFO class in Java

Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E> with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.

Specifying onClick event type with Typescript and React.Konva

React.MouseEvent works for me:

private onClick = (e: React.MouseEvent<HTMLInputElement>) => {
  let button = e.target as HTMLInputElement;
}

Python equivalent of D3.js

I've got a good example of automatically generating D3.js network diagrams using Python here: http://brandonrose.org/ner2sna

The cool thing is that you end up with auto-generated HTML and JS and can embed the interactive D3 chart in a notebook with an IFrame

How to directly execute SQL query in C#?

Something like this should suffice, to do what your batch file was doing (dumping the result set as semi-colon delimited text to the console):

// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "

DataTable dt            = new DataTable() ;
int       rows_returned ;

const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
  select tPatCulIntPatIDPk ,
         tPatSFirstname    ,
         tPatSName         ,
         tPatDBirthday
  from dbo.TPatientRaw
  where tPatSName = @patientSurname
  " ;

using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand    cmd        = connection.CreateCommand() )
using ( SqlDataAdapter sda       = new SqlDataAdapter( cmd ) )
{
  cmd.CommandText = sqlQuery ;
  cmd.CommandType = CommandType.Text ;
  connection.Open() ;
  rows_returned = sda.Fill(dt) ;
  connection.Close() ;
}

if ( dt.Rows.Count == 0 )
{
  // query returned no rows
}
else
{

  //write semicolon-delimited header
  string[] columnNames = dt.Columns
                           .Cast<DataColumn>()
                           .Select( c => c.ColumnName )
                           .ToArray()
                           ;
  string   header      = string.Join("," , columnNames) ;
  Console.WriteLine(header) ;

  // write each row
  foreach ( DataRow dr in dt.Rows )
  {

    // get each rows columns as a string (casting null into the nil (empty) string
    string[] values = new string[dt.Columns.Count];
    for ( int i = 0 ; i < dt.Columns.Count ; ++i )
    {
      values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
    }

    // construct the string to be dumped, quoting each value and doubling any embedded quotes.
    string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
    Console.WriteLine(values);

  }

}

Check whether there is an Internet connection available on Flutter app

I found that just using the connectivity package was not enough to tell if the internet was available or not. In Android it only checks if there is WIFI or if mobile data is turned on, it does not check for an actual internet connection . During my testing, even with no mobile signal ConnectivityResult.mobile would return true.

With IOS my testing found that the connectivity plugin does correctly detect if there is an internet connection when the phone has no signal, the issue was only with Android.

The solution I found was to use the data_connection_checker package along with the connectivity package. This just makes sure there is an internet connection by making requests to a few reliable addresses, the default timeout for the check is around 10 seconds.

My finished isInternet function looked a bit like this:

  Future<bool> isInternet() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      // I am connected to a mobile network, make sure there is actually a net connection.
      if (await DataConnectionChecker().hasConnection) {
        // Mobile data detected & internet connection confirmed.
        return true;
      } else {
        // Mobile data detected but no internet connection found.
        return false;
      }
    } else if (connectivityResult == ConnectivityResult.wifi) {
      // I am connected to a WIFI network, make sure there is actually a net connection.
      if (await DataConnectionChecker().hasConnection) {
        // Wifi detected & internet connection confirmed.
        return true;
      } else {
        // Wifi detected but no internet connection found.
        return false;
      }
    } else {
      // Neither mobile data or WIFI detected, not internet connection found.
      return false;
    }
  }

The if (await DataConnectionChecker().hasConnection) part is the same for both mobile and wifi connections and should probably be moved to a separate function. I've not done that here to leave it more readable.

This is my first Stack Overflow answer, hope it helps someone.

Skipping every other element after the first

There are more ways than one to skin a cat. - Seba Smith

arr = list(range(10)) # Range from 0-9

# List comprehension: Range with conditional
print [arr[index] for index in range(len(arr)) if index % 2 == 0]

# List comprehension: Range with step
print [arr[index] for index in range(0, len(arr), 2)]

# List comprehension: Enumerate with conditional
print [item for index, item in enumerate(arr) if index % 2 == 0]

# List filter: Index in range
print filter(lambda index: index % 2 == 0, range(len(arr)))

# Extended slice
print arr[::2]

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

Remove characters before character "."

A couple of methods that, if the char does not exists, return the original string.

This one cuts the string after the first occurrence of the pivot:

public static string truncateStringAfterChar(string input, char pivot){         
    int index = input.IndexOf(pivot);   
    if(index >= 0) {
        return input.Substring(index + 1);          
    }           
    return input;       
}

This one instead cuts the string after the last occurrence of the pivot:

public static string truncateStringAfterLastChar(string input, char pivot){         
    return input.Split(pivot).Last();   
}

How to compile .c file with OpenSSL includes?

For this gcc error, you should reference to to the gcc document about Search Path.

In short:

1) If you use angle brackets(<>) with #include, gcc will search header file firstly from system path such as /usr/local/include and /usr/include, etc.

2) The path specified by -Ldir command-line option, will be searched before the default directories.

3)If you use quotation("") with #include as #include "file", the directory containing the current file will be searched firstly.

so, the answer to your question is as following:

1) If you want to use header files in your source code folder, replace <> with "" in #include directive.

2) if you want to use -I command line option, add it to your compile command line.(if set CFLAGS in environment variables, It will not referenced automatically)

3) About package configuration(openssl.pc), I do not think it will be referenced without explicitly declared in build configuration.

#include errors detected in vscode

In my case I did not need to close the whole VS-Code, closing the opened file (and sometimes even saving it) solved the issue.

How to create timer events using C++ 11?

This is the code I have so far:

I am using VC++ 2012 (no variadic templates)

//header
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
#include <memory>
#include <algorithm>

template<class T>
class TimerThread
{
  typedef std::chrono::high_resolution_clock clock_t;

  struct TimerInfo
  {
    clock_t::time_point m_TimePoint;
    T m_User;

    template <class TArg1>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1))
    {
    }

    template <class TArg1, class TArg2>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1, TArg2 && arg2)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2))
    {
    }
  };

  std::unique_ptr<std::thread> m_Thread;
  std::vector<TimerInfo>       m_Timers;
  std::mutex                   m_Mutex;
  std::condition_variable      m_Condition;
  bool                         m_Sort;
  bool                         m_Stop;

  void TimerLoop()
  {
    for (;;)
    {
      std::unique_lock<std::mutex>  lock(m_Mutex);

      while (!m_Stop && m_Timers.empty())
      {
        m_Condition.wait(lock);
      }

      if (m_Stop)
      {
        return;
      }

      if (m_Sort)
      {
        //Sort could be done at insert
        //but probabily this thread has time to do
        std::sort(m_Timers.begin(),
                  m_Timers.end(),
                  [](const TimerInfo & ti1, const TimerInfo & ti2)
        {
          return ti1.m_TimePoint > ti2.m_TimePoint;
        });
        m_Sort = false;
      }

      auto now = clock_t::now();
      auto expire = m_Timers.back().m_TimePoint;

      if (expire > now) //can I take a nap?
      {
        auto napTime = expire - now;
        m_Condition.wait_for(lock, napTime);

        //check again
        auto expire = m_Timers.back().m_TimePoint;
        auto now = clock_t::now();

        if (expire <= now)
        {
          TimerCall(m_Timers.back().m_User);
          m_Timers.pop_back();
        }
      }
      else
      {
        TimerCall(m_Timers.back().m_User);
        m_Timers.pop_back();
      }
    }
  }

  template<class T, class TArg1>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1);

  template<class T, class TArg1, class TArg2>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2);

public:
  TimerThread() : m_Stop(false), m_Sort(false)
  {
    m_Thread.reset(new std::thread(std::bind(&TimerThread::TimerLoop, this)));
  }

  ~TimerThread()
  {
    m_Stop = true;
    m_Condition.notify_all();
    m_Thread->join();
  }
};

template<class T, class TArg1>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

template<class T, class TArg1, class TArg2>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1),
                                      std::forward<TArg2>(arg2)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

//sample
#include <iostream>
#include <string>

void TimerCall(int i)
{
  std::cout << i << std::endl;
}

int main()
{
  std::cout << "start" << std::endl;
  TimerThread<int> timers;

  CreateTimer(timers, 2000, 1);
  CreateTimer(timers, 5000, 2);
  CreateTimer(timers, 100, 3);

  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "end" << std::endl;
}

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

Try DELETE the current datas from tblDomare.PersNR . Because the values in tblDomare.PersNR didn't match with any of the values in tblBana.BanNR.

HTML not loading CSS file

I found myself out here looking for an answer and figured out that my issue was a missing character - spelling is important.

<link href="tss_layout.css" rel=styleheet" />

once I put the s in the middle of stylesheet - worked like a charm.

How to get an Instagram Access Token

If you're looking for instructions, check out this article post. And if you're using C# ASP.NET, have a look at this repo.

base 64 encode and decode a string in angular (2+)

For encoding to base64 in Angular2, you can use btoa() function.

Example:-

console.log(btoa("stringAngular2")); 
// Output:- c3RyaW5nQW5ndWxhcjI=

For decoding from base64 in Angular2, you can use atob() function.

Example:-

console.log(atob("c3RyaW5nQW5ndWxhcjI=")); 
// Output:- stringAngular2

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

You'll get this error if you try to use a Git command when your current working directory is not within a Git repository. That is because, by default, Git will look for a .git repository directory (inside of the project root?), as pointed out by my answer to "Git won't show log unless I am in the project directory":

According to the official Linux Kernel Git documentation, GIT_DIR is [an environment variable] set to look for a .git directory (in the current working directory?) by default:

If the GIT_DIR environment variable is set then it specifies a path to use instead of the default .git for the base of the repository.

You'll either need to cd into the repository/working copy, or you didn't initialize or clone a repository in the first place, in which case you need to initialize a repo in the directory where you want to place the repo:

git init

or clone a repository

git clone <remote-url>
cd <repository>

Debugging WebSocket in Google Chrome

Chrome Canary and Chromium now have WebSocket message frame inspection feature. Here are the steps to test it quickly:

  1. Navigate to the WebSocket Echo demo, hosted on the websocket.org site.
  2. Turn on the Chrome Developer Tools.
  3. Click Network, and to filter the traffic shown by the Dev Tools, click WebSockets.
  4. In the Echo demo, click Connect. On the Headers tab in Google Dev Tool you can inspect the WebSocket handshake.
  5. Click the Send button in the Echo demo.
  6. THIS STEP IS IMPORTANT: To see the WebSocket frames in the Chrome Developer Tools, under Name/Path, click the echo.websocket.org entry, representing your WebSocket connection. This refreshes the main panel on the right and makes the WebSocket Frames tab show up with the actual WebSocket message content.

Note: Every time you send or receive new messages, you have to refresh the main panel by clicking on the echo.websocket.org entry on the left.

I also posted the steps with screen shots and video.

My recently published book, The Definitive Guide to HTML5 WebSocket, also has a dedicated appendix covering the various inspection tools, including Chrome Dev Tools, Chrome net-internals, and Wire Shark.

Shortcut to Apply a Formula to an Entire Column in Excel

Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

The following steps fix the problem for VS 2015 and VS 2017:


Close VS.

Navigate to the folder of the solution and delete the hidden .vs folder.

open VS.

Hit F5 and IIS Express should load as normal, allowing you to debug.

How to Get XML Node from XDocument

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");

How do I get into a non-password protected Java keystore or change the password?

The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.

Starting the week on Monday with isoWeekday()

Here is a more generic solution for any given weekday. Working demo on jsfiddle

var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.

var startOfPeriod = moment("2013-06-23T00:00:00"),

// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
    moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
    7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;

// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);

How do you modify a CSS style in the code behind file for divs in ASP.NET?

Another way to do it:

testSpace.Style.Add("display", "none");

or

testSpace.Style["background-image"] = "url(images/foo.png)";

in vb.net you can do it this way:

testSpace.Style.Item("display") = "none"

Cron job every three days

Because cron is "stateless", it cannot accurately express "frequencies", only "patterns" which it (apparently) continuously matches against the current time.

Rephrasing your question makes this more obvious: "is it possible to run a cronjob at 00:01am every night except skip nights when it had run within 2 nights?" When cron is comparing the current time to job request time patterns, there's no way cron can know if it ran your job in the past.

(it certainly is possible to write a stateful cron that records past jobs and thus includes patterns for matching against this state, but that's not the standard cron included in most operating systems. Such a system would get complicated by requiring the introduction of the concept of when such patterns "reset". For example, is the pattern reset when the time is changed (i.e. the crontab entry is revised)? Look to your favorite calendar app to see how complicated it can get to express Repeating patterns of scheduled events, and note that they don't have the reset problem because the starting calendar event has a natural "start" a/k/a "reset" date. Try rescheduling an every-other-week recurring calendar event to postpone by a week, over christmas for example. Usually you have to terminate that recurring event and restart a completely new one; this illustrates the limited expressivity of how even complicated calendar apps represent repeating patterns. And of course Calendars have a lot of state-- each individual event can be deleted or rescheduled independently [in most calendar apps]).

Further, you probably want to do your job every 3rd night if successful, but if the last one failed, to try again immediately, perhaps the next night (not wait 3 more days) or even sooner, like an hour later (but stop retrying upon morning's arrival). Clearly, cron couldn't possibly know if your job succeeded and the pattern can't also express an alternate more frequent "retry" schedule.

ANYWAY-- You can do what you want yourself. Write a script, tell cron to run it nightly at 00:01am. This script could check the timestamp of something* which records the "last run", and if it was >3 days ago**, perform the job and reset the "last run" timestamp.

(*that timestamped indicator is a bit of persisted state which you can manipulate and examine, but which cron cannot)

**be careful with time arithmetic if you're using human-readable clock time-- twice a year, some days have 23 or 25 hours in their day, and 02:00-02:59 occurs twice in one day or not at all. Use UTC to avoid this.

How can I save a base64-encoded image to disk?

You can use a third-party library like base64-img or base64-to-image.

  1. base64-img
const base64Img = require('base64-img');

const data = 'data:image/png;base64,...';
const destpath = 'dir/to/save/image';
const filename = 'some-filename';

base64Img.img(data, destpath, filename, (err, filepath) => {}); // Asynchronous using

const filepath = base64Img.imgSync(data, destpath, filename); // Synchronous using
  1. base64-to-image
const base64ToImage = require('base64-to-image');

const base64Str = 'data:image/png;base64,...';
const path = 'dir/to/save/image/'; // Add trailing slash
const optionalObj = { fileName: 'some-filename', type: 'png' };

const { imageType, fileName } = base64ToImage(base64Str, path, optionalObj); // Only synchronous using

Left function in c#

use substring function:

yourString.Substring(0, length);

A html space is showing as %2520 instead of %20

The following code snippet resolved my issue. Thought this might be useful to others.

_x000D_
_x000D_
var strEnc = this.$.txtSearch.value.replace(/\s/g, "-");_x000D_
strEnc = strEnc.replace(/-/g, " ");
_x000D_
_x000D_
_x000D_

Rather using default encodeURIComponent my first line of code is converting all spaces into hyphens using regex pattern /\s\g and the following line just does the reverse, i.e. converts all hyphens back to spaces using another regex pattern /-/g. Here /g is actually responsible for finding all matching characters.

When I am sending this value to my Ajax call, it traverses as normal spaces or simply %20 and thus gets rid of double-encoding.

Transparent scrollbar with css

Embed this code in your css.

::-webkit-scrollbar {
    width: 0px;
}

/* Track */

::-webkit-scrollbar-track {
    -webkit-box-shadow: none;
}

/* Handle */

::-webkit-scrollbar-thumb {
    background: white;
    -webkit-box-shadow: none;
}

::-webkit-scrollbar-thumb:window-inactive {
    background: none;
}

Align Bootstrap Navigation to Center

Try this css

.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
    content: " ";
    display: table-cell;
}

ul.nav {
    float: none;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    width: 240px;
}

How to start and stop/pause setInterval?

The reason you're seeing this specific problem:

JSFiddle wraps your code in a function, so start() is not defined in the global scope.

enter image description here


Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


Other notes:

Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

Use a function instead, and get cozy with var and white space:

_x000D_
_x000D_
var input = document.getElementById("input"),
  add;

function start() {
  add = setInterval(function() {
    input.value++;
  }, 1000);
}

start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

Android Studio shortcuts like Eclipse

you can not remember all shortcuts :)
android studio(actually intellij) has a solution

quick command search : ctrl+shift+A

enter image description here

How to transform array to comma separated words string?

You're looking for implode()

$string = implode(",", $array);

Verify if file exists or not in C#

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.

is there any PHP function for open page in new tab

This is a trick,

function OpenInNewTab(url) {

  var win = window.open(url, '_blank');
  win.focus();
}

In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.

<div onclick="OpenInNewTab();">Something To Click On</div>

How to convert a char array back to a string?

1 alternate way is to do:

String b = a + "";

Check if checkbox is checked with jQuery

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Use its value directly:

In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]: 
array([[ 0.98836259,  0.82403141],
       [ 0.337358  ,  0.02054435],
       [ 0.29271728,  0.37813099],
       [ 0.70033513,  0.69919695]])

Box shadow in IE7 and IE8

Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.

It supports box-shadow (except for the inset keyword).

Java output formatting for Strings

If you want a minimum of 4 characters, for instance,

System.out.println(String.format("%4d", 5));
// Results in "   5", minimum of 4 characters

How to show all shared libraries used by executables in Linux?

With ldd you can get the libraries that tools use. To rank the usage of libraries for a set of tool you can use something like the following command.

ldd /bin/* /usr/bin/* ... | sed -e '/^[^\t]/ d; s/^\t\(.* => \)\?\([^ ]*\) (.*/\2/g' | sort | uniq -c

(Here sed strips all lines that do not start with a tab and the filters out only the actual libraries. With sort | uniq -c you get each library with a count indicating the number of times it occurred.)

You might want to add sort -g at the end to get the libraries in order of usage.

Note that you probably get lines two non-library lines with the above command. One of static executables ("not a dynamic executable") and one without any library. The latter is the result of linux-gate.so.1 which is not a library in your file system but one "supplied" by the kernel.

Detect when a window is resized using JavaScript ?

If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:

Super Super compact

var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }

All 3 possible combinations together (ES6)

var t
window.onresize = () => {
    resizing(this, this.innerWidth, this.innerHeight) //1
    if (typeof t == 'undefined') resStarted() //2
    clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}

function resizing(target, w, h) {
    console.log(`Youre resizing: width ${w} height ${h}`)
}    
function resStarted() { 
    console.log('Resize Started') 
}
function resEnded() { 
    console.log('Resize Ended') 
}

Floating point comparison functions for C#

I translated the sample from Michael Borgwardt. This is the result:

public static bool NearlyEqual(float a, float b, float epsilon){
    float absA = Math.Abs (a);
    float absB = Math.Abs (b);
    float diff = Math.Abs (a - b);

    if (a == b) {
        return true;
    } else if (a == 0 || b == 0 || diff < float.Epsilon) {
        // a or b is zero or both are extremely close to it
        // relative error is less meaningful here
        return diff < epsilon;
    } else { // use relative error
        return diff / (absA + absB) < epsilon;
    }
}

Feel free to improve this answer.

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Here's how to fix this error when launching Eclipse:

Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.

  1. Go and install latest JDK

  2. Make sure you have installed 64 bit Eclipse

How to SHUTDOWN Tomcat in Ubuntu?

Try

/etc/init.d/tomcat stop

(maybe you have to write something after tomcat, just press tab one time)

Edit: And you also need to do it as root.

What does "control reaches end of non-void function" mean?

add to your code:

"#include < stdlib.h>"

return EXIT_SUCCESS;

at the end of main()

MySQL - count total number of rows in php

Either use COUNT in your MySQL query or do a SELECT * FROM table and do:

$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

In case you need C++11 compatibility and cannot use boost, here is a boost-compatible drop-in with an example of usage:

#include <iostream>
#include <string>

static bool starts_with(const std::string str, const std::string prefix)
{
    return ((prefix.size() <= str.size()) && std::equal(prefix.begin(), prefix.end(), str.begin()));
}

int main(int argc, char* argv[])
{
    bool usage = false;
    unsigned int foos = 0; // default number of foos if no parameter was supplied

    if (argc > 1)
    {
        const std::string fParamPrefix = "-f="; // shorthand for foo
        const std::string fooParamPrefix = "--foo=";

        for (unsigned int i = 1; i < argc; ++i)
        {
            const std::string arg = argv[i];

            try
            {
                if ((arg == "-h") || (arg == "--help"))
                {
                    usage = true;
                } else if (starts_with(arg, fParamPrefix)) {
                    foos = std::stoul(arg.substr(fParamPrefix.size()));
                } else if (starts_with(arg, fooParamPrefix)) {
                    foos = std::stoul(arg.substr(fooParamPrefix.size()));
                }
            } catch (std::exception& e) {
                std::cerr << "Invalid parameter: " << argv[i] << std::endl << std::endl;
                usage = true;
            }
        }
    }

    if (usage)
    {
        std::cerr << "Usage: " << argv[0] << " [OPTION]..." << std::endl;
        std::cerr << "Example program for parameter parsing." << std::endl << std::endl;
        std::cerr << "  -f, --foo=N   use N foos (optional)" << std::endl;
        return 1;
    }

    std::cerr << "number of foos given: " << foos << std::endl;
}

getting error while updating Composer

for php7 you can do that:

sudo apt-get install php-gd php-xml php7.0-mbstring

Extending from two classes

Why Not Use an Inner Class (Nesting)

class A extends B {
    private class C extends D {
        //Classes A , B , C , D accessible here 
    }
}

How to get text of an element in Selenium WebDriver, without including child element text?

Here's a general solution:

def get_text_excluding_children(driver, element):
    return driver.execute_script("""
    return jQuery(arguments[0]).contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text();
    """, element)

The element passed to the function can be something obtained from the find_element...() methods (i.e. it can be a WebElement object).

Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:

return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
    if (child.nodeType === Node.TEXT_NODE)
        ret += child.textContent;
    child = child.nextSibling;
}
return ret;
""", element) 

I'm actually using this code in a test suite.

ASP.Net MVC Redirect To A Different View

The simplest way is use return View.

return View("ViewName");

Remember, the physical name of the "ViewName" should be something like ViewName.cshtml in your project, if your are using MVC C# / .NET.

How can you tell if a value is not numeric in Oracle?

CREATE OR REPLACE FUNCTION IS_NUMERIC(P_INPUT IN VARCHAR2) RETURN INTEGER IS
  RESULT INTEGER;
  NUM NUMBER ;
BEGIN
  NUM:=TO_NUMBER(P_INPUT);
  RETURN 1;
EXCEPTION WHEN OTHERS THEN
  RETURN 0;
END IS_NUMERIC;
/

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

How can you make a custom keyboard in Android?

Had the same problem. I used table layout at first but the layout kept changing after a button press. Found this page very useful though. http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-creating-a-numeric-keypad-with-gridlayout/

Why use Gradle instead of Ant or Maven?

I don't use Gradle in anger myself (just a toy project so far) [author means they have used Gradle on only a toy project so far, not that Gradle is a toy project - see comments], but I'd say that the reasons one would consider using it would be because of the frustrations of Ant and Maven.

In my experience Ant is often write-only (yes I know it is possible to write beautifully modular, elegant builds, but the fact is most people don't). For any non-trivial projects it becomes mind-bending, and takes great care to ensure that complex builds are truly portable. Its imperative nature can lead to replication of configuration between builds (though macros can help here).

Maven takes the opposite approach and expects you to completely integrate with the Maven lifecycle. Experienced Ant users find this particularly jarring as Maven removes many of the freedoms you have in Ant. For example there's a Sonatype blog that enumerates many of the Maven criticisms and their responses.

The Maven plugin mechanism allows for very powerful build configurations, and the inheritance model means you can define a small set of parent POMs encapsulating your build configurations for the whole enterprise and individual projects can inherit those configurations, leaving them lightweight. Maven configuration is very verbose (though Maven 3 promises to address this), and if you want to do anything that is "not the Maven way" you have to write a plugin or use the hacky Ant integration. Note I happen to like writing Maven plugins but appreciate that many will object to the effort involved.

Gradle promises to hit the sweet spot between Ant and Maven. It uses Ivy's approach for dependency resolution. It allows for convention over configuration but also includes Ant tasks as first class citizens. It also wisely allows you to use existing Maven/Ivy repositories.

So if you've hit and got stuck with any of the Ant/Maven pain points, it is probably worth trying Gradle out, though in my opinion it remains to be seen if you wouldn't just be trading known problems for unknown ones. The proof of the pudding is in the eating though so I would reserve judgment until the product is a little more mature and others have ironed out any kinks (they call it bleeding edge for a reason). I'll still be using it in my toy projects though, It's always good to be aware of the options.

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

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

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

Accessing elements of Python dictionary by index

As I noticed your description, you just know that your parser will give you a dictionary that its values are dictionary too like this:

sampleDict = {
              "key1": {"key10": "value10", "key11": "value11"},
              "key2": {"key20": "value20", "key21": "value21"}
              }

So you have to iterate over your parent dictionary. If you want to print out or access all first dictionary keys in sampleDict.values() list, you may use something like this:

for key, value in sampleDict.items():
    print value.keys()[0]

If you want to just access first key of the first item in sampleDict.values(), this may be useful:

print sampleDict.values()[0].keys()[0]

If you use the example you gave in the question, I mean:

sampleDict = {
              'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
              'Grapes':{'Arabian':'25','Indian':'20'}
              }

The output for the first code is:

American
Indian

And the output for the second code is:

American

EDIT 1:

Above code examples does not work for version 3 and above of python; since from version 3, python changed the type of output of methods keys and values from list to dict_values. Type dict_values is not accepting indexing, but it is iterable. So you need to change above codes as below:

First One:

for key, value in sampleDict.items():
    print(list(value.keys())[0])

Second One:

print(list(list(sampleDict.values())[0].keys())[0])

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

Why not use tables for layout in HTML?

This isn't the definitive argument, by any means, but with CSS you can take the same markup and change the layout depending on medium, which is a nice advantage. For a print page you can quietly suppress navigation without having to create a printer-friendly page, for example.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

From your output:

no listening sockets available, shutting down

what basically means, that any port in which one apache is going to be listening is already being used by another application.

netstat -punta | grep LISTEN

Will give you a list of all the ports being used and the information needed to recognize which process is so you can kill stop or do whatever you want to do with it.

After doing a nmap of your ip I can see that

80/tcp    open     http

so I guess you sorted it out.

If statement for strings in python?

You want:

answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer == "y" or answer == "Y":
  print("this will do the calculation")
else:
  exit()

Or

answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer in ["y","Y"]:
  print("this will do the calculation")
else:
  exit()

Note:

  1. It's "if", not "If". Python is case sensitive.
  2. Indentation is important.
  3. There is no colon or semi-colon at the end of python commands.
  4. You want raw_input not input; input evals the input.
  5. "or" gives you the first result if it evaluates to true, and the second result otherwise. So "a" or "b" evaluates to "a", whereas 0 or "b" evaluates to "b". See The Peculiar Nature of and and or.

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Python, Matplotlib, subplot: How to set the axis range?

If you know the exact axis you want, then

pylab.ylim([0,1000])

works as answered previously. But if you want a more flexible axis to fit your exact data, as I did when I found this question, then set axis limit to be the length of your dataset. If your dataset is fft as in the question, then add this after your plot command:

length = (len(fft)) pylab.ylim([0,length])

Creating an array of objects in Java

You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:

A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
  • Stream.generate(() -> new A()) is like factory for separate A elements created in a way described by lambda, () -> new A() which is implementation of Supplier<A> - it describe how each new A instances should be created.
  • limit(4) sets amount of elements which stream will generate
  • toArray(A[]::new) (can also be rewritten as toArray(size -> new A[size])) - it lets us decide/describe type of array which should be returned.

For some primitive types you can use DoubleStream, IntStream, LongStream which additionally provide generators like range rangeClosed and few others.

Disable browser cache for entire ASP.NET website

Create a class that inherits from IActionFilter.

public class NoCacheAttribute : ActionFilterAttribute
{  
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

Then put attributes where needed...

[NoCache]
[HandleError]
public class AccountController : Controller
{
    [NoCache]
    [Authorize]
    public ActionResult ChangePassword()
    {
        return View();
    }
}

ValueError when checking if variable is None or numpy.array

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):
    pass

Not too pretty, but it does the job.

Get current date/time in seconds

These JavaScript solutions give you the milliseconds or the seconds since the midnight, January 1st, 1970.

The IE 9+ solution(IE 8 or the older version doesn't support this.):

var timestampInMilliseconds = Date.now();
var timestampInSeconds = Date.now() / 1000; // A float value; not an integer.
    timestampInSeconds = Math.floor(Date.now() / 1000); // Floor it to get the seconds.
    timestampInSeconds = Date.now() / 1000 | 0; // Also you can do floor it like this.
    timestampInSeconds = Math.round(Date.now() / 1000); // Round it to get the seconds.

To get more information about Date.now(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

The generic solution:

// ‘+’ operator makes the operand numeric.
// And ‘new’ operator can be used without the arguments ‘(……)’.
var timestampInMilliseconds = +new Date;
var timestampInSeconds = +new Date / 1000; // A float value; not an intger.
    timestampInSeconds = Math.floor(+new Date / 1000); // Floor it to get the seconds.
    timestampInSeconds = +new Date / 1000 | 0; // Also you can do floor it like this.
    timestampInSeconds = Math.round(+new Date / 1000); // Round it to get the seconds.

Be careful to use, if you don't want something like this case.

if(1000000 < Math.round(1000000.2)) // false.

How to split the screen with two equal LinearLayouts?

Use the layout_weight attribute. The layout will roughly look like this:

<LinearLayout android:orientation="horizontal"
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent">

    <LinearLayout 
        android:layout_weight="1" 
        android:layout_height="fill_parent" 
        android:layout_width="0dp"/>

    <LinearLayout 
        android:layout_weight="1" 
        android:layout_height="fill_parent" 
        android:layout_width="0dp"/>

</LinearLayout>

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

After a few days of struggle, this works for me, and I hope this also works for you.

add this to your CONFIG.XML, top of your code.

<access origin="*" />
<allow-navigation href="*" />

and this, under the platform android.

<edit-config file="app/src/main/AndroidManifest.xml" 
   mode="merge" target="/manifest/application" 
   xmlns:android="http://schemas.android.com/apk/res/android">
     <application android:usesCleartextTraffic="true" />
     <application android:networkSecurityConfig="@xml/network_security_config" />
 </edit-config>
 <resource-file src="resources/android/xml/network_security_config.xml" 
 target="app/src/main/res/xml/network_security_config.xml" />

add the follow code to this file "resources/android/xml/network_security_config.xml".

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">YOUR DOMAIN HERE/IP</domain>
    </domain-config>
</network-security-config>

enter image description here

enter image description here

How to save a bitmap on internal storage

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.

public onClick(View v){

switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
} 
}

OpenCV !_src.empty() in function 'cvtColor' error

Your code can't find the figure or the name of your figure named the by error message. Solution:

import cv2
import numpy as np 
import matplotlib.pyplot as plt 
img=cv2.imread('??.jpg')#solution:img=cv2.imread('haha.jpg')
print(img)

C# code to validate email address

I find this regex to be a good trade off between checking for something more than just the @ mark, and accepting weird edge cases:

^[^@\s]+@[^@\s]+(\.[^@\s]+)+$

It will at least make you put something around the @ mark, and put at least a normal looking domain.

Initializing C dynamic arrays

Instead of using

int * p;
p = {1,2,3};

we can use

int * p;
p =(int[3]){1,2,3};

Java: Convert String to TimeStamp

first convert your date string to date then convert it to timestamp by using following set of line

Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());//instead of date put your converted date
Timestamp myTimeStamp= timestamp;

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

This suggestion is based on pixel manipulation in canvas 2d context.

From MDN:

You can directly manipulate pixel data in canvases at the byte level

To manipulate pixels we'll use two functions here - getImageData and putImageData.

getImageData usage:

var myImageData = context.getImageData(left, top, width, height);

The putImageData syntax:

context.putImageData(myImageData, x, y); 

Where context is your canvas 2d context, and x and y are the position on the canvas.

So to get red green blue and alpha values, we'll do the following:

var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];

Where x is the horizontal offset, y is the vertical offset.

The code making image half-transparent:

var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload  = function() {
   c.drawImage(img, 0, 0);
   var ImageData = c.getImageData(0,0,img.width,img.height);
   for(var i=0;i<img.height;i++)
      for(var j=0;j<img.width;j++)
         ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
   c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';

You can make you own "shaders" - see full MDN article here