Programs & Examples On #Webcontent

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

I got this error loading a http:// URL where the server replied with a redirect to https. After changing the URL I pass to WKWebView to https://... it worked.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You are using an old version of the date picker js. Upgrade datepicker js with latest one.

Replace your bootstrap-datetimepicker.min.js file with this will work..

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.3/js/bootstrap-datetimepicker.min.js"></script>

Direct download from Google Drive using Google Drive API

I would consider downloading from the link, scraping the page that you get to grab the confirmation link, and then downloading that.

If you look at the "download anyway" URL it has an extra confirm query parameter with a seemingly randomly generated token. Since it's random...and you probably don't want to figure out how to generate it yourself, scraping might be the easiest way without knowing anything about how the site works.

You may need to consider various scenarios.

org.apache.jasper.JasperException: Unable to compile class for JSP:

Please remove the servlet jar from web project,as any how, the application/web server already had.

Google drive limit number of download

This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "

This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.

Maybe using the TOR network may help you do your job.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

If you would like to open a servlet with javascript without using 'form' and 'submit' button, here is the following code:

var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
  window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});

Key:

1) button-id : The 'id' tag you give to your button in your html/jsp file.

2) full-servlet-path: The path that shows in the browser when you run the servlet alone

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

Eclipse Build Path Nesting Errors

Here is a simple solution:

  1. Right click the project >> properties >> build path;
  2. In Source tab, Select all the source folders;
  3. Remove them;
  4. Right click on project, Maven >> Update the project.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:

Producer:

@Service
public void FooServiceImpl implements FooService{}

Consumer:

@Autowired
private FooService fooService;

or

@Autowired
private void setFooService(FooService fooService) {}

but not ok if you use it by name:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");

It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined In this case, assigning name to @Service("fooService") would make it work.

scale fit mobile web content using viewport meta tag

Adding style="width:100%;max-width:640px" to the image tag will scale it up to the viewport width, i.e. for larger windows it will look fixed width.

how to load CSS file into jsp

css href link is incorrect. Use relative path instead:

<link href="../css/loginstyle.css" rel="stylesheet" type="text/css">

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

Configure hibernate to connect to database via JNDI Datasource

Apparently, you did it right. But here is a list of things you'll need with examples from a working application:

1) A context.xml file in META-INF, specifying your data source:

<Context>
    <Resource 
        name="jdbc/DsWebAppDB" 
        auth="Container" 
        type="javax.sql.DataSource" 
        username="sa" 
        password="" 
        driverClassName="org.h2.Driver" 
        url="jdbc:h2:mem:target/test/db/h2/hibernate" 
        maxActive="8" 
        maxIdle="4"/>
</Context>

2) web.xml which tells the container that you are using this resource:

<resource-env-ref>
    <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml, but it's similar in hibernate.cfg.xml

<persistence-unit name="dswebapp">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
        <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
    </properties>
</persistence-unit>

Ant build failed: "Target "build..xml" does not exist"

Looks like you called it 'ant build..xml'. ant automatically choose a file build.xml in the current directory, so it is enough to call 'ant' (if a default-target is defined) or 'ant target' (the target named target will be called).

With the call 'ant -p' you get a list of targets defined in your build.xml.

Edit: In the comment is shown the call 'ant -verbose build.xml'. To be correct, this has to be called as 'ant -verbose'. The file build.xml in the current directory will be used automatically. If it is needed to explicitly specify the buildfile (because it's name isn't build.xml for example), you have to specify the buildfile with the '-f'-option: 'ant -verbose -f build.xml'. I hope this helps.

Difference between UTF-8 and UTF-16?

They're simply different schemes for representing Unicode characters.

Both are variable-length - UTF-16 uses 2 bytes for all characters in the basic multilingual plane (BMP) which contains most characters in common use.

UTF-8 uses between 1 and 3 bytes for characters in the BMP, up to 4 for characters in the current Unicode range of U+0000 to U+1FFFFF, and is extensible up to U+7FFFFFFF if that ever becomes necessary... but notably all ASCII characters are represented in a single byte each.

For the purposes of a message digest it won't matter which of these you pick, so long as everyone who tries to recreate the digest uses the same option.

See this page for more about UTF-8 and Unicode.

(Note that all Java characters are UTF-16 code points within the BMP; to represent characters above U+FFFF you need to use surrogate pairs in Java.)

How to get a value from a Pandas DataFrame and not the index and object type

Nobody mentioned it, but you can also simply use loc with the index and column labels.

df.loc[2, 'Letters']
# 'C'

Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.

df.set_index('Numbers').loc[3, 'Letters']

Can't bind to 'routerLink' since it isn't a known property

This problem is because you did not import the module

import {RouterModule} from '@angular/router';

And you must declare this modulce in the import section

   imports:[RouterModule]

PHP - Failed to open stream : No such file or directory

The following PHP settings in php.ini if set to non-existent directory can also raise

PHP Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0

sys_temp_dir
upload_tmp_dir
session.save_path

Grep regex NOT containing string

grep matches, grep -v does the inverse. If you need to "match A but not B" you usually use pipes:

grep "${PATT}" file | grep -v "${NOTPATT}"

Conversion failed when converting the varchar value to data type int in sql

I got the same error message. In my case, it was due to not using quotes.

Although the column was supposed to have only numbers, it was a Varchar column, and one of the rows had a letter in it.

So I was doing this:

select * from mytable where myid = 1234

While I should be doing this:

select * from mytable where myid = '1234'

If the column had all numbers, the conversion would have worked, but not in this case.

How to get text of an input text box during onKeyPress?

Try to concatenate the event charCode to the value you get. Here is a sample of my code:

<input type="text" name="price" onkeypress="return (cnum(event,this))" maxlength="10">
<p id="demo"></p>

js:

function cnum(event, str) {
    var a = event.charCode;
    var ab = str.value + String.fromCharCode(a);
    document.getElementById('demo').innerHTML = ab;
}

The value in ab will get the latest value in the input field.

Configuring so that pip install can work from github

I had similar issue when I had to install from github repo, but did not want to install git , etc.

The simple way to do it is using zip archive of the package. Add /zipball/master to the repo URL:

    $ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
  Downloading master
  Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
  Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...

This way you will make pip work with github source repositories.

Printf long long int in C with GCC?

You can try settings of code::block, there is a complier..., then you select in C mode.

enter image description here

Where do I find the definition of size_t?

Practically speaking size_t represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t. For example things like array sizes should always use size_t's. If you look at the standard containers the ::size() always returns a size_t.

Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".

How do I create a Bash alias?

MacOS Catalina and Above

Apple switched their default shell to zsh, so the config files include ~/.zshenv and ~/.zshrc. This is just like ~/.bashrc, but for zsh. Just edit the file and add what you need; it should be sourced every time you open a new terminal window:

nano ~/.zshenv alias py=python

Then do ctrl+x, y, then enter to save.

This file seems to be executed no matter what (login, non-login, or script), so seems better than the ~/.zshrc file.

High Sierra and earlier

The default shell is bash, and you can edit the file ~/.bash_profile and add aliases:

nano ~/.bash_profile alias py=python

Then ctrl+x, y, and enter to save. See this post for more on these configs. It's a little better to set it up with your alias in ~/.bashrc, then source ~/.bashrc from ~/.bash_profile. In ~/.bash_profile it would then look like:

source ~/.bashrc

Maven skip tests

During maven compilation you can skip test execution by adding following plugin in pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20.1</version>
    <configuration>
         <skipTests>true</skipTests>
    </configuration>
</plugin>

How to get a web page's source code from Java

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

How to get ID of clicked element with jQuery

You just need to remove the hash from the beginning:

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id').substring(1);
    $container.cycle(id); 
    return false; 
}); 

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Have you tried :

hadoop dfs -rmr hdfs://host:port/Navi/MyDir\,\ Name?

Create normal zip file programmatically

.NET has a built functionality for compressing files in the System.IO.Compression namespace. Using this you do not have to take an extra library as a dependency. This functionality is available from .NET 2.0.

Here is the way to do the compressing from the MSDN page I linked:

    public static void Compress(FileInfo fi)
    {
        // Get the stream of the source file.
        using (FileStream inFile = fi.OpenRead())
        {
            // Prevent compressing hidden and already compressed files.
            if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
                    != FileAttributes.Hidden & fi.Extension != ".gz")
            {
                // Create the compressed file.
                using (FileStream outFile = File.Create(fi.FullName + ".gz"))
                {
                    using (GZipStream Compress = new GZipStream(outFile,
                            CompressionMode.Compress))
                    {
                        // Copy the source file into the compression stream.
                        byte[] buffer = new byte[4096];
                        int numRead;
                        while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            Compress.Write(buffer, 0, numRead);
                        }
                        Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                            fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                    }
                }
            }
        }

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

wait process until all subprocess finish?

subprocess.call

Automatically waits , you can also use:

p1.wait()

OnClick vs OnClientClick for an asp:CheckBox?

For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

Convert spark DataFrame column to python list

Let's create the dataframe in question

df_test = spark.createDataFrame(
    [
        (1, 5),
        (2, 9),
        (3, 3),
        (4, 1),
    ],
    ['mvv', 'count']
)
df_test.show()

Which gives

+---+-----+
|mvv|count|
+---+-----+
|  1|    5|
|  2|    9|
|  3|    3|
|  4|    1|
+---+-----+

and then apply rdd.flatMap(f).collect() to get the list

test_list = df_test.select("mvv").rdd.flatMap(list).collect()
print(type(test_list))
print(test_list)

which gives

<type 'list'>
[1, 2, 3, 4]

What is the javascript filename naming convention?

I generally prefer hyphens with lower case, but one thing not yet mentioned is that sometimes it's nice to have the file name exactly match the name of a single module or instantiable function contained within.

For example, I have a revealing module declared with var knockoutUtilityModule = function() {...} within its own file named knockoutUtilityModule.js, although objectively I prefer knockout-utility-module.js.

Similarly, since I'm using a bundling mechanism to combine scripts, I've taken to defining instantiable functions (templated view models etc) each in their own file, C# style, for maintainability. For example, ProductDescriptorViewModel lives on its own inside ProductDescriptorViewModel.js (I use upper case for instantiable functions).

`ui-router` $stateParams vs. $state.params

Another reason to use $state.params is for non-URL based state, which (to my mind) is woefully underdocumented and very powerful.

I just discovered this while googling about how to pass state without having to expose it in the URL and answered a question elsewhere on SO.

Basically, it allows this sort of syntax:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

When is the finalize() method called in Java?

When is the finalize() method called in Java?

The finalize method will be called after the GC detects that the object is no longer reachable, and before it actually reclaims the memory used by the object.

  • If an object never becomes unreachable, finalize() will never be called on it.

  • If the GC doesn't run then finalize() may never be called. (Normally, the GC only runs when the JVM decides that there is likely to enough garbage to make it worthwhile.)

  • It may take more than one GC cycle before the GC determines that a specific object is unreachable. (Java GCs are typically "generational" collectors ...)

  • Once the GC detects an object is unreachable and finalizable, it is places on a finalization queue. Finalization typically occurs asynchronously with the normal GC.

(The JVM spec actually allows a JVM to never run finalizers ... provided that it doesn't reclaim the space used by the objects. A JVM that was implemented this way would be crippled / useless, but it this behavior is "allowed".)

The upshot is that it is unwise to rely on finalization to do things that have to be done in a definite time-frame. It is "best practice" not to use them at all. There should be a better (i.e. more reliable) way to do whatever it is you are trying to do in the finalize() method.

The only legitimate use for finalization is to clean up resources associated with objects that have been lost by application code. Even then, you should try to write the application code so that it doesn't lose the objects in the first place. (For example, use Java 7+ try-with-resources to ensure that close() is always called ...)


I created a test class which writes into a file when the finalize() method is called by overriding it. It is not executed. Can anybody tell me the reason why it is not executing?

It is hard to say, but there are a few possibilities:

  • The object is not garbage collected because it is still reachable.
  • The object is not garbage collected because the GC doesn't run before your test finishes.
  • The object is found by the GC and placed in the finalization queue by the GC, but finalization isn't completed before your test finishes.

Using Mysql in the command line in osx - command not found?

That means /usr/local/mysql/bin/mysql is not in the PATH variable..

Either execute /usr/local/mysql/bin/mysql to get your mysql shell,

or type this in your terminal:

PATH=$PATH:/usr/local/mysql/bin

to add that to your PATH variable so you can just run mysql without specifying the path

Dynamically set value of a file input

I ended up doing something like this for AngularJS in case someone stumbles across this question:

const imageElem = angular.element('#awardImg');

if (imageElem[0].files[0])
    vm.award.imageElem = imageElem;
    vm.award.image = imageElem[0].files[0];

And then:

if (vm.award.imageElem)
    $('#awardImg').replaceWith(vm.award.imageElem);
    delete vm.award.imageElem;

Iterate a list with indexes in Python

Here's another using the zip function.

>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]

How to output (to a log) a multi-level array in a format that is human-readable?

http://php.net/manual/en/function.print-r.php This function can be used to format output,

$output = print_r($array,1);

$output is a string variable, it can be logged like every other string. In pure php you can use trigger_error

Ex. trigger_error($output);

http://php.net/manual/en/function.trigger-error.php

if you need to format it also in html, you can use <pre> tag

How to check if an appSettings key exists?

MSDN: Configuration Manager.AppSettings

if (ConfigurationManager.AppSettings[name] != null)
{
// Now do your magic..
}

or

string s = ConfigurationManager.AppSettings["myKey"];
if (!String.IsNullOrEmpty(s))
{
    // Key exists
}
else
{
    // Key doesn't exist
}

how to create a login page when username and password is equal in html

Doing password checks on client side is unsafe especially when the password is hard coded.

The safest way is password checking on server side, but even then the password should not be transmitted plain text.

Checking the password client side is possible in a "secure way":

  • The password needs to be hashed
  • The hashed password is used as part of a new url

Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).

Google Drive as FTP Server

What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.

The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.

I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.

This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter

Regex date format validation on Java

java.time

The proper (and easy) way to do date/time validation using Java 8+ is to use the java.time.format.DateTimeFormatter class. Using a regex for validation isn't really ideal for dates. For the example case in this question:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

try {
    LocalDate date = formatter.parse(text, LocalDate::from);
} catch (DateTimeParseException e) {
    // Thrown if text could not be parsed in the specified format
}

This code will parse the text, validate that it is a valid date, and also return the date as a LocalDate object. Note that the DateTimeFormatter class has a number of static predefined date formats matching ISO standards if your use case matches any of them.

How to change UIPickerView height

I am working with ios 7, Xcode 5. I was able to adjust the height of date picker indirectly by enclosing it in a view. The container views height can be adjusted.

Excel VBA Password via Hex Editor

I have your answer, as I just had the same problem today:

Someone made a working vba code that changes the vba protection password to "macro", for all excel files, including .xlsm (2007+ versions). You can see how it works by browsing his code.

This is the guy's blog: http://lbeliarl.blogspot.com/2014/03/excel-removing-password-from-vba.html Here's the file that does the work: https://docs.google.com/file/d/0B6sFi5sSqEKbLUIwUTVhY3lWZE0/edit

Pasted from a previous post from his blog:

For Excel 2007/2010 (.xlsm) files do following steps:

  1. Create a new .xlsm file.
  2. In the VBA part, set a simple password (for instance 'macro').
  3. Save the file and exit.
  4. Change file extention to '.zip', open it by any archiver program.
  5. Find the file: 'vbaProject.bin' (in 'xl' folder).
  6. Extract it from archive.
  7. Open the file you just extracted with a hex editor.
  8. Find and copy the value from parameter DPB (value in quotation mark), example: DPB="282A84CBA1CBA1345FCCB154E20721DE77F7D2378D0EAC90427A22021A46E9CE6F17188A". (This value generated for 'macro' password. You can use this DPB value to skip steps 1-8)

  9. Do steps 4-7 for file with unknown password (file you want to unlock).

  10. Change DBP value in this file on value that you have copied in step 8.

    If copied value is shorter than in encrypted file you should populate missing characters with 0 (zero). If value is longer - that is not a problem (paste it as is).

  11. Save the 'vbaProject.bin' file and exit from hex editor.

  12. Replace existing 'vbaProject.bin' file with modified one.
  13. Change extention from '.zip' back to '.xlsm'
  14. Now, open the excel file you need to see the VBA code in. The password for the VBA code will simply be macro (as in the example I'm showing here).

How can I change the color of a Google Maps marker?

With version 3 of the Google Maps API, the easiest way to do this may be by grabbing a custom icon set, like the one that Benjamin Keen has created here:

http://www.benjaminkeen.com/?p=105

If you put all of those icons at the same place as your map page, you can colorize a Marker simply by using the appropriate icon option when creating it:

var beachMarker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: 'brown_markerA.png'
});

This is super-easy, and is the approach I'm using for the project I'm working on currently.

How to bind Events on Ajax loaded Content?

If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!

Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:

$('.parent-element').on('click', '.mylink', function(){
  alert ("new link clicked!");
})

Some more reading on the subject:

can not find module "@angular/material"

import {MatButtonModule} from '@angular/material/button';

Sanitizing user input before adding it to the DOM in Javascript

Since the text that you are escaping will appear in an HTML attribute, you must be sure to escape not only HTML entities but also HTML attributes:

var ESC_MAP = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
};

function escapeHTML(s, forAttribute) {
    return s.replace(forAttribute ? /[&<>'"]/g : /[&<>]/g, function(c) {
        return ESC_MAP[c];
    });
}

Then, your escaping code becomes var user_id = escapeHTML(id, true).

For more information, see Foolproof HTML escaping in Javascript.

Show loading screen when navigating between routes in Angular 2

The current Angular Router provides Navigation Events. You can subscribe to these and make UI changes accordingly. Remember to count in other Events such as NavigationCancel and NavigationError to stop your spinner in case router transitions fail.

app.component.ts - your root component

...
import {
  Router,
  // import as RouterEvent to avoid confusion with the DOM Event
  Event as RouterEvent,
  NavigationStart,
  NavigationEnd,
  NavigationCancel,
  NavigationError
} from '@angular/router'

@Component({})
export class AppComponent {

  // Sets initial value to true to show loading spinner on first load
  loading = true

  constructor(private router: Router) {
    this.router.events.subscribe((e : RouterEvent) => {
       this.navigationInterceptor(e);
     })
  }

  // Shows and hides the loading spinner during RouterEvent changes
  navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      this.loading = true
    }
    if (event instanceof NavigationEnd) {
      this.loading = false
    }

    // Set loading state to false in both of the below events to hide the spinner in case a request fails
    if (event instanceof NavigationCancel) {
      this.loading = false
    }
    if (event instanceof NavigationError) {
      this.loading = false
    }
  }
}

app.component.html - your root view

<div class="loading-overlay" *ngIf="loading">
    <!-- show something fancy here, here with Angular 2 Material's loading bar or circle -->
    <md-progress-bar mode="indeterminate"></md-progress-bar>
</div>

Performance Improved Answer: If you care about performance there is a better method, it is slightly more tedious to implement but the performance improvement will be worth the extra work. Instead of using *ngIf to conditionally show the spinner, we could leverage Angular's NgZone and Renderer to switch on / off the spinner which will bypass Angular's change detection when we change the spinner's state. I found this to make the animation smoother compared to using *ngIf or an async pipe.

This is similar to my previous answer with some tweaks:

app.component.ts - your root component

...
import {
  Router,
  // import as RouterEvent to avoid confusion with the DOM Event
  Event as RouterEvent,
  NavigationStart,
  NavigationEnd,
  NavigationCancel,
  NavigationError
} from '@angular/router'
import {NgZone, Renderer, ElementRef, ViewChild} from '@angular/core'


@Component({})
export class AppComponent {

  // Instead of holding a boolean value for whether the spinner
  // should show or not, we store a reference to the spinner element,
  // see template snippet below this script
  @ViewChild('spinnerElement')
  spinnerElement: ElementRef

  constructor(private router: Router,
              private ngZone: NgZone,
              private renderer: Renderer) {
    router.events.subscribe(this._navigationInterceptor)
  }

  // Shows and hides the loading spinner during RouterEvent changes
  private _navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      // We wanna run this function outside of Angular's zone to
      // bypass change detection
      this.ngZone.runOutsideAngular(() => {
        // For simplicity we are going to turn opacity on / off
        // you could add/remove a class for more advanced styling
        // and enter/leave animation of the spinner
        this.renderer.setElementStyle(
          this.spinnerElement.nativeElement,
          'opacity',
          '1'
        )
      })
    }
    if (event instanceof NavigationEnd) {
      this._hideSpinner()
    }
    // Set loading state to false in both of the below events to
    // hide the spinner in case a request fails
    if (event instanceof NavigationCancel) {
      this._hideSpinner()
    }
    if (event instanceof NavigationError) {
      this._hideSpinner()
    }
  }

  private _hideSpinner(): void {
    // We wanna run this function outside of Angular's zone to
    // bypass change detection,
    this.ngZone.runOutsideAngular(() => {
      // For simplicity we are going to turn opacity on / off
      // you could add/remove a class for more advanced styling
      // and enter/leave animation of the spinner
      this.renderer.setElementStyle(
        this.spinnerElement.nativeElement,
        'opacity',
        '0'
      )
    })
  }
}

app.component.html - your root view

<div class="loading-overlay" #spinnerElement style="opacity: 0;">
    <!-- md-spinner is short for <md-progress-circle mode="indeterminate"></md-progress-circle> -->
    <md-spinner></md-spinner>
</div>

jQuery.each - Getting li elements inside an ul

$(function() {
    $('.phrase .items').each(function(i, items_list){
        var myText = "";

        $(items_list).find('li').each(function(j, li){
            alert(li.text());
        })

        alert(myText);

    });
};

How to output to the console in C++/Windows

You don't necessarily need to make any changes to your code (nor to change the SUBSYSTEM type). If you wish, you also could simply pipe stdout and stderr to a console application (a Windows version of cat works well).

This version of the application is not configured for billing through Google Play

The same will happen if your published version is not the same as the version you're testing on your phone.

For example, uploaded version is android:versionCode="1", and the version you're testing on your phone is android:versionCode="2"

How to push both key and value into an Array in Jquery

There are no keys in JavaScript arrays. Use objects for that purpose.

var obj = {};

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        obj[news.title] = news.link;
    });                      
});

// later:
$.each(obj, function (index, value) {
    alert( index + ' : ' + value );
});

In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).

However, In your case it is not really clear to me why you transfer data from the original object (data.news) at all. Why do you not simply pass a reference to that object around?


You can combine objects and arrays to achieve predictable iteration and key/value behavior:

var arr = [];

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        arr.push({
            title: news.title, 
            link:  news.link
        });
    });                      
});

// later:
$.each(arr, function (index, value) {
    alert( value.title + ' : ' + value.link );
});

How can I quantify difference between two images?

General idea

Option 1: Load both images as arrays (scipy.misc.imread) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference.

Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather than images.

However, there are some decisions to make first.

Questions

You should answer these questions first:

  • Are images of the same shape and dimension?

    If not, you may need to resize or crop them. PIL library will help to do it in Python.

    If they are taken with the same settings and the same device, they are probably the same.

  • Are images well-aligned?

    If not, you may want to run cross-correlation first, to find the best alignment first. SciPy has functions to do it.

    If the camera and the scene are still, the images are likely to be well-aligned.

  • Is exposure of the images always the same? (Is lightness/contrast the same?)

    If not, you may want to normalize images.

    But be careful, in some situations this may do more wrong than good. For example, a single bright pixel on a dark background will make the normalized image very different.

  • Is color information important?

    If you want to notice color changes, you will have a vector of color values per point, rather than a scalar value as in gray-scale image. You need more attention when writing such code.

  • Are there distinct edges in the image? Are they likely to move?

    If yes, you can apply edge detection algorithm first (e.g. calculate gradient with Sobel or Prewitt transform, apply some threshold), then compare edges on the first image to edges on the second.

  • Is there noise in the image?

    All sensors pollute the image with some amount of noise. Low-cost sensors have more noise. You may wish to apply some noise reduction before you compare images. Blur is the most simple (but not the best) approach here.

  • What kind of changes do you want to notice?

    This may affect the choice of norm to use for the difference between images.

    Consider using Manhattan norm (the sum of the absolute values) or zero norm (the number of elements not equal to zero) to measure how much the image has changed. The former will tell you how much the image is off, the latter will tell only how many pixels differ.

Example

I assume your images are well-aligned, the same size and shape, possibly with different exposure. For simplicity, I convert them to grayscale even if they are color (RGB) images.

You will need these imports:

import sys

from scipy.misc import imread
from scipy.linalg import norm
from scipy import sum, average

Main function, read two images, convert to grayscale, compare and print results:

def main():
    file1, file2 = sys.argv[1:1+2]
    # read images as 2D arrays (convert to grayscale for simplicity)
    img1 = to_grayscale(imread(file1).astype(float))
    img2 = to_grayscale(imread(file2).astype(float))
    # compare
    n_m, n_0 = compare_images(img1, img2)
    print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size
    print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size

How to compare. img1 and img2 are 2D SciPy arrays here:

def compare_images(img1, img2):
    # normalize to compensate for exposure difference, this may be unnecessary
    # consider disabling it
    img1 = normalize(img1)
    img2 = normalize(img2)
    # calculate the difference and its norms
    diff = img1 - img2  # elementwise for scipy arrays
    m_norm = sum(abs(diff))  # Manhattan norm
    z_norm = norm(diff.ravel(), 0)  # Zero norm
    return (m_norm, z_norm)

If the file is a color image, imread returns a 3D array, average RGB channels (the last array axis) to obtain intensity. No need to do it for grayscale images (e.g. .pgm):

def to_grayscale(arr):
    "If arr is a color image (3D array), convert it to grayscale (2D array)."
    if len(arr.shape) == 3:
        return average(arr, -1)  # average over the last axis (color channels)
    else:
        return arr

Normalization is trivial, you may choose to normalize to [0,1] instead of [0,255]. arr is a SciPy array here, so all operations are element-wise:

def normalize(arr):
    rng = arr.max()-arr.min()
    amin = arr.min()
    return (arr-amin)*255/rng

Run the main function:

if __name__ == "__main__":
    main()

Now you can put this all in a script and run against two images. If we compare image to itself, there is no difference:

$ python compare.py one.jpg one.jpg
Manhattan norm: 0.0 / per pixel: 0.0
Zero norm: 0 / per pixel: 0.0

If we blur the image and compare to the original, there is some difference:

$ python compare.py one.jpg one-blurred.jpg 
Manhattan norm: 92605183.67 / per pixel: 13.4210411116
Zero norm: 6900000 / per pixel: 1.0

P.S. Entire compare.py script.

Update: relevant techniques

As the question is about a video sequence, where frames are likely to be almost the same, and you look for something unusual, I'd like to mention some alternative approaches which may be relevant:

  • background subtraction and segmentation (to detect foreground objects)
  • sparse optical flow (to detect motion)
  • comparing histograms or some other statistics instead of images

I strongly recommend taking a look at “Learning OpenCV” book, Chapters 9 (Image parts and segmentation) and 10 (Tracking and motion). The former teaches to use Background subtraction method, the latter gives some info on optical flow methods. All methods are implemented in OpenCV library. If you use Python, I suggest to use OpenCV = 2.3, and its cv2 Python module.

The most simple version of the background subtraction:

  • learn the average value µ and standard deviation s for every pixel of the background
  • compare current pixel values to the range of (µ-2s,µ+2s) or (µ-s,µ+s)

More advanced versions make take into account time series for every pixel and handle non-static scenes (like moving trees or grass).

The idea of optical flow is to take two or more frames, and assign velocity vector to every pixel (dense optical flow) or to some of them (sparse optical flow). To estimate sparse optical flow, you may use Lucas-Kanade method (it is also implemented in OpenCV). Obviously, if there is a lot of flow (high average over max values of the velocity field), then something is moving in the frame, and subsequent images are more different.

Comparing histograms may help to detect sudden changes between consecutive frames. This approach was used in Courbon et al, 2010:

Similarity of consecutive frames. The distance between two consecutive frames is measured. If it is too high, it means that the second frame is corrupted and thus the image is eliminated. The Kullback–Leibler distance, or mutual entropy, on the histograms of the two frames:

$$ d(p,q) = \sum_i p(i) \log (p(i)/q(i)) $$

where p and q are the histograms of the frames is used. The threshold is fixed on 0.2.

How to create a windows service from java app

it's simple as you have to put shortcut in

Windows 7 C:\users\All Users\Start Menu\Programs\Startup(Admin) or User home directory(%userProfile%)

Windows 10 : In Run shell:startup

in it's property -> shortcut -> target - > java.exe -jar D:\..\runJar.jar

NOTE: This will run only after you login


With Admin Right

sc create serviceName binpath= "java.exe -jar D:\..\runJar.jar" Will create windows service

if you get timeout use cmd /c D:\JAVA7~1\jdk1.7.0_51\bin\java.exe -jar d:\jenkins\jenkins.war but even with this you'll get timeout but in background java.exe will be started. Check in task manager

NOTE: This will run at windows logon start-up(before sign-in, Based on service 'Startup Type')

Detailed explanation of creating windows service

Select n random rows from SQL Server table

select * from table where id in ( select id from table order by random() limit ((select count(*) from table)*55/100))

// to select 55 percent of rows randomly

Removing body margin in CSS

I found this problem continued even when setting the BODY MARGIN to zero.

However it turns out there is an easy fix. All you need to do is give your HEADER tag a 1px border, aswell as setting the BODY MARGIN to zero, as shown below.

body { margin:0px; }

header { border:1px black solid; }

You may also need to change the MARGIN to zero for any H1, H2, etc. elements you have within your HEADER div. This will get rid of any extra space which may show around the text.

Not sure why this works, but I use Chrome browser. Obviously you can also change the colour of the border to match your header colour.

Auto line-wrapping in SVG text

Here's an alternative:

<svg ...>
  <switch>
    <g requiredFeatures="http://www.w3.org/Graphics/SVG/feature/1.2/#TextFlow">
      <textArea width="200" height="auto">
       Text goes here
      </textArea>
    </g>
    <foreignObject width="200" height="200" 
     requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
      <p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
    </foreignObject>
    <text x="20" y="20">No automatic linewrapping.</text>
  </switch>
</svg>

Noting that even though foreignObject may be reported as being supported with that featurestring, there's no guarantee that HTML can be displayed because that's not required by the SVG 1.1 specification. There is no featurestring for html-in-foreignobject support at the moment. However, it is still supported in many browsers, so it's likely to become required in the future, perhaps with a corresponding featurestring.

Note that the 'textArea' element in SVG Tiny 1.2 supports all the standard svg features, e.g advanced filling etc, and that you can specify either of width or height as auto, meaning that the text can flow freely in that direction. ForeignObject acts as clipping viewport.

Note: while the above example is valid SVG 1.1 content, in SVG 2 the 'requiredFeatures' attribute has been removed, which means the 'switch' element will try to render the first 'g' element regardless of having support for SVG 1.2 'textArea' elements. See SVG2 switch element spec.

How return error message in spring mvc @Controller

return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);

pandas get column average/mean

Do note that it needs to be in the numeric data type in the first place.

 import pandas as pd
 df['column'] = pd.to_numeric(df['column'], errors='coerce')

Next find the mean on one column or for all numeric columns using describe().

df['column'].mean()
df.describe()

Example of result from describe:

          column 
count    62.000000 
mean     84.678548 
std     216.694615 
min      13.100000 
25%      27.012500 
50%      41.220000 
75%      70.817500 
max    1666.860000

How do I syntax check a Bash script without running it?

I also enable the 'u' option on every bash script I write in order to do some extra checking:

set -u 

This will report the usage of uninitialized variables, like in the following script 'check_init.sh'

#!/bin/sh
set -u
message=hello
echo $mesage

Running the script :

$ check_init.sh

Will report the following :

./check_init.sh[4]: mesage: Parameter not set.

Very useful to catch typos

RegExp in TypeScript

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

Sending HTML email using Python

Actually, yagmail took a bit different approach.

It will by default send HTML, with automatic fallback for incapable email-readers. It is not the 17th century anymore.

Of course, it can be overridden, but here goes:

import yagmail
yag = yagmail.SMTP("[email protected]", "mypassword")

html_msg = """<p>Hi!<br>
              How are you?<br>
              Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

yag.send("[email protected]", "the subject", html_msg)

For installation instructions and many more great features, have a look at the github.

How do I see the extensions loaded by PHP?

Are you looking for a particular extension? In your phpinfo();, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.

Usually in phpinfo() it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.

Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

What is this date format? 2011-08-12T20:17:46.384Z

You can use the following example.

    String date = "2011-08-12T20:17:46.384Z";

    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

    String outputPattern = "yyyy-MM-dd HH:mm:ss";

    LocalDateTime inputDate = null;
    String outputDate = null;


    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);

    inputDate = LocalDateTime.parse(date, inputFormatter);
    outputDate = outputFormatter.format(inputDate);

    System.out.println("inputDate: " + inputDate);
    System.out.println("outputDate: " + outputDate);

How to truncate the time on a DateTime object in Python?

To get a midnight corresponding to a given datetime object, you could use datetime.combine() method:

>>> from datetime import datetime, time
>>> dt = datetime.utcnow()
>>> dt.date()
datetime.date(2015, 2, 3)
>>> datetime.combine(dt, time.min)
datetime.datetime(2015, 2, 3, 0, 0)

The advantage compared to the .replace() method is that datetime.combine()-based solution will continue to work even if datetime module introduces the nanoseconds support.

tzinfo can be preserved if necessary but the utc offset may be different at midnight e.g., due to a DST transition and therefore a naive solution (setting tzinfo time attribute) may fail. See How do I get the UTC time of “midnight” for a given timezone?

error: request for member '..' in '..' which is of non-class type

Foo foo2();

change to

Foo foo2;

You get the error because compiler thinks of

Foo foo2()

as of function declaration with name 'foo2' and the return type 'Foo'.

But in that case If we change to Foo foo2 , the compiler might show the error " call of overloaded ‘Foo()’ is ambiguous".

Can I open a dropdownlist using jQuery

No you can't.

You can change the size to make it larger... similar to Dreas idea, but it is the size you need to change.

<select id="countries" size="6">
  <option value="1">Country 1</option>
  <option value="2">Country 2</option>
  <option value="3">Country 3</option>
  <option value="4">Country 4</option>
  <option value="5">Country 5</option>
  <option value="6">Country 6</option>
</select>

Replace all 0 values to NA

Replacing all zeroes to NA:

df[df == 0] <- NA



Explanation

1. It is not NULL what you should want to replace zeroes with. As it says in ?'NULL',

NULL represents the null object in R

which is unique and, I guess, can be seen as the most uninformative and empty object.1 Then it becomes not so surprising that

data.frame(x = c(1, NULL, 2))
#   x
# 1 1
# 2 2

That is, R does not reserve any space for this null object.2 Meanwhile, looking at ?'NA' we see that

NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw.

Importantly, NA is of length 1 so that R reserves some space for it. E.g.,

data.frame(x = c(1, NA, 2))
#    x
# 1  1
# 2 NA
# 3  2

Also, the data frame structure requires all the columns to have the same number of elements so that there can be no "holes" (i.e., NULL values).

Now you could replace zeroes by NULL in a data frame in the sense of completely removing all the rows containing at least one zero. When using, e.g., var, cov, or cor, that is actually equivalent to first replacing zeroes with NA and setting the value of use as "complete.obs". Typically, however, this is unsatisfactory as it leads to extra information loss.

2. Instead of running some sort of loop, in the solution I use df == 0 vectorization. df == 0 returns (try it) a matrix of the same size as df, with the entries TRUE and FALSE. Further, we are also allowed to pass this matrix to the subsetting [...] (see ?'['). Lastly, while the result of df[df == 0] is perfectly intuitive, it may seem strange that df[df == 0] <- NA gives the desired effect. The assignment operator <- is indeed not always so smart and does not work in this way with some other objects, but it does so with data frames; see ?'<-'.


1 The empty set in the set theory feels somehow related.
2 Another similarity with the set theory: the empty set is a subset of every set, but we do not reserve any space for it.

Getting request payload from POST request in Java servlet

Java 8 streams

String body = request.getReader().lines()
    .reduce("", (accumulator, actual) -> accumulator + actual);

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

Notepad++ add to every line

Simply in the "Find what:" field, type \r. This means "Ends of the Row". In the "Replace with:" field, you put what you want for instance .xml

if you have several lines, and you are aiming to add that text to the end of the each line, you need to markup the option ". matches newline" in the "Search Mode" group box.

Example:

You have a file name list, but you want to add an extension like .xml. This would be what you need to do and Bang! One shot!:

See the image here

In python, what is the difference between random.uniform() and random.random()?

The difference is in the arguments. It's very common to generate a random number from a uniform distribution in the range [0.0, 1.0), so random.random() just does this. Use random.uniform(a, b) to specify a different range.

How can I reconcile detached HEAD with master/origin?

Instead of doing git checkout origin/master

just do git checkout master

then git branch will confirm your branch.

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

Well no, from an iOS developer prospective, there are two links that I know of that will open the Maps app on the iPhone

On iOS 5 and lower: http://maps.apple.com?q=xxxx

On iOS 6 and up: http://maps.google.com?q=xxxx

And that's only on Safari. Chrome will direct you to Google Maps webpage.

Other than that you'll need to use a URL scheme that basically beats the purpose because no android will know that protocol.

You might want to know, Why Safari opens the Maps app and Chrome directs me to a webpage?

Well, because safari is the build in browser made by apple and can detect the URL above. Chrome is "just another app" and must comply to the iOS Ecosystem. Therefor the only way for it to communicate with other apps is by using URL schemes.

Iterate over object in Angular

Angular 2.x && Angular 4.x do not support this out of the box

You can use this two pipes to iterate either by key or by value.

Keys pipe:

import {Pipe, PipeTransform} from '@angular/core'

@Pipe({
  name: 'keys',
  pure: false
})
export class KeysPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value)
  }
}

Values pipe:

import {Pipe, PipeTransform} from '@angular/core'

@Pipe({
  name: 'values',
  pure: false
})
export class ValuesPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => value[key])
  }
}

How to use:

let data = {key1: 'value1', key2: 'value2'}

<div *ngFor="let key of data | keys"></div>
<div *ngFor="let value of data | values"></div>

How to read lines of a file in Ruby

how about gets ?

myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
 //do stuff with line
end

Insert/Update Many to Many Entity Framework . How do I do it?

I wanted to add my experience on that. Indeed EF, when you add an object to the context, it changes the state of all the children and related entities to Added. Although there is a small exception in the rule here: if the children/related entities are being tracked by the same context, EF does understand that these entities exist and doesn't add them. The problem happens when for example, you load the children/related entities from some other context or a web ui etc and then yes, EF doesn't know anything about these entities and goes and adds all of them. To avoid that, just get the keys of the entities and find them (e.g. context.Students.FirstOrDefault(s => s.Name == "Alice")) in the same context in which you want to do the addition.

Opening a SQL Server .bak file (Not restoring!)

From SQL Server 2008 SSMS (SQL Server Management Studio), simply:

  1. Connect to your database instance (for example, "localhost\sqlexpress")
  2. Either:

    • a) Select the database you want to restore to; or, alternatively
    • b) Just create a new, empty database to restore to.
  3. Right-click, Tasks, Restore, Database

  4. Device, [...], Add, Browse to your .bak file
  5. Select the backup.
    Choose "overwrite=Y" under options.
    Restore the database
  6. It should say "100% complete", and your database should be on-line.

PS: Again, I emphasize: you can easily do this on a "scratch database" - you do not need to overwrite your current database. But you do need to RESTORE.

PPS: You can also accomplish the same thing with T-SQL commands, if you wished to script it.

How can I read the contents of an URL with Python?

None of these answers are very good for Python 3 (tested on latest version at the time of this post).

This is how you do it...

import urllib.request

try:
   with urllib.request.urlopen('http://www.python.org/') as f:
      print(f.read().decode('utf-8'))
except urllib.error.URLError as e:
   print(e.reason)

The above is for contents that return 'utf-8'. Remove .decode('utf-8') if you want python to "guess the appropriate encoding."

Documentation: https://docs.python.org/3/library/urllib.request.html#module-urllib.request

Clearing the terminal screen?

the best way I can think of is using processing there are a few introductions on the net like displaying serial data, arduino graph and arduino radar
Since Arduino is based on processing its not that hard to learn

How to find server name of SQL Server Management Studio

start -> CMD -> (Write comand) SQLCMD -L first line is Server name if Server name is (local) Server name is : YourPcName\SQLEXPRESS

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Lets see, numeric (3,2). That means you have 3 places for data and two of them are to the right of the decimal leaving only one to the left of the decimal. 15 has two places to the left of the decimal. BTW if you might have 100 as a value I'd increase that to numeric (5, 2)

How to test if a string is basically an integer in quotes using Ruby

Expanding on @rado's answer above one could also use a ternary statement to force the return of true or false booleans without the use of double bangs. Granted, the double logical negation version is more terse, but probably harder to read for newcomers (like me).

class String
  def is_i?
     self =~ /\A[-+]?[0-9]+\z/ ? true : false
  end
end

Can I update a component's props in React.js?

Props can change when a component's parent renders the component again with different properties. I think this is mostly an optimization so that no new component needs to be instantiated.

C++ cout hex values?

There are different kinds of flags & masks you can use as well. Please refer http://www.cplusplus.com/reference/iostream/ios_base/setf/ for more information.

#include <iostream>
using namespace std;

int main()
{
    int num = 255;
    cout.setf(ios::hex, ios::basefield);
    cout << "Hex: " << num << endl;

    cout.unsetf(ios::hex);
    cout << "Original format: " << num << endl;

    return 0;
}

How can I make a DateTimePicker display an empty string?

The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.

dateTimePicker1.Value = DateTime.Now;
dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker1.ShowCheckBox=true;
dateTimePicker1.Checked=false;


dateTimePicker2.Value = DateTime.Now;
dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker2.ShowCheckBox=true;
dateTimePicker2.Checked=false;

the value changed event function

        void Dtp_ValueChanged(object sender, EventArgs e)
        {
            if(((DateTimePicker)sender).ShowCheckBox==true)
            {
                if(((DateTimePicker)sender).Checked==false)
                {
                    ((DateTimePicker)sender).CustomFormat = " ";
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
                }
                else
                {
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
                }
            }
            else
            {
                ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
            }
        }

When unchecked enter image description here

When checked enter image description here

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

get parent's view from a layout

The RelativeLayout (i.e. the ViewParent) should have a resource Id defined in the layout file (for example, android:id=@+id/myParentViewId). If you don't do that, the call to getId will return null. Look at this answer for more info.

Trigger event when user scroll to specific element - with jQuery

Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.

Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.

function elementInView(el) {
  // The vertical distance between the top of the page and the top of the element.
  var elementOffset = $(el).offset().top;
  // The height of the element, including padding and borders.
  var elementOuterHeight = $(el).outerHeight();
  // Height of the window without margins, padding, borders.
  var windowHeight = $(window).height();
  // The vertical distance between the top of the page and the top of the viewport.
  var scrollOffset = $(this).scrollTop();

  if (elementOuterHeight < windowHeight) {
    // Element is smaller than viewport.
    if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
      // Element is completely inside viewport, reveal the element!
      return true;
    }
  } else {
    // Element is larger than the viewport, handle visibility differently.
    // Consider it visible as soon as it's top half has filled the viewport.
    if (scrollOffset > elementOffset) {
      // The top of the viewport has touched the top of the element, reveal the element!
      return true;
    }
  }
  return false;
}

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

What does "async: false" do in jQuery.ajax()?

Setting async to false means the instructions following the ajax request will have to wait for the request to complete. Below is one case where one have to set async to false, for the code to work properly.

var phpData = (function get_php_data() {
  var php_data;
  $.ajax({
    url: "http://somesite/v1/api/get_php_data",
    async: false, 
    //very important: else php_data will be returned even before we get Json from the url
    dataType: 'json',
    success: function (json) {
      php_data = json;
    }
  });
  return php_data;
})();

Above example clearly explains the usage of async:false

By setting it to false, we have made sure that once the data is retreived from the url ,only after that return php_data; is called

Reading a binary file with python

import pickle
f=open("filename.dat","rb")
try:
    while True:
        x=pickle.load(f)
        print x
except EOFError:
    pass
f.close()

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

What's the most efficient way to erase duplicates and sort a vector?

You need to sort it before you call unique because unique only removes duplicates that are next to each other.

edit: 38 seconds...

ReportViewer Client Print Control "Unable to load client print control"?

Unable to load Client Print Control!
Everytime, clients wanted to print report by clicking the button print on their report viewer, they always got this error message.

I had spent nearly two weeks to fix this problem.
My environment is:
- Window Server 2003 Standard Edition R2
- Report Server Version 10.X.X.X
- Clients with windowXP SP3
My Solution is:
- Replacing the CAP file (RSClientPrint-x86.cab) in C\Program Files\Microsoft SQL
Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin\
- Extract the RSClientPrint-x86.cab and destribute it to clients.


Hear is the CAB file: https://sites.google.com/site/narithsite/Home/RSClientPrint-x86.cab?attredirects=0&d=1

Convert time span value to format "hh:mm Am/Pm" using C#

You can add the TimeSpan to a DateTime, for example:

TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");

Demo: http://ideone.com/veJ6tT

04:00 PM

Standard Date and Time Format Strings

How to color the Git console?

Add to your .gitconfig file next code:

[color]
    ui = auto
[color "branch"]
    current = yellow reverse
    local = yellow
    remote = green
[color "diff"]
    meta = yellow bold
    frag = magenta bold
    old = red bold
    new = green bold
[color "status"]
    added = yellow
    changed = green
    untracked = cyan

Adding system header search path to Xcode

Follow up to Eonil's answer related to project level settings. With the target selected and the Build Settings tab selected, there may be no listing under Search Paths for Header Search Paths. In this case, you can change to "All" from "Basic" in the search bar and Header Search Paths will show up in the Search Paths section.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

ORACLE_HOME needs to be at the top level of the Oracle directory structure for the database installation. From that point, Oracle knows how to find all the other files it needs. For example, the error message you get is because Oracle can't locate the message files to report errors with (should be in the various mesg directories below the oracle home. Instead of the above value you give, I would try

export ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0

How to get the full url in Express?

You can use this function in the route like this

app.get('/one/two', function (req, res) {
    const url = getFullUrl(req);
}

/**
 * Gets the self full URL from the request
 * 
 * @param {object} req Request
 * @returns {string} URL
 */
const getFullUrl = (req) => `${req.protocol}://${req.headers.host}${req.originalUrl}`;

req.protocol will give you http or https, req.headers.host will give you the full host name like www.google.com, req.originalUrl will give the rest pathName(in your case /one/two)

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

Create a Bitmap/Drawable from file path

here is a solution:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

What is null in Java?

Null in Java(tm)

In C and C++, "NULL" is a constant defined in a header file, with a value like:

    0

or:

    0L

or:

    ((void*)0)

depending on the compiler and memory model options. NULL is not, strictly speaking, part of C/C++ itself.

In Java(tm), "null" is not a keyword, but a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type.

Give column name when read csv file pandas

we can do it with a single line of code.

 user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)

Python: Checking if a 'Dictionary' is empty doesn't seem to work

A dictionary can be automatically cast to boolean which evaluates to False for empty dictionary and True for non-empty dictionary.

if myDictionary: non_empty_clause()
else: empty_clause()

If this looks too idiomatic, you can also test len(myDictionary) for zero, or set(myDictionary.keys()) for an empty set, or simply test for equality with {}.

The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.

  1. The return False statement is indented one level too deep. It should be outside the for loop and at the same level as the for statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives.
  2. If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives.
  3. Let us say you correct the indentation of the return False statement and bring it outside the for loop. Then what you get is the boolean OR of all the keys, or False if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.

myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

Here is my extension method for Control, using LINQ, as an adaptation of @PsychoCoder version:

It takes a list of type instead that allows you to not need multiple calls of GetAll to get what you want. I currently use it as an overload version.

public static IEnumerable<Control> GetAll(this Control control, IEnumerable<Type> filteringTypes)
{
    var ctrls = control.Controls.Cast<Control>();

    return ctrls.SelectMany(ctrl => GetAll(ctrl, filteringTypes))
                .Concat(ctrls)
                .Where(ctl => filteringTypes.Any(t => ctl.GetType() == t));
}

Usage:

//   The types you want to select
var typeToBeSelected = new List<Type>
{
    typeof(TextBox)
    , typeof(MaskedTextBox)
    , typeof(Button)
};

//    Only one call
var allControls = MyControlThatContainsOtherControls.GetAll(typeToBeSelected);

//    Do something with it
foreach(var ctrl in allControls)
{
    ctrl.Enabled = true;
}

Set select option 'selected', by value

Try this. Simple yet effective javaScript + jQuery the lethal combo.

SelectComponent :

<select id="YourSelectComponentID">
            <option value="0">Apple</option>
            <option value="2">Banana</option>
            <option value="3">Cat</option>
            <option value="4">Dolphin</option>
</select>

Selection :

document.getElementById("YourSelectComponentID").value = 4;

Now your option 4 will be selected. You can do this, to select the values on start by default.

$(function(){
   document.getElementById("YourSelectComponentID").value = 4;
});

or create a simple function put the line in it and call the function on anyEvent to select the option

A mixture of jQuery + javaScript does the magic....

How do I display an alert dialog on Android?

This is a basic sample of how to create an Alert Dialog :

AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Dialog on Android");
dialog.setMessage("Are you sure you want to delete this entry?" );
dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        //Action for "Delete".
    }
})
        .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            //Action for "Cancel".
            }
        });

final AlertDialog alert = dialog.create();
alert.show();

enter image description here

Go Back to Previous Page

You can use a link to invoke history.go(-1) in Javascript, which is essentially equivalent to clicking the Back button. Ideally, however, it'd be better to just create a link back to the URL from whence the user was posted to the form - that way the proper "flow" of history is preserved and the user doesn't wonder why they have something to click "Forward" to which is actually just submitting the form again.

Reading Email using Pop3 in C#

You can also try Mail.dll mail component, it has SSL support, unicode, and multi-national email support:

using(Pop3 pop3 = new Pop3())
{
    pop3.Connect("mail.host.com");           // Connect to server and login
    pop3.Login("user", "password");

    foreach(string uid in pop3.GetAll())
    {
        IMail email = new MailBuilder()
            .CreateFromEml(pop3.GetMessageByUID(uid));
          Console.WriteLine( email.Subject );
    }
    pop3.Close(false);      
}

You can download it here at https://www.limilabs.com/mail

Please note that this is a commercial product I've created.

What is the most efficient way to loop through dataframes with pandas?

The newest versions of pandas now include a built-in function for iterating over rows.

for index, row in df.iterrows():

    # do some logic here

Or, if you want it faster use itertuples()

But, unutbu's suggestion to use numpy functions to avoid iterating over rows will produce the fastest code.

GitHub - List commits by author

Just add ?author=<emailaddress> or ?author=<githubUserName> to the url when viewing the "commits" section of a repo.

The response content cannot be parsed because the Internet Explorer engine is not available, or

It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.

But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.

So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

Transform char array into String

Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.

This worked for me:

char yyy[6];

String xxx;

yyy[0]='h';

yyy[1]='e';

yyy[2]='l';

yyy[3]='l';

yyy[4]='o';

yyy[5]='\0';

xxx=String(yyy);

How to work offline with TFS

I just wanted to include a link to a resolution to an issue I was having with VS2008 and TFS08.

I accidently opened my solution without being connected to my network and was not able to get it "back the way it was" and had to rebind every time I openned.

I found the solution here; http://www.fkollmann.de/v2/post/Visual-Studio-2008-refuses-to-bind-to-TFS-or-to-open-solution-source-controlled.aspx

Basically, you need to open the "Connect to Team Foundation Server" and then "Servers..." once there, Delete/Remove your server and re-add it. This fixed my issue.

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

Broken references in Virtualenvs

I had a similar issue and i solved it by just rebuilding the virtual environment with virtualenv .

Python Serial: How to use the read or readline function to read more than 1 character at a time

I was reciving some date from my arduino uno (0-1023 numbers). Using code from 1337holiday, jwygralak67 and some tips from other sources:

import serial
import time

ser = serial.Serial(
    port='COM4',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
seq = []
count = 1

while True:
    for c in ser.read():
        seq.append(chr(c)) #convert from ANSII
        joined_seq = ''.join(str(v) for v in seq) #Make a string from array

        if chr(c) == '\n':
            print("Line " + str(count) + ': ' + joined_seq)
            seq = []
            count += 1
            break


ser.close()

Where do alpha testers download Google Play Android apps?

You can use a Google Group and have your alpha testers just join the group. Everything else should just be handled through the Google Play Store App.

Setting an image button in CSS - image:active

This is what worked for me.

<!DOCTYPE html> 
<form action="desired Link">
  <button>  <img src="desired image URL"/>
  </button>
</form>
<style> 

</style>

How to export and import a .sql file from command line with options?

Type the following command to import sql data file:

$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql

In this example, import 'data.sql' file into 'blog' database using vivek as username:

$ mysql -u vivek -p -h localhost blog < data.sql

If you have a dedicated database server, replace localhost hostname with with actual server name or IP address as follows:

$ mysql -u username -p -h 202.54.1.10 databasename < data.sql

To export a database, use the following:

mysqldump -u username -p databasename > filename.sql

Note the < and > symbols in each case.

Aligning two divs side-by-side

This Can be Done by Style Property.

<!DOCTYPE html>
<html>
<head>
<style> 
#main {

  display: flex;
}

#main div {
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 40px;
}
</style>
</head>
<body>

<div id="main">
  <div style="background-color:coral;">Red DIV</div>
  <div style="background-color:lightblue;" id="myBlueDiv">Blue DIV</div>
</div>

</body>
</html>

Its Result will be :

enter image description here

Enjoy... Please Note: This works in Higher version of CSS (>3.0).

How to open a link in new tab using angular?

Use window.open(). It's pretty straightforward !

In your component.html file-

<a (click)="goToLink("www.example.com")">page link</a>

In your component.ts file-

goToLink(url: string){
    window.open(url, "_blank");
}

Set Google Maps Container DIV width and height 100%

I struggled a lot to find the answer.

You don't really need to do anything with body size. All you need to remove the inline style from the map code:

<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.co.uk/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=new+york&amp;aq=&amp;sll=53.546224,-2.106543&amp;sspn=0.02453,0.084543&amp;ie=UTF8&amp;hq=&amp;hnear=New+York,+United+States&amp;t=m&amp;z=10&amp;iwloc=A&amp;output=embed"></iframe><br /><small><a href="https://maps.google.co.uk/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=new+york&amp;aq=&amp;sll=53.546224,-2.106543&amp;sspn=0.02453,0.084543&amp;ie=UTF8&amp;hq=&amp;hnear=New+York,+United+States&amp;t=m&amp;z=10&amp;iwloc=A" style="color:#0000FF;text-align:left">View Larger Map</a></small>

remove all the inline style and add class or ID and then style it the way you like.

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

internet explorer 10 - how to apply grayscale filter?

IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.

However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:

img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

svg {
    background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}

(from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)

Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/

More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx

Java Initialize an int array in a constructor

The best way is not to write any initializing statements. This is because if you write int a[]=new int[3] then by default, in Java all the values of array i.e. a[0], a[1] and a[2] are initialized to 0! Regarding the local variable hiding a field, post your entire code for us to come to conclusion.

JQuery, select first row of table

jQuery is not necessary, you can use only javascript.

<table id="table">
  <tr>...</tr>
  <tr>...</tr>
  <tr>...</tr>
   ......
  <tr>...</tr>
</table>

The table object has a collection of all rows.

var myTable = document.getElementById('table');
var rows =  myTable.rows;
var firstRow = rows[0];

Get controller and action name from within controller?

Try this code

add this override method to controller

protected override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
{
   var actionName = actionExecutingContext.ActionDescriptor.ActionName;
   var controllerName = actionExecutingContext.ActionDescriptor.ControllerDescriptor.ControllerName;
   base.OnActionExecuting(actionExecutingContext);
}

What is the fastest way to create a checksum for large files in C#

You're doing something wrong (probably too small read buffer). On a machine of undecent age (Athlon 2x1800MP from 2002) that has DMA on disk probably out of whack (6.6M/s is damn slow when doing sequential reads):

Create a 1G file with "random" data:

# dd if=/dev/sdb of=temp.dat bs=1M count=1024    
1073741824 bytes (1.1 GB) copied, 161.698 s, 6.6 MB/s

# time sha1sum -b temp.dat
abb88a0081f5db999d0701de2117d2cb21d192a2 *temp.dat

1m5.299s

# time md5sum -b temp.dat
9995e1c1a704f9c1eb6ca11e7ecb7276 *temp.dat

1m58.832s

This is also weird, md5 is consistently slower than sha1 for me (reran several times).

How do I work with dynamic multi-dimensional arrays in C?

Here is working code that defines a subroutine make_3d_array to allocate a multidimensional 3D array with N1, N2 and N3 elements in each dimension, and then populates it with random numbers. You can use the notation A[i][j][k] to access its elements.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


// Method to allocate a 2D array of floats
float*** make_3d_array(int nx, int ny, int nz) {
    float*** arr;
    int i,j;

    arr = (float ***) malloc(nx*sizeof(float**));

    for (i = 0; i < nx; i++) {
        arr[i] = (float **) malloc(ny*sizeof(float*));

        for(j = 0; j < ny; j++) {
            arr[i][j] = (float *) malloc(nz * sizeof(float));
        }
    }

    return arr;
} 



int main(int argc, char *argv[])
{
    int i, j, k;
    size_t N1=10,N2=20,N3=5;

    // allocates 3D array
    float ***ran = make_3d_array(N1, N2, N3);

    // initialize pseudo-random number generator
    srand(time(NULL)); 

    // populates the array with random numbers
    for (i = 0; i < N1; i++){
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                ran[i][j][k] = ((float)rand()/(float)(RAND_MAX));
            }
        }
   }

    // prints values
    for (i=0; i<N1; i++) {
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]);
            }
        }
    }

    free(ran);
}

Remove space above and below <p> tag HTML

Look here: http://www.w3schools.com/tags/tag_p.asp

The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.

you could remove the extra space by using css

p {
   margin: 0px;
   padding: 0px;
}

or use the element <span> which has no default margins and is an inline element.

How to convert UTF-8 byte[] to string?

I saw some answers at this post and it's possible to be considered completed base knowledge, because have a several approaches in C# Programming to resolve the same problem. Only one thing that is necessary to be considered is about a difference between Pure UTF-8 and UTF-8 with B.O.M..

In last week, at my job, I need to develop one functionality that outputs CSV files with B.O.M. and other CSVs with pure UTF-8 (without B.O.M.), each CSV file Encoding type will be consumed by different non-standardized APIs, that one API read UTF-8 with B.O.M. and the other API read without B.O.M.. I need to research the references about this concept, reading "What's the difference between UTF-8 and UTF-8 without B.O.M.?" Stack Overflow discussion and this Wikipedia link "Byte order mark" to build my approach.

Finally, my C# Programming for the both UTF-8 encoding types (with B.O.M. and pure) needed to be similar like this example bellow:

//for UTF-8 with B.O.M., equals shared by Zanoni (at top)
string result = System.Text.Encoding.UTF8.GetString(byteArray);

//for Pure UTF-8 (without B.O.M.)
string result = (new UTF8Encoding(false)).GetString(byteArray);

SVN Repository Search

If you're really desperate, do a dump of the repo (look at "svnadmin dump") and then grep through it. It's not pretty, but you can look around the search results to find the metadata that indicates the file and revision, then check it out for a better look.

Not a good solution, to be sure, but it is free :) SVN provides no feature for searching past checkins (or even past log files, AFAIK).

How can I pass a parameter to a setTimeout() callback?

The answer by David Meister seems to take care of parameters that may change immediately after the call to setTimeout() but before the anonymous function is called. But it's too cumbersome and not very obvious. I discovered an elegant way of doing pretty much the same thing using IIFE (immediately inviked function expression).

In the example below, the currentList variable is passed to the IIFE, which saves it in its closure, until the delayed function is invoked. Even if the variable currentList changes immediately after the code shown, the setInterval() will do the right thing.

Without this IIFE technique, the setTimeout() function will definitely get called for each h2 element in the DOM, but all those calls will see only the text value of the last h2 element.

<script>
  // Wait for the document to load.
  $(document).ready(function() {
  $("h2").each(function (index) {

    currentList = $(this).text();

    (function (param1, param2) {
        setTimeout(function() {
            $("span").text(param1 + ' : ' + param2 );
        }, param1 * 1000);

    })(index, currentList);
  });
</script>

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

In my case - I had to perform below operations:

  1. Move context.xml file from src/java/package to the resource directory (IntelliJ IDE)
  2. Clean target directory.

How to use SortedMap interface in Java?

A TreeMap is probably the most straightforward way of doing this. You use it exactly like a normal Map. i.e.

Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>();
// Put some values in it
mySortedMap.put(1.0f,"One");
mySortedMap.put(0.0f,"Zero");
mySortedMap.put(3.0f,"Three");

// Iterate through it and it'll be in order!
for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) {
    System.out.println(entry.getValue());
} // outputs Zero One Three 

It's worth taking a look at the API docs, http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html to see what else you can do with it.

jQuery set radio button

In my case, radio button value is fetched from database and then set into the form. Following code works for me.

$("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);

Increase heap size in Java

java -d64 -Xms512m -Xmx4g HelloWorld

where, -d64: Will enable 64-bit JVM -Xms512m: Will set initial heap size as 512 MB -Xmx4g: Will set maximum heap size as 4 GB (here java file name is : HelloWorld.java)

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

delete the module which is identified in .Net error message , 1 down vote

In Windows server 2012. Go to ISS -> Modules -> Remove the ServiceModel3-0. (without number worked for me)

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

How to query DATETIME field using only date in Microsoft SQL Server?

you can try this

select * from test where DATEADD(dd, 0, DATEDIFF(dd, 0, date)) = '03/19/2014';

Sort dataGridView columns in C# ? (Windows Form)

There's a method on the DataGridView called "Sort":

this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);

This will programmatically sort your datagridview.

Bootstrap Alert Auto Close

This is a good approach to show animation in and out using jQuery

  $(document).ready(function() {
      // show the alert
      $(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
         $(this).remove(); 
      });
  });

FirebaseInstanceIdService is deprecated

For kotlin I use the following

val fcmtoken = FirebaseMessaging.getInstance().token.await()

and for the extension functions

public suspend fun <T> Task<T>.await(): T {
    // fast path
    if (isComplete) {
        val e = exception
        return if (e == null) {
            if (isCanceled) {
                throw CancellationException("Task $this was cancelled normally.")
            } else {
                @Suppress("UNCHECKED_CAST")
                result as T
            }
        } else {
            throw e
        }
    }

    return suspendCancellableCoroutine { cont ->
        addOnCompleteListener {
            val e = exception
            if (e == null) {
                @Suppress("UNCHECKED_CAST")
                if (isCanceled) cont.cancel() else cont.resume(result as T)
            } else {
                cont.resumeWithException(e)
            }
        }
    }
}

How to get the text of the selected value of a dropdown list?

Hi if you are having dropdownlist like this

<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">

after giving id to dropdownlist you just need to add jquery code like this

function getHTML()
{
      var display=$('#testID option:selected').html();
      alert(display);
}

Git - deleted some files locally, how do I get them from a remote repository

Since git is a distributed VCS, your local repository contains all of the information. No downloading is necessary; you just need to extract the content you want from the repo at your fingertips.

If you haven't committed the deletion, just check out the files from your current commit:

git checkout HEAD <path>

If you have committed the deletion, you need to check out the files from a commit that has them. Presumably it would be the previous commit:

git checkout HEAD^ <path>

but if it's n commits ago, use HEAD~n, or simply fire up gitk, find the SHA1 of the appropriate commit, and paste it in.

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

This problem has been addressed in ASP.Net MVC 3. They now automatically convert underscores in html attribute properties to dashes. They got lucky on this one, as underscores are not legal in html attributes, so MVC can confidently imply that you'd like a dash when you use an underscore.

For example:

@Html.TextBoxFor(vm => vm.City, new { data_bind = "foo" })

will render this in MVC 3:

<input data-bind="foo" id="City" name="City" type="text" value="" />

If you're still using an older version of MVC, you can mimic what MVC 3 is doing by creating this static method that I borrowed from MVC3's source code:

public class Foo {
    public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes) {
        RouteValueDictionary result = new RouteValueDictionary();
        if (htmlAttributes != null) {
            foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes)) {
                result.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
            }
        }
        return result;
    }
}

And then you can use it like this:

<%: Html.TextBoxFor(vm => vm.City, Foo.AnonymousObjectToHtmlAttributes(new { data_bind = "foo" })) %>

and this will render the correct data-* attribute:

<input data-bind="foo" id="City" name="City" type="text" value="" />

Is it necessary to use # for creating temp tables in SQL server?

Yes. You need to prefix the table name with "#" (hash) to create temporary tables.

If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.

"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.

Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005

If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.

They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.

DECLARE @ItemBack1 TABLE
(
 column1 int,
 column2 int,
 someInt int,
 someVarChar nvarchar(50)
);

INSERT INTO @ItemBack1
SELECT column1, 
       column2, 
       someInt, 
       someVarChar 
  FROM table2
 WHERE table2.ID = 7;

More Info on Table Variables: http://odetocode.com/articles/365.aspx

Merging cells in Excel using Apache POI

You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);

example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).

for detail refer BusyDeveloper's Guide

Array Size (Length) in C#

In most of the general cases 'Length' and 'Count' are used.

Array:

int[] myArray = new int[size];
int noOfElements = myArray.Length;

Typed List Array:

List <int> myArray = new List<int>();
int noOfElements = myArray.Count;

Waiting for HOME ('android.process.acore') to be launched

I increased the virtual device SD card size from 500MB to 2GiB, the problem solved.

Creating a new directory in C

Look at stat for checking if the directory exists,

And mkdir, to create a directory.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

You can see the manual of these functions with the man 2 stat and man 2 mkdir commands.

The import org.apache.commons cannot be resolved in eclipse juno

If you got a Apache Maven project, it's easy to use this package in your project. Just specify it in your pom.xml:

<project>
...

    <properties>
        <version.commons-io>2.4</version.commons-io>
    </properties>

    <dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${version.commons-io}</version>
        </dependency>
    </dependencies>

...
</project>

pip3: command not found

You would need to install pip3.

On Linux, the command would be: sudo apt install python3-pip

On Mac, using brew, first brew install python3
Then brew postinstall python3

Try calling pip3 -V to see if it worked.

HTML5 Video autoplay on iPhone

iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The PostgreSQL documentation on Character Types is a good reference for this. They are two different names for the same type.

PHP exec() vs system() vs passthru()

The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...

+----------------+-----------------+----------------+----------------+
|    Command     | Displays Output | Can Get Output | Gets Exit Code |
+----------------+-----------------+----------------+----------------+
| system()       | Yes (as text)   | Last line only | Yes            |
| passthru()     | Yes (raw)       | No             | Yes            |
| exec()         | No              | Yes (array)    | Yes            |
| shell_exec()   | No              | Yes (string)   | No             |
| backticks (``) | No              | Yes (string)   | No             |
+----------------+-----------------+----------------+----------------+
  • "Displays Output" means it streams the output to the browser (or command line output if running from a command line).
  • "Can Get Output" means you can get the output of the command and assign it to a PHP variable.
  • The "exit code" is a special value returned by the command (also called the "return status"). Zero usually means it was successful, other values are usually error codes.

Other misc things to be aware of:

  • The shell_exec() and the backticks operator do the same thing.
  • There are also proc_open() and popen() which allow you to interactively read/write streams with an executing command.
  • Add "2>&1" to the command string if you also want to capture/display error messages.
  • Use escapeshellcmd() to escape command arguments that may contain problem characters.
  • If passing an $output variable to exec() to store the output, if $output isn't empty, it will append the new output to it. So you may need to unset($output) first.

What is the difference between match_parent and fill_parent?

Both have similar functionality only difference is that fill_parent is used up to API level 8 and match_parent is used after API level 8 or higher level.

combining two data frames of different lengths

I think I have come up with a quite shorter solution.. Hope it helps someone.

cbind.na<-function(df1, df2){

  #Collect all unique rownames
  total.rownames<-union(x = rownames(x = df1),y = rownames(x=df2))

  #Create a new dataframe with rownames
  df<-data.frame(row.names = total.rownames)

  #Get absent rownames for both of the dataframe
  absent.names.1<-setdiff(x = rownames(df1),y = rownames(df))
  absent.names.2<-setdiff(x = rownames(df2),y = rownames(df))

  #Fill absents with NAs
  df1.fixed<-data.frame(row.names = absent.names.1,matrix(data = NA,nrow = length(absent.names.1),ncol=ncol(df1)))
  colnames(df1.fixed)<-colnames(df1)
  df1<-rbind(df1,df1.fixed)

  df2.fixed<-data.frame(row.names = absent.names.2,matrix(data = NA,nrow = length(absent.names.2),ncol=ncol(df2)))
  colnames(df2.fixed)<-colnames(df2)
  df2<-rbind(df2,df2.fixed)

  #Finally cbind into new dataframe
  df<-cbind(df,df1[rownames(df),],df2[rownames(df),])
  return(df)

}

IE6/IE7 css border on select element

Using ONLY css is impossbile. In fact, all form elements are impossible to customize to look in the same way on all browsers only with css. You can try niceforms though ;)

In Spring MVC, how can I set the mime type header when using @ResponseBody

Use ResponseEntity instead of ResponseBody. This way you have access to the response headers and you can set the appropiate content type. According to the Spring docs:

The HttpEntity is similar to @RequestBody and @ResponseBody. Besides getting access to the request and response body, HttpEntity (and the response-specific subclass ResponseEntity) also allows access to the request and response headers

The code will look like:

@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
    String json = "jsonResponse";
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true

In Sender

  1. Declare params to be sent. We can send String, Object,…

Sender.xhtml

<f:metadata>
      <f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
  1. We’re going send param ID, it will be included with “includeViewParams=true” in return String of click button event Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrData

Sender.xhtml

<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
      <p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="??" 
      ajax="false"/>
</p:dataTable>

In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID

Sender_MB.java
    public String clickBtnDetail(sender_DTO sender_dto) {
        this._strID = sender_dto.getStrID();
        return "Receiver?faces-redirect=true&includeViewParams=true";
    }

The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*

In Recever

  1. Get viewParam Receiver.xhtml In Receiver we declare f:viewParam to get param from get request (receive), the name of param of receiver must be the same with sender (page)

Receiver.xhtml

<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>

It will get param ID from sender View and assign to receiver_MB._strID

  1. Use viewParam In Receiver, we want to use this param in sql query before the page render, so that we use preRenderView event. We are not going to use constructor because constructor will be invoked before viewParam is received So that we add

Receiver.xhtml

<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />

into f:metadata tag

Receiver.xhtml

<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
            type="preRenderView" />
</f:metadata>

Now we want to use this param in our read database method, it is available to use

Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
        if (FacesContext.getCurrentInstance().isPostback()) {
            return;
        }
        readFromDatabase();
    }
private void readFromDatabase() {
//use _strID to read and set property   
}

Best way to get identity of inserted row?

Even though this is an older thread, there is a newer way to do this which avoids some of the pitfalls of the IDENTITY column in older versions of SQL Server, like gaps in the identity values after server reboots. Sequences are available in SQL Server 2016 and forward which is the newer way is to create a SEQUENCE object using TSQL. This allows you create your own numeric sequence object in SQL Server and control how it increments.

Here is an example:

CREATE SEQUENCE CountBy1  
    START WITH 1  
    INCREMENT BY 1 ;  
GO  

Then in TSQL you would do the following to get the next sequence ID:

SELECT NEXT VALUE FOR CountBy1 AS SequenceID
GO

Here are the links to CREATE SEQUENCE and NEXT VALUE FOR

New Array from Index Range Swift

subscript

extension Array where Element : Equatable {
  public subscript(safe bounds: Range<Int>) -> ArraySlice<Element> {
    if bounds.lowerBound > count { return [] }
    let lower = Swift.max(0, bounds.lowerBound)
    let upper = Swift.max(0, Swift.min(count, bounds.upperBound))
    return self[lower..<upper]
  }
  
  public subscript(safe lower: Int?, _ upper: Int?) -> ArraySlice<Element> {
    let lower = lower ?? 0
    let upper = upper ?? count
    if lower > upper { return [] }
    return self[safe: lower..<upper]
  }
}

returns a copy of this range clamped to the given limiting range.

var arr = [1, 2, 3]
    
arr[safe: 0..<1]    // returns [1]  assert(arr[safe: 0..<1] == [1])
arr[safe: 2..<100]  // returns [3]  assert(arr[safe: 2..<100] == [3])
arr[safe: -100..<0] // returns []   assert(arr[safe: -100..<0] == [])

arr[safe: 0, 1]     // returns [1]  assert(arr[safe: 0, 1] == [1])
arr[safe: 2, 100]   // returns [3]  assert(arr[safe: 2, 100] == [3])
arr[safe: -100, 0]  // returns []   assert(arr[safe: -100, 0] == [])

Using JavaMail with TLS

As a small note, it only started to work for me when I changed smtp to smtps in the examples above per samples from javamail (see smtpsend.java, https://github.com/javaee/javamail/releases/download/JAVAMAIL-1_6_2/javamail-samples.zip, option -S).

My resulting code is as follow:

Properties props=new Properties();
props.put("mail.smtps.starttls.enable","true");
// Use the following if you need SSL
props.put("mail.smtps.socketFactory.port", port);
props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtps.socketFactory.fallback", "false");
props.put("mail.smtps.host", serverList.get(randNum));
Session session = Session.getDefaultInstance(props);

smtpConnectionPool = new SmtpConnectionPool(
    SmtpConnectionFactories.newSmtpFactory(session));
    
final ClosableSmtpConnection transport = smtpConnectionPool.borrowObject();
...
transport.sendMessage(message, message.getAllRecipients());

How to convert a date String to a Date or Calendar object?

tl;dr

LocalDate.parse( "2015-01-02" )

java.time

Java 8 and later has a new java.time framework that makes these other answers outmoded. This framework is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See the Tutorial.

The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them.

LocalDate

Like Joda-Time, java.time has a class LocalDate to represent a date-only value without time-of-day and without time zone.

ISO 8601

If your input string is in the standard ISO 8601 format of yyyy-MM-dd, you can ask that class to directly parse the string with no need to specify a formatter.

The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values.

LocalDate localDate = LocalDate.parse( "2015-01-02" );

Formatter

If you have a different format, specify a formatter from the java.time.format package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a Locale specifying a human language for translation and cultural norms for deciding issues such as period versus comma.

Formatting pattern

Read the DateTimeFormatter class doc for details on the codes used in the format pattern. They vary a bit from the old outmoded java.text.SimpleDateFormat class patterns.

Note how the second argument to the parse method is a method reference, syntax added to Java 8 and later.

String input = "January 2, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "MMMM d, yyyy" , Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );

Dump to console.

System.out.println ( "localDate: " + localDate );

localDate: 2015-01-02

Localize automatically

Or rather than specify a formatting pattern, let java.time localize for you. Call DateTimeFormatter.ofLocalizedDate, and be sure to specify the desired/expected Locale rather than rely on the JVM’s current default which can change at any moment during runtime(!).

String input = "January 2, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG );
formatter = formatter.withLocale ( Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );

Dump to console.

System.out.println ( "input: " + input + " | localDate: " + localDate );

input: January 2, 2015 | localDate: 2015-01-02

How to convert an int to a hex string?

This worked best for me

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

Hiding a form and showing another when a button is clicked in a Windows Forms application

Anything after Application.Run( ) will only be executed when the main form closes.

What you could do is handle the VisibleChanged event as follows:

static Form1 form1;
static Form2 form2;

static void Main()
{

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    form2 = new Form2();
    form1 = new Form1();
    form2.Hide();
    form1.VisibleChanged += OnForm1Changed;
    Application.Run(form1);

}

static void OnForm1Changed( object sender, EventArgs args )
{
    if ( !form1.Visible )
    {
        form2.Show( );
    }
}

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

This happened to me when my package name wasn't represented in the google-services.json file I downloaded. Open your google-services.json file and make sure there is a client_info object that has a package name that corresponds to your manifests package name.

Make sure the package name in your project manifest is exactly the same in google-services.json file

thanks.

Access index of the parent ng-repeat from child ng-repeat

My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.

<div ng-repeat="f in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething($parent.$index)">Add Something</a>
    </div>
  </div>
</div>

How to fix .pch file missing on build?

In case this is happening to you on a server build (AppCenter) and yo uaer using CocoaPods ensure that your Podfile is checked in.

AppCenter only runs the "pod install" command if it finds a Pofile and it DOES NOT find the PODS folder on the files.

I had the folder checked-in, but because git automatically ignores .pch files (check you .gitignore to veryfy this), my .pch weren'nt being checked in.

I sorted my issue by forcing the .pch files to check it, but Deleting the PODS folder should work too, since Appcenter will run the pod install command in that case.

Hoppefully this helps somebody.

How to Correctly Use Lists in R?

Just to add one more point to this:

R does have a data structure equivalent to the Python dict in the hash package. You can read about it in this blog post from the Open Data Group. Here's a simple example:

> library(hash)
> h <- hash( keys=c('foo','bar','baz'), values=1:3 )
> h[c('foo','bar')]
<hash> containing 2 key-value pairs.
  bar : 2
  foo : 1

In terms of usability, the hash class is very similar to a list. But the performance is better for large datasets.

Compare object instances for equality by their attributes

Depending on your specific case, you could do:

>>> vars(x) == vars(y)
True

See Python dictionary from an object's fields

How to insert text with single quotation sql server 2005

You asked how to escape an Apostrophe character (') in SQL Server. All the answers above do an excellent job of explaining that.

However, depending on the situation, the Right single quotation mark character (’) might be appropriate.

(No escape characters needed)

-- Direct insert
INSERT INTO Table1 (Column1) VALUES ('John’s')

• Apostrophe (U+0027)

Ascii Apostrophe on Wikipedia

• Right single quotation mark (U+2019)

Unicode Right single quotation on Wikipedia

Can I change the color of Font Awesome's icon color?

.fa-search{
    color:#fff;
 }

you write that code in css and it would change the color to white or any color you want, you specify it

How to implement zoom effect for image view in android?

Here is one of the most efficient way, it works smoothly:

https://github.com/MikeOrtiz/TouchImageView

Place TouchImageView.java in your project. It can then be used the same as ImageView.

Example:

TouchImageView img = (TouchImageView) findViewById(R.id.img);

If you are using TouchImageView in xml, then you must provide the full package name, because it is a custom view.

Example:

    <com.example.touch.TouchImageView
            android:id="@+id/img”
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

How do I select elements of an array given condition?

Add one detail to @J.F. Sebastian's and @Mark Mikofski's answers:
If one wants to get the corresponding indices (rather than the actual values of array), the following code will do:

For satisfying multiple (all) conditions:

select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] #   1 < x <5

For satisfying multiple (or) conditions:

select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

I know it's late, but I take the original code and change some stuff to control easily the css. So I made a code with the addClass() and the removeClass()

Here the full code : http://jsfiddle.net/e5qaD/4837/

        if( bottom_of_window > bottom_of_object ){
            $(this).addClass('showme');
       }
        if( bottom_of_window < bottom_of_object ){
            $(this).removeClass('showme');

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

How to create custom exceptions in Java?

public class MyException extends Exception {
        // special exception code goes here
}

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
   // something
}

Java: How can I compile an entire directory structure of code ?

I would take Jon's suggestion and use Ant, since this is a pretty complex task.

However, if you are determined to get it all in one line in the Terminal, on Linux you could use the find command. But I don't recommend this at all, since there's no guarantee that, say, Foo.java will be compiled after Bar.java, even though Foo uses Bar. An example would be:

find . -type f -name "*.java" -exec javac {} \;

If all of your classes haven't been compiled yet, if there's one main harness or driver class (basically the one containing your main method), compiling that main class individually should compile most of project, even if they are in different folders, since Javac will try to the best of its abilities to resolve dependency issues.

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

In Linux I've resolved this by deleting all the folders with names starting as ".AndroidStudio" in my home directory and then rerunning the Android Studio.

<hr> tag in Twitter Bootstrap not functioning correctly?

You may want one of these, so to correspond to the Bootstrap layout:

<div class="col-xs-12">
    <hr >
</div>

<!-- or -->

<div class="col-xs-12">
    <hr style="border-style: dashed; border-top-width: 2px;">
</div>

<!-- or -->

<div class="col-xs-12">
    <hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>

Without a DIV grid element included, layout may brake on different devices.

Android Spinner: Get the selected item change event

https://stackoverflow.com/q/1714426/811625

You can avoid the OnItemSelectedListener() being called with a simple check: Store the current selection index in an integer variable and check within the onItemSelected(..) before doing anything.

E.g:

Spinner spnLocale;

spnLocale = (Spinner)findViewById(R.id.spnLocale);

int iCurrentSelection = spnLocale.getSelectedItemPosition();

spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
    if (iCurrentSelection != i){
            // Your code here
    }
    iCurrentSelection = i;
    } 

    public void onNothingSelected(AdapterView<?> adapterView) {
        return;
    } 
}); 

Of cause the iCurrentSelection should be in object scope for this to work!

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Script not served by static file handler on IIS7.5

I know this is an old question, but I've just had this with a 3.5 application on my rebuilt Windows 8 machine and I was still getting this after aspnet_regiis -iru and it turned out the be ASP.NET 3.5 wasn't ticked within Application Development Features (not enough reputation to post an image).

Xcode "Device Locked" When iPhone is unlocked

Recently I have met the Xcode shows "development cannot be enabled while your device is locked, Please unlock your device and reattach. (0xE80000E2).

If your iOS device is already unlocked and connected to mac and still get the error from Xcode 8.1 after upgrading to iOS 10.1.1, then the mac is not trusted by the device.

To fix it, first disconnect device to mac and then go to iOS settings app, and open general->reset->Reset Location & Privacy.

Then connect device to mac and when prompted, set select trust the mac.

Then wait the processing symbol files within your device and mac. After it finished, you can run the project to your device. It will be working.

Can an AWS Lambda function call another

here's a sample code for python,

from boto3 import client as boto3_client
from datetime import datetime
import json

lambda_client = boto3_client('lambda')

def lambda_handler(event, context):
    msg = {"key":"new_invocation", "at": datetime.now()}
    invoke_response = lambda_client.invoke(FunctionName="another_lambda_",
                                           InvocationType='Event',
                                           Payload=json.dumps(msg))
    print(invoke_response)

Btw, you would need to add a policy like this to your lambda role as well

   {
        "Sid": "Stmt1234567890",
        "Effect": "Allow",
        "Action": [
            "lambda:InvokeFunction"
        ],
        "Resource": "*"
    }

TempData keep() vs peek()

Just finished understanding Peek and Keep and had same confusion initially. The confusion arises becauses TempData behaves differently under different condition. You can watch this video which explains the Keep and Peek with demonstration https://www.facebook.com/video.php?v=689393794478113

Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”.

If we understand these 4 points you would see more clarity.Below is a diagram with all 4 conditions, read the third and fourth point which talks about Peek and Keep.

enter image description here

Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.

Condition 2 ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.

string str = TempData["MyData"];

Even if you are displaying it’s a normal read like the code below.

@TempData["MyData"];

Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.

@TempData["MyData"];
TempData.Keep("MyData");

Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.

string str = TempData.Peek("Td").ToString();

Reference :- http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion

Is a Java hashmap search really O(1)?

It depends on the algorithm you choose to avoid collisions. If your implementation uses separate chaining then the worst case scenario happens where every data element is hashed to the same value (poor choice of the hash function for example). In that case, data lookup is no different from a linear search on a linked list i.e. O(n). However, the probability of that happening is negligible and lookups best and average cases remain constant i.e. O(1).

How to put two divs side by side

http://jsfiddle.net/kkobold/qMQL5/

_x000D_
_x000D_
#header {_x000D_
    width: 100%;_x000D_
    background-color: red;_x000D_
    height: 30px;_x000D_
}_x000D_
_x000D_
#container {_x000D_
    width: 300px;_x000D_
    background-color: #ffcc33;_x000D_
    margin: auto;_x000D_
}_x000D_
#first {_x000D_
    width: 100px;_x000D_
    float: left;_x000D_
    height: 300px;_x000D_
        background-color: blue;_x000D_
}_x000D_
#second {_x000D_
    width: 200px;_x000D_
    float: left;_x000D_
    height: 300px;_x000D_
    background-color: green;_x000D_
}_x000D_
#clear {_x000D_
    clear: both;_x000D_
}
_x000D_
<div id="header"></div>_x000D_
<div id="container">_x000D_
    <div id="first"></div>_x000D_
    <div id="second"></div>_x000D_
    <div id="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Swap x and y axis without manually swapping values

  1. Click somewhere on the chart to select it.

  2. You should now see 3 new tabs appear at the top of the screen called "Design", "Layout" and "Format".

  3. Click on the "Design" tab.

  4. There will be a button called "Switch Row/Column" within the "data" group, click it.

React setState not updating state

I had an issue when setting react state multiple times (it always used default state). Following this react/github issue worked for me

const [state, setState] = useState({
  foo: "abc",
  bar: 123
});

// Do this!
setState(prevState => {
  return {
    ...prevState,
    foo: "def"
  };
});
setState(prevState => {
  return {
    ...prevState,
    bar: 456
  };
});

How to create a sub array from another array in Java?

I you are using java prior to version 1.6 use System.arraycopy() instead. Or upgrade your environment.

Python argparse command line flags without arguments

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

Import text file as single character string

readChar doesn't have much flexibility so I combined your solutions (readLines and paste).

I have also added a space between each line:

con <- file("/Users/YourtextFile.txt", "r", blocking = FALSE)
singleString <- readLines(con) # empty
singleString <- paste(singleString, sep = " ", collapse = " ")
close(con)

Converting XDocument to XmlDocument and vice versa

You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.

Putting that into an Extension method to make it easier to work with.

using System;
using System.Xml;
using System.Xml.Linq;

namespace MyTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");

            var xDocument = xmlDocument.ToXDocument();
            var newXmlDocument = xDocument.ToXmlDocument();
            Console.ReadLine();
        }
    }

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using(var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var nodeReader = new XmlNodeReader(xmlDocument))
            {
                nodeReader.MoveToContent();
                return XDocument.Load(nodeReader);
            }
        }
    }
}

Sources:

Case insensitive comparison NSString

A new way to do this. iOS 8

let string: NSString = "Café"
let substring: NSString = "É"

string.localizedCaseInsensitiveContainsString(substring) // true

Minimum Hardware requirements for Android development

I use an i5 processor with 4Gb RAM. It works very well. I feel this is the minimum configuration required to run both eclipse and android avd simultaneously. Just an old processor with high RAM is not sufficient.

MySQL remove all whitespaces from the entire column

To replace all spaces :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, ' ', '')

To remove all tabs characters :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\t', '' )

To remove all new line characters :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\n', '')

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

To remove first and last space(s) of column :

UPDATE `table` SET `col_name` = TRIM(`col_name`)

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim

dlib installation on Windows 10

After spending a lot of time, this comment gave me the right result.

https://github.com/ageitgey/face_recognition/issues/802#issuecomment-544232494

  1. Download Python 3.6.8 and install, make sure you add it to PATH.

  2. Install NumPy, scipy, matplotlib and pandas in your pc/laptop with this command in command prompt:-

    pip install numpy

    pip install scipy

    pip install matplotlib

    pip install pandas

  3. Go to https://pypi.org/project/wheel/#files and right click on filename wheel-0.33.6-py2.py3-none-any.whl (21.6 kB) and copy link address. Then go to your pc/laptop, open command prompt and write this command "python -m pip install" after this command space first then paste the link copied. After install successful go to next step.

  4. Then go this link, https://pypi.org/simple/dlib/ and right click on filename "dlib-19.8.1-cp36-cp36m-win_amd64.whl" then copy link address. Then open command prompt and do the same as step 2 which is, write this command "python -m pip install" after this command space first then paste the link copied. then the dlib will be installed successfully.

  5. After that, type python and enter, then type import dlib to check dlib is installed perfectly. the you can proceed to install face recognition.py which suite for python 3.6.