Programs & Examples On #Touchxml

TouchXML is a lightweight replacement for Cocoa's NSXML* cluster of classes. It is based on the commonly available open source libxml2 library.

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

Get only filename from url in php without any variable values which exist in the url

Try the following code:

For PHP 5.4.0 and above:

$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);

For PHP Version < 5.4.0

$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);

python exception message capturing

There are some cases where you can use the e.message or e.messages.. But it does not work in all cases. Anyway the more safe is to use the str(e)

try:
  ...
except Exception as e:
  print(e.message)

How do I reload a page without a POSTDATA warning in Javascript?

If you use GET method instead of POST then we can't the form filed values. If you use window.opener.location.href = window.opener.location.href; then we can fire the db and we can get the value but only thing is the JSP is not refreshing eventhough the scriplet having the form values.

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

I would just do:

private static Timer timer;
 private static void Main()
 {
   timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
   Console.ReadLine();
 }

  private static void OnCallBack()
  {
    timer.Dispose();
    Thread.Sleep(3000); //doing some long operation
    timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
  }

And ignore the period parameter, since you're attempting to control the periodicy yourself.


Your original code is running as fast as possible, since you keep specifying 0 for the dueTime parameter. From Timer.Change:

If dueTime is zero (0), the callback method is invoked immediately.

Can HTML checkboxes be set to readonly?

you can use this:

<input type="checkbox" onclick="return false;"/>

This works because returning false from the click event stops the chain of execution continuing.

Adding files to java classpath at runtime

Yes I believe it's possible but you might have to implement your own classloader. I have never done it but that is the path I would probably look at.

How to select a radio button by default?

XHTML solution:

<input type="radio" name="imgsel" value="" checked="checked" />

Please note, that the actual value of checked attribute does not actually matter; it's just a convention to assign "checked". Most importantly, strings like "true" or "false" don't have any special meaning.

If you don't aim for XHTML conformance, you can simplify the code to:

<input type="radio" name="imgsel" value="" checked>

Convert HTML to PDF in .NET

Below is an example of converting html + css to PDF using iTextSharp (iTextSharp + itextsharp.xmlworker)

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;


byte[] pdf; // result will be here

var cssText = File.ReadAllText(MapPath("~/css/test.css"));
var html = File.ReadAllText(MapPath("~/css/test.html"));

using (var memoryStream = new MemoryStream())
{
        var document = new Document(PageSize.A4, 50, 50, 60, 60);
        var writer = PdfWriter.GetInstance(document, memoryStream);
        document.Open();

        using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
        {
            using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
            {
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
            }
        }

        document.Close();

        pdf = memoryStream.ToArray();
}

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

java - path to trustStore - set property doesn't work?

Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.

System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");

should be:

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

(Edit: Forget my previous babble...)

Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.

About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <modelname>sController (e.g. "UsersController" is the controller of the model "User").

If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.

Group dataframe and get sum AND count?

If you have lots of columns and only one is different you could do:

In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
                      Organisation Name   Amount
Company Name                                   
Vifor Pharma UK Ltd                  5  4207.93

Note you can then rename the Organisation Name column as you wish.

How can I open Java .class files in a human-readable way?

There is no need to decompile Applet.class. The public Java API classes sourcecode comes with the JDK (if you choose to install it), and is better readable than decompiled bytecode. You can find compressed in src.zip (located in your JDK installation folder).

How to preserve request url with nginx proxy_pass

Note to other people finding this: The heart of the solution to make nginx not manipulate the URL, is to remove the slash at the end of the Copy: proxy_pass directive. http://my_app_upstream vs http://my_app_upstream/ – Hugo Josefson

I found this above in the comments but I think it really should be an answer.

How to calculate the CPU usage of a process by PID in Linux from C?

Take a look at the "pidstat" command, sounds like exactly what you require.

How to change or add theme to Android Studio?

For additional themes I visited https://plugins.jetbrains.com/search?headline=164-theme&tags=Theme I was able to download one of them. I closed all my tabs opened and simply dragged and dropped the jar file. That was the way Android Studio prompted to restart. I tried importing the jar file as mentioned previously but it simply didn't work.

default value for struct member in C

I agree with Als that you can not initialize at time of defining the structure in C. But you can initialize the structure at time of creating instance shown as below.

In C,

 struct s {
        int i;
        int j;
    };

    struct s s_instance = { 10 ,20 };

in C++ its possible to give direct value in definition of structure shown as below

struct s {
    int i;

    s(): i(10)
    {
    }
};

How to round up the result of integer division?

A generic method, whose result you can iterate over may be of interest:

public static Object[][] chunk(Object[] src, int chunkSize) {

    int overflow = src.length%chunkSize;
    int numChunks = (src.length/chunkSize) + (overflow>0?1:0);
    Object[][] dest = new Object[numChunks][];      
    for (int i=0; i<numChunks; i++) {
        dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];
        System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length); 
    }
    return dest;
}

"You have mail" message in terminal, os X

As inspiredlife explained, you can figure out whats happening using mail command.

If you don't want to delete bunch of unrelated / auto-generated messages one by one (like me), simply run the command below to get rid of all messages:

echo -n > /var/mail/yourusername

Why would you use String.Equals over ==?

There is one subtle but very important difference between == and the String.Equals methods:

class Program
{
    static void Main(string[] args)
    {
        CheckEquality("a", "a");
        Console.WriteLine("----------");
        CheckEquality("a", "ba".Substring(1));
    }

    static void CheckEquality<T>(T value1, T value2) where T : class
    {
        Console.WriteLine("value1: {0}", value1);
        Console.WriteLine("value2: {0}", value2);

        Console.WriteLine("value1 == value2:      {0}", value1 == value2);
        Console.WriteLine("value1.Equals(value2): {0}", value1.Equals(value2));

        if (typeof(T).IsEquivalentTo(typeof(string)))
        {
            string string1 = (string)(object)value1;
            string string2 = (string)(object)value2;
            Console.WriteLine("string1 == string2:    {0}", string1 == string2);
        }
    }
}

Produces this output:

value1: a
value2: a
value1 == value2:      True
value1.Equals(value2): True
string1 == string2:    True
----------
value1: a
value2: a
value1 == value2:      False
value1.Equals(value2): True
string1 == string2:    True

You can see that the == operator is returning false to two obviously equal strings. Why? Because the == operator in use in the generic method is resolved to be the op_equal method as defined by System.Object (the only guarantee of T the method has at compile time), which means that it's reference equality instead of value equality.

When you have two values typed as System.String explicitly, then == has a value-equality semantic because the compiler resolves the == to System.String.op_equal instead of System.Object.op_equal.

So to play it safe, I almost always use String.Equals instead to that I always get the value equality semantics I want.

And to avoid NullReferenceExceptions if one of the values is null, I always use the static String.Equals method:

bool true = String.Equals("a", "ba".Substring(1));

How to get featured image of a product in woocommerce

This should do the trick:

<?php
    $product_meta = get_post_meta($post_id);
    echo wp_get_attachment_image( $product_meta['_thumbnail_id'][0], 'full' );
?>

You can change the parameters according to your needs.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Short answer:

const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

Why plt.imshow() doesn't display the image?

The solution was as simple as adding plt.show() at the end of the code snippet:

import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

Creating a new column based on if-elif-else condition

To formalize some of the approaches laid out above:

Create a function that operates on the rows of your dataframe like so:

def f(row):
    if row['A'] == row['B']:
        val = 0
    elif row['A'] > row['B']:
        val = 1
    else:
        val = -1
    return val

Then apply it to your dataframe passing in the axis=1 option:

In [1]: df['C'] = df.apply(f, axis=1)

In [2]: df
Out[2]:
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.

Edit

Here is the vectorized version

df['C'] = np.where(
    df['A'] == df['B'], 0, np.where(
    df['A'] >  df['B'], 1, -1)) 

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Android failed to load JS bundle

Hey I was facing this issue with my react-native bare project, the IOS simulator works fine but android kept giving me this error. here is a possible solution which has worked for me.

step 1, check if the adb device is authorized by running in your terminal : adb devices

if it is unauthorised run the following commands

step 2, sudo adb kill-server step 3, sudo adb start-server

then check if the adb devices command shows list of devices attached emulator-5554 device

instead of unauthorized if it is device instead of unauthorized

step 4, run npx react-native run-android

this has worked in my instance.

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

Creating files in C++

One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:

ofstream reference

For completeness, here's some example code:

// using ofstream constructors.
#include <iostream>
#include <fstream>  

std::ofstream outfile ("test.txt");

outfile << "my text here!" << std::endl;

outfile.close();

You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

Neither BindingResult nor plain target object for bean name available as request attr

Try adding a BindingResult parameter to methods annotated with @RequestMapping which have a @ModelAttribute annotated parameters. After each @ModelAttribute parameter, Spring looks for a BindingResult in the next parameter position (order is important).

So try changing:

@RequestMapping(method = RequestMethod.POST)
public String loadCharts(HttpServletRequest request, ModelMap model, @ModelAttribute("sideForm") Chart chart) 
...

To:

@RequestMapping(method = RequestMethod.POST)
public String loadCharts(@ModelAttribute("sideForm") Chart chart, BindingResult bindingResult, HttpServletRequest request, ModelMap model) 
...

Best solution to protect PHP code without encryption

The only way to really protect your php-applications from other, is to not share the source code. If you post you code somewhere online, or send it to you customers by some medium, other people than you have access to the code.

You could add an unique watermark to every single copy of your code. That way you can trace leaks back to a singe customer. (But will that help you, since the code already are outside of your control?)

Most code I see comes with a licence and maybe a warranty. A line at the top of the script telling people not to alter the script, will maybe be enought. Self; when I find non-open source code, I won't use it in my projects. Maybe I'm a bit dupe, but I expect ppl not to use my none-OSS code!

How to use OAuth2RestTemplate?

I have different approach if you want access token and make call to other resource system with access token in header

Spring Security comes with automatic security: oauth2 properties access from application.yml file for every request and every request has SESSIONID which it reads and pull user info via Principal, so you need to make sure inject Principal in OAuthUser and get accessToken and make call to resource server

This is your application.yml, change according to your auth server:

security:
  oauth2:
    client:
      clientId: 233668646673605
      clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
      accessTokenUri: https://graph.facebook.com/oauth/access_token
      userAuthorizationUri: https://www.facebook.com/dialog/oauth
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://graph.facebook.com/me

@Component
public class OAuthUser implements Serializable {

private static final long serialVersionUID = 1L;

private String authority;

@JsonIgnore
private String clientId;

@JsonIgnore
private String grantType;
private boolean isAuthenticated;
private Map<String, Object> userDetail = new LinkedHashMap<String, Object>();

@JsonIgnore
private String sessionId;

@JsonIgnore
private String tokenType;

@JsonIgnore
private String accessToken;

@JsonIgnore
private Principal principal;

public void setOAuthUser(Principal principal) {
    this.principal = principal;
    init();
}

public Principal getPrincipal() {
    return principal;
}

private void init() {
    if (principal != null) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
        if (oAuth2Authentication != null) {
            for (GrantedAuthority ga : oAuth2Authentication.getAuthorities()) {
                setAuthority(ga.getAuthority());
            }
            setClientId(oAuth2Authentication.getOAuth2Request().getClientId());
            setGrantType(oAuth2Authentication.getOAuth2Request().getGrantType());
            setAuthenticated(oAuth2Authentication.getUserAuthentication().isAuthenticated());

            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) oAuth2Authentication
                    .getDetails();
            if (oAuth2AuthenticationDetails != null) {
                setSessionId(oAuth2AuthenticationDetails.getSessionId());
                setTokenType(oAuth2AuthenticationDetails.getTokenType());

            // This is what you will be looking for 
                setAccessToken(oAuth2AuthenticationDetails.getTokenValue());
            }

    // This detail is more related to Logged-in User
            UsernamePasswordAuthenticationToken userAuthenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
            if (userAuthenticationToken != null) {
                LinkedHashMap<String, Object> detailMap = (LinkedHashMap<String, Object>) userAuthenticationToken.getDetails();
                if (detailMap != null) {
                    for (Map.Entry<String, Object> mapEntry : detailMap.entrySet()) {
                        //System.out.println("#### detail Key = " + mapEntry.getKey());
                        //System.out.println("#### detail Value = " + mapEntry.getValue());
                        getUserDetail().put(mapEntry.getKey(), mapEntry.getValue());
                    }

                }

            }

        }

    }
}


public String getAuthority() {
    return authority;
}

public void setAuthority(String authority) {
    this.authority = authority;
}

public String getClientId() {
    return clientId;
}

public void setClientId(String clientId) {
    this.clientId = clientId;
}

public String getGrantType() {
    return grantType;
}

public void setGrantType(String grantType) {
    this.grantType = grantType;
}

public boolean isAuthenticated() {
    return isAuthenticated;
}

public void setAuthenticated(boolean isAuthenticated) {
    this.isAuthenticated = isAuthenticated;
}

public Map<String, Object> getUserDetail() {
    return userDetail;
}

public void setUserDetail(Map<String, Object> userDetail) {
    this.userDetail = userDetail;
}

public String getSessionId() {
    return sessionId;
}

public void setSessionId(String sessionId) {
    this.sessionId = sessionId;
}

public String getTokenType() {
    return tokenType;
}

public void setTokenType(String tokenType) {
    this.tokenType = tokenType;
}

public String getAccessToken() {
    return accessToken;
}

public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
}

@Override
public String toString() {
    return "OAuthUser [clientId=" + clientId + ", grantType=" + grantType + ", isAuthenticated=" + isAuthenticated
            + ", userDetail=" + userDetail + ", sessionId=" + sessionId + ", tokenType="
            + tokenType + ", accessToken= " + accessToken + " ]";
}

@RestController
public class YourController {

@Autowired
OAuthUser oAuthUser;

// In case if you want to see Profile of user then you this 
@RequestMapping(value = "/profile", produces = MediaType.APPLICATION_JSON_VALUE)
public OAuthUser user(Principal principal) {
    oAuthUser.setOAuthUser(principal);

    // System.out.println("#### Inside user() - oAuthUser.toString() = " + oAuthUser.toString());

    return oAuthUser;
}


@RequestMapping(value = "/createOrder",
        method = RequestMethod.POST,
        headers = {"Content-type=application/json"},
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public FinalOrderDetail createOrder(@RequestBody CreateOrder createOrder) {

    return postCreateOrder_restTemplate(createOrder, oAuthUser).getBody();
}


private ResponseEntity<String> postCreateOrder_restTemplate(CreateOrder createOrder, OAuthUser oAuthUser) {

String url_POST = "your post url goes here";

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Authorization", String.format("%s %s", oAuthUser.getTokenType(), oAuthUser.getAccessToken()));
    headers.add("Content-Type", "application/json");

    RestTemplate restTemplate = new RestTemplate();
    //restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpEntity<String> request = new HttpEntity<String>(createOrder, headers);

    ResponseEntity<String> result = restTemplate.exchange(url_POST, HttpMethod.POST, request, String.class);
    System.out.println("#### post response = " + result);

    return result;
}


}

How do I convert between ISO-8859-1 and UTF-8 in Java?

Regex can also be good and be used effectively (Replaces all UTF-8 characters not covered in ISO-8859-1 with space):

String input = "€Tes¶ti©ng [§] al€l o€f i¶t _ - À ÆÑ with some 9umbers as"
            + " w2921**#$%!@# well Ü, or ü, is a chaŒracte?";
String output = input.replaceAll("[^\\u0020-\\u007e\\u00a0-\\u00ff]", " ");
System.out.println("Input = " + input);
System.out.println("Output = " + output);

Java: Unresolved compilation problem

I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.

Javascript: Extend a Function

There are several ways to go about this, it depends what your purpose is, if you just want to execute the function as well and in the same context, you can use .apply():

function init(){
  doSomething();
}
function myFunc(){
  init.apply(this, arguments);
  doSomethingHereToo();
}

If you want to replace it with a newer init, it'd look like this:

function init(){
  doSomething();
}
//anytime later
var old_init = init;
init = function() {
  old_init.apply(this, arguments);
  doSomethingHereToo();
};

Auto-expanding layout with Qt-Designer

According to the documentation, there needs to be a top level layout set.

A top level layout is necessary to ensure that your widgets will resize correctly when its window is resized. To check if you have set a top level layout, preview your widget and attempt to resize the window by dragging the size grip.

You can set one by clearing the selection and right clicking on the form itself and choosing one of the layouts available in the context menu.

Qt layouts

Disable scrolling in all mobile devices

I suspect most everyone really wants to disable zoom/scroll in order to put together a more app-like experience; because the answers seem to contain elements of solutions for both zooming and scrolling, but nobody's really nailed either one down.

Scrolling

To answer OP, the only thing you seem to need to do to disable scrolling is intercept the window's scroll and touchmove events and call preventDefault and stopPropagation on the events they generate; like so

window.addEventListener("scroll", preventMotion, false);
window.addEventListener("touchmove", preventMotion, false);

function preventMotion(event)
{
    window.scrollTo(0, 0);
    event.preventDefault();
    event.stopPropagation();
}

And in your stylesheet, make sure your body and html tags include the following:

html:
{
    overflow: hidden;
}

body
{
    overflow: hidden;
    position: relative;
    margin: 0;
    padding: 0;
}

Zooming

However, scrolling is one thing, but you probably want to disable zoom as well. Which you do with the meta tag in your markup:

<meta name="viewport" content="user-scalable=no" />

All of these put together give you an app-like experience, probably a best fit for canvas.

(Be wary of the advice of some to add attributes like initial-scale and width to the meta tag if you're using a canvas, because canvasses scale their contents, unlike block elements, and you'll wind up with an ugly canvas, more often than not).

How to insert a large block of HTML in JavaScript?

Template literals may solve your issue as it will allow writing multi-line strings and string interpolation features. You can use variables or expression inside string (as given below). It's easy to insert bulk html in a reader friendly way.

I have modified the example given in question and please see it below. I am not sure how much browser compatible Template literals are. Please read about Template literals here.

_x000D_
_x000D_
var a = 1, b = 2;_x000D_
var div = document.createElement('div');_x000D_
div.setAttribute('class', 'post block bc2');_x000D_
div.innerHTML = `_x000D_
    <div class="parent">_x000D_
        <div class="child">${a}</div>_x000D_
        <div class="child">+</div>_x000D_
        <div class="child">${b}</div>_x000D_
        <div class="child">=</div>_x000D_
        <div class="child">${a + b}</div>_x000D_
    </div>_x000D_
`;_x000D_
document.getElementById('posts').appendChild(div);
_x000D_
.parent {_x000D_
  background-color: blue;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}_x000D_
.post div {_x000D_
  color: white;_x000D_
  font-size: 2.5em;_x000D_
  padding: 20px;_x000D_
}
_x000D_
<div id="posts"></div>
_x000D_
_x000D_
_x000D_

How to verify a method is called two times with mockito verify()

Using the appropriate VerificationMode:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

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

If eclipse Java build path is mapped to 7, 8 and in Project pom.xml Maven properties java.version is mentioned higher Java version(9,10,11, etc..,) than 7,8 you need to update in pom.xml file.

In Eclipse if Java is mapped to Java version 11 and in pom.xml it is mapped to Java version 8. Update Eclipse support to Java 11 by go through below steps in eclipse IDE Help -> Install New Software ->

Paste following link http://download.eclipse.org/eclipse/updates/4.9-P-builds at Work With

or

Add (Popup window will open) ->

Name: Java 11 support Location: http://download.eclipse.org/eclipse/updates/4.9-P-builds

then update Java version in Maven properties of pom.xml file as below

<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>

Finally do right click on project Debug as -> Maven clean, Maven build steps

Python: find position of element in array

You should do:

try:
    value_index = my_list.index(value)
except:
    value_index = -1;

Disabling Minimize & Maximize On WinForm?

How to make form minimize when closing was already answered, but how to remove the minimize and maximize buttons wasn't.
FormBorderStyle: FixedDialog
MinimizeBox: false
MaximizeBox: false

add Shadow on UIView using swift 3

This works for me (Swift 3 and 4)

yourView.layer.shadowColor = UIColor.gray.cgColor
yourView.layer.shadowOpacity = 0.3
yourView.layer.shadowOffset = CGSize.zero
yourView.layer.shadowRadius = 6

Get a Windows Forms control by name in C#

string name = "the_name_you_know";

Control ctn = this.Controls[name];

ctn.Text = "Example...";

How to make an unaware datetime timezone aware in python

I use this statement in Django to convert an unaware time to an aware:

from django.utils import timezone

dt_aware = timezone.make_aware(dt_unaware, timezone.get_current_timezone())

How do I install Python packages in Google's Colab?

You can use !setup.py install to do that.

Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line.

For example: !pip install tensorflow. This will treat that line (here pip install tensorflow) as a command prompt line and not some Python code. However, if you do this without adding the ! preceding the line, it'll throw up an error saying "invalid syntax".

But keep in mind that you'll have to upload the setup.py file to your drive before doing this (preferably into the same folder where your notebook is).

Hope this answers your question :)

Does C have a string type?

C does not have its own String data type like Java.

Only we can declare String datatype in C using character array or character pointer For example :

 char message[10]; 
 or 
 char *message;

But you need to declare at least:

    char message[14]; 

to copy "Hello, world!" into message variable.

  • 13 : length of the "Hello, world!"
  • 1 : for '\0' null character that identifies end of the string

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

How to display HTML tags as plain text

you may use htmlspecialchars()

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Validation to check if password and confirm password are same is not working

function validate()
{
  var a=documents.forms["yourformname"]["yourpasswordfieldname"].value;
  var b=documents.forms["yourformname"]["yourconfirmpasswordfieldname"].value;
  if(!(a==b))
  {
    alert("both passwords are not matching");
    return false;
  }
  return true;
}

Generate a range of dates using SQL

Better late than never. Here's a method that I devised (after reading this post) for returning a list of dates that includes: (a) day 1 of of the current month through today, PLUS (b) all dates for the past two months:

select (sysdate +1 - rownum) dt 
from dual 
 connect by rownum <= (sysdate - add_months(sysdate - extract(day from sysdate),-2));

The "-2" is the number of prior full months of dates to include. For example, on July 10th, this SQL returns a list of all dates from May 1 through July 10 - i.e. two full prior months plus the current partial month.

Are there any disadvantages to always using nvarchar(MAX)?

Sometimes you want the data type to enforce some sense on the data in it.

Say for example you have a column that really shouldn't be longer than, say, 20 characters. If you define that column as VARCHAR(MAX), some rogue application could insert a long string into it and you'd never know, or have any way of preventing it.

The next time your application uses that string, under the assumption that the length of the string is modest and reasonable for the domain it represents, you will experience an unpredictable and confusing result.

Method has the same erasure as another method in type

Java generics uses type erasure. The bit in the angle brackets (<Integer> and <String>) gets removed, so you'd end up with two methods that have an identical signature (the add(Set) you see in the error). That's not allowed because the runtime wouldn't know which to use for each case.

If Java ever gets reified generics, then you could do this, but that's probably unlikely now.

What's the difference between event.stopPropagation and event.preventDefault?

return false;


return false; does 3 separate things when you call it:

  1. event.preventDefault() – It stops the browsers default behaviour.
  2. event.stopPropagation() – It prevents the event from propagating (or “bubbling up”) the DOM.
  3. Stops callback execution and returns immediately when called.

Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

preventDefault();


preventDefault(); does one thing: It stops the browsers default behaviour.

When to use them?


We know what they do but when to use them? Simply it depends on what you want to accomplish. Use preventDefault(); if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM. In most situations where you would use return false; what you really want is preventDefault().

Examples:


Let’s try to understand with examples:

We will see pure JAVASCRIPT example

Example 1:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked and immediately you will be redirected to stackoverflow.com.

Example 2:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.preventDefault();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is due > to event.preventDefault() method we used to prevent the default click action to be triggered.

Example 3:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.stopPropagation();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

This time if you click on Link the function executeParent() will not be called and you will not get the javascript alert div Clicked this time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to stackoverflow.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.

Example 4:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

If you click on the Link, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.

Example 5:

For return false I have three examples and all appear to be doing the exact same thing (just returning false), but in reality the results are quite different. Here's what actually happens in each of the above.

cases:

  1. Returning false from an inline event handler prevents the browser from navigating to the link address, but it doesn't stop the event from propagating through the DOM.
  2. Returning false from a jQuery event handler prevents the browser from navigating to the link address and it stops the event from propagating through the DOM.
  3. Returning false from a regular DOM event handler does absolutely nothing.

Will see all three example.

  1. Inline return false.

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='return false'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  var link = document.querySelector('a');_x000D_
_x000D_
  link.addEventListener('click', function() {_x000D_
    event.currentTarget.innerHTML = 'Click event prevented using inline html'_x000D_
    alert('Link Clicked');_x000D_
  });_x000D_
_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

  1. Returning false from a jQuery event handler.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
  <a href='https://stackoverflow.com'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  $('a').click(function(event) {_x000D_
    alert('Link Clicked');_x000D_
    $('a').text('Click event prevented using return FALSE');_x000D_
    $('a').contents().unwrap();_x000D_
    return false;_x000D_
  });_x000D_
  $('div').click(function(event) {_x000D_
    alert('Div clicked');_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

  1. Returning false from a regular DOM event handler.

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
    return false_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Hope these examples are clear. Try executing all these examples in a html file to see how they work.

preferredStatusBarStyle isn't called

For anyone still struggling with this, this simple extension in swift should fix the problem for you.

extension UINavigationController {
    override open var childForStatusBarStyle: UIViewController? {
        return self.topViewController
    }
}

Google Gson - deserialize list<class> object? (generic type)

Here is a solution that works with a dynamically defined type. The trick is creating the proper type of of array using Array.newInstance().

    public static <T> List<T> fromJsonList(String json, Class<T> clazz) {
    Object [] array = (Object[])java.lang.reflect.Array.newInstance(clazz, 0);
    array = gson.fromJson(json, array.getClass());
    List<T> list = new ArrayList<T>();
    for (int i=0 ; i<array.length ; i++)
        list.add(clazz.cast(array[i]));
    return list; 
}

JavaScript listener, "keypress" doesn't detect backspace?

My numeric control:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

try it

BackSpace key code is 8

How to kill a running SELECT statement

If you want to stop process you can kill it manually from task manager onother side if you want to stop running query in DBMS you can stop as given here for ms sqlserver T-SQL STOP or ABORT command in SQL Server Hope it helps you

SQL: How to properly check if a record exists

I'm using this way:

IIF(EXISTS (SELECT TOP 1 1 
                FROM Users 
                WHERE FirstName = 'John'), 1, 0) AS DoesJohnExist

What does it mean to have an index to scalar variable error? python

In my case, I was getting this error because I had an input named x and I was creating (without realizing it) a local variable called x. I thought I was trying to access an element of the input x (which was an array), while I was actually trying to access an element of the local variable x (which was a scalar).

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

So many answers.... all bad!

Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...

But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords.

anything with less than 8 characters OR anything with no numbers OR anything with no uppercase OR anything with no special characters

So:

^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$

If anything matches that, then it's an invalid password.

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Windows Firewall could cause this exception, try to disable it or add a rule for port or even program (java)

Why do Sublime Text 3 Themes not affect the sidebar?

I had the same problem. Just set the theme in Preferences -> Settings – User by editing the json property called.

{
    // Default theme
    "theme": "Material-Theme.sublime-theme",
    "color_scheme": "Packages/Material Theme/schemes/Material-Theme.tmTheme"
}

For Material theme that I use. It worked for me.

Bootstrap 3 only for mobile

I found a solution wich is to do:

<span class="visible-sm"> your code without col </span>
<span class="visible-xs"> your code with col </span>

It's not very optimized but it works. Did you find something better? It really miss a class like col-sm-0 to apply colons just to the xs size...

How to create an Oracle sequence starting with max value from a table?

DECLARE
    v_max NUMBER;
BEGIN
    SELECT (NVL (MAX (<COLUMN_NAME>), 0) + 1) INTO v_max FROM <TABLE_NAME>;
    EXECUTE IMMEDIATE 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || v_max || ' NOCYCLE CACHE 20 NOORDER';
END;

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

I had the same problem: I have a 64 bit Windows and when I typed "java -version" in CMD-Console i received the same Error message. Try to start a 64bit-cmd(C:\Windows\SysWOW64\cmd.exe) and you will see, it works there ;)

How can I count the occurrences of a list item?

Given a list X

 import numpy as np
 X = [1, -1, 1, -1, 1]

The dictionary which shows i: frequency(i) for elements of this list is:

{i:X.count(i) for i in np.unique(X)}

Output:

{-1: 2, 1: 3}

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

How to convert a string to a date in sybase

Use the convert function, for example:

select * from data 
where dateVal < convert(datetime, '01/01/2008', 103)

Where the convert style (103) determines the date format to use.

How do I view events fired on an element in Chrome DevTools?

For jQuery (at least version 1.11.2) the following procedure worked for me.

  1. Right click on the element and open 'Chrome Developer Tools'
  2. Type $._data(($0), 'events'); in the 'Console'
  3. Expand the attached objects and double click the handler: value.
  4. This shows the source code of the attached function, search for part of that using the 'Search' tab.

And it's time to stop re-inventing the wheel and start using vanilla JS events ... :)

how-to-find-jquery-click-handler-function

How do I set session timeout of greater than 30 minutes

if you are allowed to do it globally then you can set the session time out in

TOMCAT_HOME/conf/web.xml as below

 <!-- ==================== Default Session Configuration ================= -->
  <!-- You can set the default session timeout (in minutes) for all newly   -->
  <!-- created sessions by modifying the value below.                       -->


<session-config>
        <session-timeout>60</session-timeout>
</session-config>

Initializing ArrayList with some predefined values

I would suggest to use Arrays.asList() for single line initialization. For different ways of declaring and initializing a List you can also refer Initialization of ArrayList in Java

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

Android - Pulling SQlite database android device

Most of the answers here are way more complicated than they have to be. If you just want to copy the database of your app from your phone to your computer then you just need this command:

adb -d shell "run-as your.package.name cat databases/database.name" > target.sqlite

All you need to fill in in the above command is the package name of your app, what the database is called and optionally what/where you want the database to be copied to.

Please note that this specific command will only work if you have only one device connected to your computer. The -d parameter means that the only connected device will be targeted. But there are other parameters which you can use instead:

  • -e will target the only running emulator
  • -s <serialnumber> will target a device with a specific serial number.

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

It is generally expected that modules of code such as .cpp files are compiled once and linked to in multiple projects, to avoid unnecessary repetitive compilation of logic. For example, g++ -o class.cpp would produce class.o which you could then link from multiple projects to using g++ main.cpp class.o.

We could use #include as our linker, as you seem to be implying, but that would just be silly when we know how to link properly using our compiler with less keystrokes and less wasteful repetition of compilation, rather than our code with more keystrokes and more wasteful repetition of compilation...

The header files are still required to be included into each of the multiple projects, however, because this provides the interface for each module. Without these headers the compiler wouldn't know about any of the symbols introduced by the .o files.

It is important to realise that the header files are what introduce the definitions of symbols for those modules; once that is realised then it makes sense that multiple inclusions could cause redefinitions of symbols (which causes errors), so we use include guards to prevent such redefinitions.

Capture keyboardinterrupt in Python without try-except

If someone is in search for a quick minimal solution,

import signal

# The code which crashes program on interruption

signal.signal(signal.SIGINT, call_this_function_if_interrupted)

# The code skipped if interrupted

Android: combining text & image on a Button or ImageButton

There's a much better solution for this problem.

Just take a normal Button and use the drawableLeft and the gravity attributes.

<Button
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:drawableLeft="@drawable/my_btn_icon"
  android:gravity="left|center_vertical" />

This way you get a button which displays a icon in the left side of the button and the text at the right site of the icon vertical centered.

Javascript change color of text and background to input value

Depending on which event you actually want to use (textbox change, or button click), you can try this:

HTML:

<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>

JS:

function changeBackground(obj) {
    document.getElementById("coltext").style.color = obj.value;
}

DEMO: http://jsfiddle.net/6pLUh/

One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange allows you to change the color based on the input.

How to fix date format in ASP .NET BoundField (DataFormatString)?

Determine the data type of your data source column, "CreateDate". Make sure it is producing an actual datetime field and not something like a varchar. If your data source is a stored procedure, it is entirely possible that CreateDate is being processed to produce a varchar in order to format the date, like so:

SELECT CONVERT(varchar,TableName.CreateDate,126) AS CreateDate 
FROM TableName ...

Using CONVERT like this is often done to make query results fill the requirements of whatever other code is going to be processing those results. Style 126 is ISO 8601 format, an international standard that works with any language setting. I don't know what your industry is, but that was probably intentional. You don't want to mess with it. This style (126) produces a string representation of a date in the form '2013-04-29T18:15:20.270' just like you reported! However, if CreateDate's been processed this way then there's no way you'll be able to get your bf1.DataFormatString to show "29/04/2013" instead. You must first start with a datetime type column in your original SQL data source first for bf1 to properly consume it. So just add it to the data source query, and call it by a different name like CreateDate2 so as not to disturb whatever other code already depends on CreateDate, like this:

SELECT CONVERT(varchar,TableName.CreateDate,126) AS CreateDate, 
       TableName.CreateDate AS CreateDate2
FROM TableName ...

Then, in your code, you'll have to bind bf1 to "CreateDate2" instead of the original "CreateDate", like so:

BoundField bf1 = new BoundField();
bf1.DataField = "CreateDate2";
bf1.DataFormatString = "{0:dd/MM/yyyy}";
bf1.HtmlEncode = false;
bf1.HeaderText = "Sample Header 2";

dv.Fields.Add(bf1);

Voila! Your date should now show "29/04/2013" instead!

How to set opacity in parent div and not affect in child div?

You can do it with pseudo-elements: (demo on dabblet.com) enter image description here

your markup:

<div class="parent">
    <div class="child"> Hello I am child </div>
</div>

css:

.parent{
    position: relative;
}

.parent:before {
    z-index: -1;
    content: '';
    position: absolute;

    opacity: 0.2;
    width: 400px;
    height: 200px;
    background: url('http://img42.imageshack.us/img42/1893/96c75664f7e94f9198ad113.png') no-repeat 0 0; 
}

.child{
    Color:black;
}

VB.NET: Clear DataGridView

You can do that only by the following 2 lines:

DataGridView1.DataSource=Nothing
DataGridView1.DataBind()

How can I change CSS display none or block property using jQuery?

Other way to do it using jQuery CSS method:

$("#id").css({display: "none"});
$("#id").css({display: "block"});

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

How to convert an array to a string in PHP?

I would turn it into CSV form, like so:

$string_version = implode(',', $original_array)

You can turn it back by doing:

$destination_array = explode(',', $string_version)

The system cannot find the file specified. in Visual Studio

I had a same problem and this fixed it:

You should add:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib\x64 for 64 bit system

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib for 32 bit system

in Property Manager>Linker>General>Additional Library Directories

How/when to generate Gradle wrapper files?

If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:

task wrapper(type: Wrapper) {
    gradleVersion = '2.13'
    distributionUrl = distributionUrl.replace("bin", "all")
}

AngularJS directive does not update on scope variable changes

A simple solution is to make the scope variable object. Then access the content with {{ whatever-object.whatever-property }}. The variable is not updating because JavaScript pass Primitive type by value. Whereas Object are passed by reference which solves the problem.

How can I delay a :hover effect in CSS?

div {
     background: #dbdbdb;
    -webkit-transition: .5s all;   
    -webkit-transition-delay: 5s; 
    -moz-transition: .5s all;   
    -moz-transition-delay: 5s; 
    -ms-transition: .5s all;   
    -ms-transition-delay: 5s; 
    -o-transition: .5s all;   
    -o-transition-delay: 5s; 
    transition: .5s all;   
    transition-delay: 5s; 
}

div:hover {
    background:#5AC900;
    -webkit-transition-delay: 0s;
    -moz-transition-delay: 0s;
    -ms-transition-delay: 0s;
    -o-transition-delay: 0s;
    transition-delay: 0s;
}

This will add a transition delay, which will be applicable to almost every browser..

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

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

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

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

How to convert string to integer in UNIX

The standard solution:

 expr $d1 - $d2

You can also do:

echo $(( d1 - d2 ))

but beware that this will treat 07 as an octal number! (so 07 is the same as 7, but 010 is different than 10).

How to encode the filename parameter of Content-Disposition header in HTTP?

We had a similar problem in a web application, and ended up by reading the filename from the HTML <input type="file">, and setting that in the url-encoded form in a new HTML <input type="hidden">. Of course we had to remove the path like "C:\fakepath\" that is returned by some browsers.

Of course this does not directly answer OPs question, but may be a solution for others.

How to horizontally center an element

CSS justify-content property

It aligns the Flexbox items at the center of the container:

#outer {
    display: flex;
    justify-content: center;
}

Where could I buy a valid SSL certificate?

The value of the certificate comes mostly from the trust of the internet users in the issuer of the certificate. To that end, Verisign is tough to beat. A certificate says to the client that you are who you say you are, and the issuer has verified that to be true.

You can get a free SSL certificate signed, for example, by StartSSL. This is an improvement on self-signed certificates, because your end-users would stop getting warning pop-ups informing them of a suspicious certificate on your end. However, the browser bar is not going to turn green when communicating with your site over https, so this solution is not ideal.

The cheapest SSL certificate that turns the bar green will cost you a few hundred dollars, and you would need to go through a process of proving the identity of your company to the issuer of the certificate by submitting relevant documents.

byte[] to hex string

Nice way to do this with LINQ...

var data = new byte[] { 1, 2, 4, 8, 16, 32 }; 
var hexString = data.Aggregate(new StringBuilder(), 
                               (sb,v)=>sb.Append(v.ToString("X2"))
                              ).ToString();

How to create a DOM node as an object?

And here is the one liner:

$("<li><div class='bar'>bla</div></li>").find("li").attr("id","1234").end().appendTo("body")

But I'm wondering why you would like to add the "id" attribute at a later stage rather than injecting it directly in the template.

Use Fieldset Legend with bootstrap

I had a different approach , used bootstrap panel to show it little more rich. Just to help someone and improve the answer.

_x000D_
_x000D_
.text-on-pannel {_x000D_
  background: #fff none repeat scroll 0 0;_x000D_
  height: auto;_x000D_
  margin-left: 20px;_x000D_
  padding: 3px 5px;_x000D_
  position: absolute;_x000D_
  margin-top: -47px;_x000D_
  border: 1px solid #337ab7;_x000D_
  border-radius: 8px;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
  /* for text on pannel */_x000D_
  margin-top: 27px !important;_x000D_
}_x000D_
_x000D_
.panel-body {_x000D_
  padding-top: 30px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="container">_x000D_
  <div class="panel panel-primary">_x000D_
    <div class="panel-body">_x000D_
      <h3 class="text-on-pannel text-primary"><strong class="text-uppercase"> Title </strong></h3>_x000D_
      <p> Your Code </p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div>
_x000D_
_x000D_
_x000D_

This will give below look. enter image description here

Note: We need to change the styles in order to use different header size.

Invalid date in safari

The pattern yyyy-MM-dd isn't an officially supported format for Date constructor. Firefox seems to support it, but don't count on other browsers doing the same.

Here are some supported strings:

  • MM-dd-yyyy
  • yyyy/MM/dd
  • MM/dd/yyyy
  • MMMM dd, yyyy
  • MMM dd, yyyy

DateJS seems like a good library for parsing non standard date formats.

Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:

Date Time String Format

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ Where the fields are as follows:

  • YYYY is the decimal digits of the year in the Gregorian calendar.
  • "-" (hyphon) appears literally twice in the string.
  • MM is the month of the year from 01 (January) to 12 (December).
  • DD is the day of the month from 01 to 31.
  • "T" appears literally in the string, to indicate the beginning of the time element.
  • HH is the number of complete hours that have passed since midnight as two decimal digits.
  • ":" (colon) appears literally twice in the string.
  • mm is the number of complete minutes since the start of the hour as two decimal digits.
  • ss is the number of complete seconds since the start of the minute as two decimal digits.
  • "." (dot) appears literally in the string.
  • sss is the number of complete milliseconds since the start of the second as three decimal digits. Both the "." and the milliseconds field may be omitted.
  • Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression hh:mm

This format includes date-only forms:

  • YYYY
  • YYYY-MM
  • YYYY-MM-DD

It also includes time-only forms with an optional time zone offset appended:

  • THH:mm
  • THH:mm:ss
  • THH:mm:ss.sss

Also included are "date-times" which may be any combination of the above.

So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.

Update: after looking at datejs documentation, using it, your problem should be solved using code like this:

var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");

Index inside map() function

Using Ramda:

import {addIndex, map} from 'ramda';

const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return 'X';
}, list);

How can I save a screenshot directly to a file in Windows?

Without installing a screenshot autosave utility, yes you do. There are several utilities you can find however folr doing this.

For example: http://www.screenshot-utility.com/

Add User to Role ASP.NET Identity

This one works for me. You can see this code on AccountController -> Register

var user = new JobUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    //add this to add role to user
     await UserManager.AddToRoleAsync(user.Id, "Name of your role");
}

but the role name must exist in your AspNetRoles table.

How can I directly view blobs in MySQL Workbench

Perform three steps:

  1. Go to "WorkBench Preferences" --> Choose "SQL Editor" Under "Query Results": check "Treat BINARY/VARBINARY as nonbinary character string"

  2. Restart MySQL WorkBench.

  3. Now select SELECT SUBSTRING(BLOB<COLUMN_NAME>,1,2500) FROM <Table_name>;

Using the "With Clause" SQL Server 2008

Just a poke, but here's another way to write FizzBuzz :) 100 rows is enough to show the WITH statement, I reckon.

;WITH t100 AS (
 SELECT n=number
 FROM master..spt_values
 WHERE type='P' and number between 1 and 100
)                
 SELECT
    ISNULL(NULLIF(
    CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
    CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
 FROM t100

But the real power behind WITH (known as Common Table Expression http://msdn.microsoft.com/en-us/library/ms190766.aspx "CTE") in SQL Server 2005 and above is the Recursion, as below where the table is built up through iterations adding to the virtual-table each time.

;WITH t100 AS (
 SELECT n=1
 union all
 SELECT n+1
 FROM t100
 WHERE n < 100
)                
 SELECT
    ISNULL(NULLIF(
    CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
    CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
 FROM t100

To run a similar query in all database, you can use the undocumented sp_msforeachdb. It has been mentioned in another answer, but it is sp_msforeachdb, not sp_foreachdb.

Be careful when using it though, as some things are not what you expect. Consider this example

exec sp_msforeachdb 'select count(*) from sys.objects'

Instead of the counts of objects within each DB, you will get the SAME count reported, begin that of the current DB. To get around this, always "use" the database first. Note the square brackets to qualify multi-word database names.

exec sp_msforeachdb 'use [?]; select count(*) from sys.objects'

For your specific query about populating a tally table, you can use something like the below. Not sure about the DATE column, so this tally table has only the DBNAME and IMG_COUNT columns, but hope it helps you.

create table #tbl (dbname sysname, img_count int);

exec sp_msforeachdb '
use [?];
if object_id(''tbldoc'') is not null
insert #tbl
select ''?'', count(*) from tbldoc'

select * from #tbl

Object not found! The requested URL was not found on this server. localhost

One thing I found out is that your folder holding your php/html files cannot be named the same name as the folder in your HTDOCS carrying your project.

Inserting created_at data with Laravel

You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:

protected $fillable = ['name', 'created_at']; 

Python Flask, how to set content type

Usually you don’t have to create the Response object yourself because make_response() will take care of that for you.

from flask import Flask, make_response                                      
app = Flask(__name__)                                                       

@app.route('/')                                                             
def index():                                                                
    bar = '<body>foo</body>'                                                
    response = make_response(bar)                                           
    response.headers['Content-Type'] = 'text/xml; charset=utf-8'            
    return response

One more thing, it seems that no one mentioned the after_this_request, I want to say something:

after_this_request

Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one.

so we can do it with after_this_request, the code should look like this:

from flask import Flask, after_this_request
app = Flask(__name__)

@app.route('/')
def index():
    @after_this_request
    def add_header(response):
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return response
    return '<body>foobar</body>'

How to get a Color from hexadecimal Color String

In Xamarin Use this

Control.SetBackgroundColor(global::Android.Graphics.Color.ParseColor("#F5F1F1"));

SQL DROP TABLE foreign key constraint

If you want to DROP a table which has been referenced by other table using the foreign key use

DROP TABLE *table_name* CASCADE CONSTRAINTS;
I think it should work for you.

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

PHP: How can I determine if a variable has a value that is between two distinct constant values?

If you just want to check the value is in Range, use this:

   MIN_VALUE = 1;
   MAX_VALUE = 100;
   $customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));

How to set the focus for a particular field in a Bootstrap modal, once it appears

Bootstrap modal show event

$('#modal-content').on('show.bs.modal', function() {
$("#txtname").focus();

})

Is there a sleep function in JavaScript?

If you are looking to block the execution of code with call to sleep, then no, there is no method for that in JavaScript.

JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.

setTimeout(myFunction, 3000);

// if you have defined a function named myFunction 
// it will run after 3 seconds (3000 milliseconds)

Remember, this is completely different from how sleep method, if it existed, would behave.

function test1()
{    
    // let's say JavaScript did have a sleep function..
    // sleep for 3 seconds
    sleep(3000);

    alert('hi'); 
}

If you run the above function, you will have to wait for 3 seconds (sleep method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep function like that in JavaScript.

function test2()
{
    // defer the execution of anonymous function for 
    // 3 seconds and go to next line of code.
    setTimeout(function(){ 

        alert('hello');
    }, 3000);  

    alert('hi');
}

If you run test2, you will see 'hi' right away (setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.

How to rename files and folder in Amazon S3?

We have 2 ways by which we can rename a file on AWS S3 storage -

1 .Using the CLI tool -

aws s3 --recursive mv s3://bucket-name/dirname/oldfile s3://bucket-name/dirname/newfile

2.Using SDK

$s3->copyObject(array(
'Bucket'     => $targetBucket,
'Key'        => $targetKeyname,
'CopySource' => "{$sourceBucket}/{$sourceKeyname}",));

Adding close button in div to close the box

jQuery("#your_div_id").remove(); will completely remove the corresponding elements from the HTML DOM. So if you want to show the div on another event without a refresh, it will not be possible to retrieve the removed elements back unless you use AJAX.

jQuery("#your_div_id").toggle("slow"); will also could make unexpected results. As an Example when you select some element on your div which generates another div with a close button(which uses the same close functionality just as your previous div) it could make undesired behaviour.

So without using AJAX, a good solution for the close button would be as follows

HTML____________

<div id="your_div_id">
<span class="close_div" onclick="close_div(1)">&#10006</span>
</div>

JQUERY__________

function close_div(id) {
    if(id === 1) {
        jQuery("#your_div_id").hide();
    }
}

Now you can show the div, when another event occures as you wish... :-)

MySQL Workbench Dark Theme

Quoting Yoga...

For Mac users, the code_editor.xml file is in MBP HD/ Applications/MySQLWorkbench.app/Contents/Resources/data/

I just discovered by dumbfounded experimentation (i.e. first thing I tried, worked) that if I copy that file to...

/Users/your.username/Library/Application Support/MySQL/Workbench/code_editor.xml

...and then edit it there, it does indeed override. Just worked perfectly for me on Mac OS X Sierra and MySQL Workbench 6.3.

Vue-router redirect on page not found (404)

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

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

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

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

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

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

This can occur when you are showing the dialog for a context that no longer exists. A common case - if the 'show dialog' operation is after an asynchronous operation, and during that operation the original activity (that is to be the parent of your dialog) is destroyed. For a good description, see this blog post and comments:

http://dimitar.me/android-displaying-dialogs-from-background-threads/

From the stack trace above, it appears that the facebook library spins off the auth operation asynchronously, and you have a Handler - Callback mechanism (onComplete called on a listener) that could easily create this scenario.

When I've seen this reported in my app, its pretty rare and matches the experience in the blog post. Something went wrong for the activity/it was destroyed during the work of the the AsyncTask. I don't know how your modification could result in this every time, but perhaps you are referencing an Activity as the context for the dialog that is always destroyed by the time your code executes?

Also, while I'm not sure if this is the best way to tell if your activity is running, see this answer for one method of doing so:

Check whether activity is active

Associating enums with strings in C#

Here is the extension method that I used to get the enum value as string. First here is the enum.

public enum DatabaseEnvironment
{
    [Description("AzamSharpBlogDevDatabase")]
    Development = 1, 
    [Description("AzamSharpBlogQADatabase")]
    QualityAssurance = 2, 
    [Description("AzamSharpBlogTestDatabase")] 
    Test = 3
}

The Description attribute came from System.ComponentModel.

And here is my extension method:

public static string GetValueAsString(this DatabaseEnvironment environment) 
{
    // get the field 
    var field = environment.GetType().GetField(environment.ToString());
    var customAttributes = field.GetCustomAttributes(typeof (DescriptionAttribute), false);

    if(customAttributes.Length > 0)
    {
        return (customAttributes[0] as DescriptionAttribute).Description;  
    }
    else
    {
        return environment.ToString(); 
    }
}

Now, you can access the enum as string value using the following code:

[TestFixture]
public class when_getting_value_of_enum
{
    [Test]
    public void should_get_the_value_as_string()
    {
        Assert.AreEqual("AzamSharpBlogTestDatabase",DatabaseEnvironment.Test.GetValueAsString());  
    }
}

unix - count of columns in file

Based on Cat Kerr response. This command is working on solaris

awk '{print NF; exit}' stores.dat

How to set default font family for entire Android app

To change your app font follow the following steps:

  1. Inside res directory create a new directory and name it font.
  2. Insert your font .ttf/.otf inside the font folder, Make sure the font name is lower case letters and underscore only.
  3. Inside res -> values -> styles.xml inside <resources> -> <style> add your font <item name="android:fontFamily">@font/font_name</item>.

enter image description here

Now all your app text should be in the font that you add.

Angular2 Routing with Hashtag to page anchor

Update

This is now supported

<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
this._router.navigate( ['/somepath', id ], {fragment: 'test'});

Add Below code to your component to scroll

  import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import

  private fragment: string;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
  }

  ngAfterViewInit(): void {
    try {
      document.querySelector('#' + this.fragment).scrollIntoView();
    } catch (e) { }
  }

Original

This is a known issue and tracked at https://github.com/angular/angular/issues/6595

Using union and order by clause in mysql

Don't forget, union all is a way to add records to a record set without sorting or merging (as opposed to union).

So for example:

select * from (
    select col1, col2
    from table a
    <....>
    order by col3
    limit by 200
) a
union all
select * from (
    select cola, colb
    from table b
    <....>
    order by colb
    limit by 300
) b

It keeps the individual queries clearer and allows you to sort by different parameters in each query. However by using the selected answer's way it might become clearer depending on complexity and how related the data is because you are conceptualizing the sort. It also allows you to return the artificial column to the querying program so it has a context it can sort by or organize.

But this way has the advantage of being fast, not introducing extra variables, and making it easy to separate out each query including the sort. The ability to add a limit is simply an extra bonus.

And of course feel free to turn the union all into a union and add a sort for the whole query. Or add an artificial id, in which case this way makes it easy to sort by different parameters in each query, but it otherwise is the same as the accepted answer.

Jenkins: Can comments be added to a Jenkinsfile?

You can use block (/***/) or single line comment (//) for each line. You should use "#" in sh command.

Block comment

_x000D_
_x000D_
/*  _x000D_
post {_x000D_
    success {_x000D_
      mail to: "[email protected]", _x000D_
      subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
      body: "Yay, we passed."_x000D_
    }_x000D_
    failure {_x000D_
      mail to: "[email protected]", _x000D_
      subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
      body: "Boo, we failed."_x000D_
    }_x000D_
  }_x000D_
*/
_x000D_
_x000D_
_x000D_

Single Line

_x000D_
_x000D_
// post {_x000D_
//     success {_x000D_
//       mail to: "[email protected]", _x000D_
//       subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
//       body: "Yay, we passed."_x000D_
//     }_x000D_
//     failure {_x000D_
//       mail to: "[email protected]", _x000D_
//       subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
//       body: "Boo, we failed."_x000D_
//     }_x000D_
// }
_x000D_
_x000D_
_x000D_

Comment in 'sh' command

_x000D_
_x000D_
        stage('Unit Test') {_x000D_
            steps {_x000D_
                ansiColor('xterm'){_x000D_
                  sh '''_x000D_
                  npm test_x000D_
                  # this is a comment in sh_x000D_
                  '''_x000D_
                }_x000D_
            }_x000D_
        }
_x000D_
_x000D_
_x000D_

What does OpenCV's cvWaitKey( ) function do?

/* Assuming this is a while loop -> e.g. video stream where img is obtained from say web camera.*/    
cvShowImage("Window",img);

/* A small interval of 10 milliseconds. This may be necessary to display the image correctly */
cvWaitKey(10);  

/* to wait until user feeds keyboard input replace with cvWaitKey(0); */

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

Try removing the text-alignment center and center the <h1> or <div> the text resides in.

h1 {
    background-color:green;
    margin: 0 auto;
    width: 200px;
}

Get selected element's outer HTML

I used Jessica's solution (which was edited by Josh) to get outerHTML to work on Firefox. The problem however is that my code was breaking because her solution wrapped the element into a DIV. Adding one more line of code solved that problem.

The following code gives you the outerHTML leaving the DOM tree unchanged.

$jq.fn.outerHTML = function() {
    if ($jq(this).attr('outerHTML'))
        return $jq(this).attr('outerHTML');
    else
    {
    var content = $jq(this).wrap('<div></div>').parent().html();
        $jq(this).unwrap();
        return content;
    }
}

And use it like this: $("#myDiv").outerHTML();

Hope someone finds it useful!

Python match a string with regex

One Liner implementation:

a=[1,3]
b=[1,2,3,4]
all(i in b for i in a)

Get hostname of current request in node.js Express

You can use the os Module:

var os = require("os");
os.hostname();

See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

Caveats:

  1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

  2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

Java NIO: What does IOException: Broken pipe mean?

You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.

You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.

How to get streaming url from online streaming radio station

When you go to a stream url, you get offered a file. feed this file to a parser to extract the contents out of it. the file is (usually) plain text and contains the url to play.

How do you stylize a font in Swift?

I am assuming this is a custom font. For any custom font this is what you do.

  1. First download and add your font files to your project in Xcode (The files should appear as well in “Target -> Build Phases -> Copy Bundle Resources”).

  2. In your Info.plist file add the key “Fonts provided by application” with type “Array”.

  3. For each font you want to add to your project, create an item for the array you have created with the full name of the file including its extension (e.g. HelveticaNeue-UltraLight.ttf). Save your “Info.plist” file.

label.font = UIFont (name: "HelveticaNeue-UltraLight", size: 30)

align an image and some text on the same line without using div width?

U wrote an unnecessary div, just leave it like this

_x000D_
_x000D_
<div id="texts" style="white-space:nowrap;">
     <img src="tree.png"  align="left"/>
     A very long text(about 300 words) 
</div>
_x000D_
_x000D_
_x000D_

What u are looking for is white-space:nowrap; this code will do the trick.

Split function in oracle to comma separated values with automatic sequence

If you need a function try this.
First we'll create a type:

CREATE OR REPLACE TYPE T_TABLE IS OBJECT
(
    Field1 int
    , Field2 VARCHAR(25)
);
CREATE TYPE T_TABLE_COLL IS TABLE OF T_TABLE;
/

Then we'll create the function:

CREATE OR REPLACE FUNCTION TEST_RETURN_TABLE
RETURN T_TABLE_COLL
    IS
      l_res_coll T_TABLE_COLL;
      l_index number;
    BEGIN
      l_res_coll := T_TABLE_COLL();
      FOR i IN (
        WITH TAB AS
          (SELECT '1001' ID, 'A,B,C,D,E,F' STR FROM DUAL
          UNION
          SELECT '1002' ID, 'D,E,F' STR FROM DUAL
          UNION
          SELECT '1003' ID, 'C,E,G' STR FROM DUAL
          )
        SELECT id,
          SUBSTR(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
        FROM
          ( SELECT ',' || STR || ',' AS STR, id FROM TAB
          ),
          ( SELECT level AS lvl FROM dual CONNECT BY level <= 100
          )
        WHERE lvl <= LENGTH(STR) - LENGTH(REPLACE(STR, ',')) - 1
        ORDER BY ID, NAME)
      LOOP
        IF i.ID = 1001 THEN
          l_res_coll.extend;
          l_index := l_res_coll.count;
          l_res_coll(l_index):= T_TABLE(i.ID, i.name);
        END IF;
      END LOOP;
      RETURN l_res_coll;
    END;
    /

Now we can select from it:

select * from table(TEST_RETURN_TABLE()); 

Output:

SQL> select * from table(TEST_RETURN_TABLE());

    FIELD1 FIELD2
---------- -------------------------
      1001 A
      1001 B
      1001 C
      1001 D
      1001 E
      1001 F

6 rows selected.

Obviously you'd need to replace the WITH TAB AS... bit with where you would be getting your actual data from. Credit Credit

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:

Whichever of those you choose, your record will look like the following:

Record: ALIAS or ANAME

Name: empty or @

Target: example.com.herokudns.com.

That's all you need.


However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.

If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www to http://example.com.

If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.

To handle the redirects at the application level, you'll need to:

  • Add both your apex and www host names to the Heroku application (heroku domains:add example.com and heroku domains:add www.example.com)
  • Set up your SSL certificates
  • Point your apex domain record at Heroku using an ALIAS or ANAME record as described above
  • Add a CNAME record with name www pointing to www.example.com.herokudns.com.
  • And then in your application, 301 redirect any www requests to the non-www URL (here's an example of how to do it in Django)
  • Also in your application, you should probably redirect any HTTP requests to HTTPS (for example, in Django set SECURE_SSL_REDIRECT to True)

Check out this post from DNSimple for more.

How to select a node of treeview programmatically in c#?

Apologies for my previously mixed up answer.

Here is how to do:

myTreeView.SelectedNode = myTreeNode;

(Update)

I have tested the code below and it works:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        treeView1.Nodes.Add("1", "1");
        treeView1.Nodes.Add("2", "2");
        treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
        TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
        treeView1.SelectedNode = treeNode;
        MessageBox.Show(treeNode.IsSelected.ToString());
    }


}

Write objects into file with Node.js

Just incase anyone else stumbles across this, I use the fs-extra library in node and write javascript objects to a file like this:

const fse = require('fs-extra');
fse.outputJsonSync('path/to/output/file.json', objectToWriteToFile); 

What does "pending" mean for request in Chrome Developer Window?

Same problem with Chrome : I had in my html page the following code :

<body>
  ...
  <script src="http://myserver/lib/load.js"></script>
  ...
</body>

But the load.js was always in status pending when looking in the Network pannel.

I found a workaround using asynchronous load of load.js:

<body>
  ...
  <script>
    setTimeout(function(){
      var head, script;
      head = document.getElementsByTagName("head")[0];
      script = document.createElement("script");
      script.src = "http://myserver/lib/load.js";
      head.appendChild(script);
    }, 1);
  </script>
  ...
</body>

Now its working fine.

How to find the array index with a value?

When the lists aren't extremely long, this is the best way I know:

function getIndex(val) {
    for (var i = 0; i < imageList.length; i++) {
        if (imageList[i] === val) {
            return i;
        }
    }
}

var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);

PostgreSQL: days/months/years between two dates

This question is full of misunderstandings. First lets understand the question fully. The asker wants to get the same result as for when running the MS SQL Server function DATEDIFF ( datepart , startdate , enddate ) where datepart takes dd, mm, or yy.

This function is defined by:

This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.

That means how many day boundaries, month boundaries, or year boundaries, are crossed. Not how many days, months, or years it is between them. That's why datediff(yy, '2010-04-01', '2012-03-05') is 2, and not 1. There is less than 2 years between those dates, meaning only 1 whole year has passed, but 2 year boundaries have crossed, from 2010 to 2011, and from 2011 to 2012.

The following are my best attempt at replicating the logic correctly.

-- datediff(dd`, '2010-04-01', '2012-03-05') = 704 // 704 changes of day in this interval
select ('2012-03-05'::date - '2010-04-01'::date );
-- 704 changes of day

-- datediff(mm, '2010-04-01', '2012-03-05') = 23  // 23 changes of month
select (date_part('year', '2012-03-05'::date) - date_part('year', '2010-04-01'::date)) * 12 + date_part('month', '2012-03-05'::date) - date_part('month', '2010-04-01'::date)
-- 23 changes of month

-- datediff(yy, '2010-04-01', '2012-03-05') = 2   // 2 changes of year
select date_part('year', '2012-03-05'::date) - date_part('year', '2010-04-01'::date);
-- 2 changes of year

Foreach in a Foreach in MVC View

Controller

public ActionResult Index()
    {


        //you don't need to include the category bc it does it by itself
        //var model = db.Product.Include(c => c.Category).ToList()

        ViewBag.Categories = db.Category.OrderBy(c => c.Name).ToList();
        var model = db.Product.ToList()
        return View(model);
    }


View

you need to filter the model with the given category

like :=> Model.where(p=>p.CategoryID == category.CategoryID)

try this...

@foreach (var category in ViewBag.Categories)
{
    <h3><u>@category.Name</u></h3>

    <div>

        @foreach (var product in Model.where(p=>p.CategoryID == category.CategoryID))
        {

                <table cellpadding="5" cellspacing"5" style="border:1px solid black; width:100%;background-color:White;">
                    <thead>
                        <tr>
                            <th style="background-color:black; color:white;">
                                @product.Title  
                                @if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
                                {
                                    @Html.Raw(" - ")  
                                    @Html.ActionLink("Edit", "Edit", new { id = product.ID }, new { style = "background-color:black; color:white !important;" })
                                }
                            </th>
                        </tr>
                    </thead>

                    <tbody>
                        <tr>
                            <td style="background-color:White;">
                                @product.Description
                            </td>
                        </tr>
                    </tbody>      
                </table>                       
            }


    </div>
}  

How to compare arrays in JavaScript?

function compareArrays(arrayA, arrayB) {
    if (arrayA.length != arrayB.length) return true;
    for (i = 0; i < arrayA.length; i++)
        if (arrayB.indexOf(arrayA[i]) == -1) {
            return true;
        }
    }
    for (i = 0; i < arrayB.length; i++) {
        if (arrayA.indexOf(arrayB[i]) == -1) {
            return true;
        }
    }
    return false;
}

Angular2 disable button

Yes you can

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
 </div>

https://angular.io/docs/ts/latest/api/common/NgClass-directive.html

Where am I? - Get country

This will get the country code set for the phone (phones language, NOT user location):

 String locale = context.getResources().getConfiguration().locale.getCountry(); 

can also replace getCountry() with getISO3Country() to get a 3 letter ISO code for the country. This will get the country name:

 String locale = context.getResources().getConfiguration().locale.getDisplayCountry();

This seems easier than the other methods and rely upon the localisation settings on the phone, so if a US user is abroad they probably still want Fahrenheit and this will work :)

Editors note: This solution has nothing to do with the location of the phone. It is constant. When you travel to Germany locale will NOT change. In short: locale != location.

How can I remove a character from a string using JavaScript?

You can use this: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)

Explanation:

  1. if ( str[4] === 'r' )
    Check if the 5th character is a 'r'

  2. str.slice(0, 4)
    Slice the string to get everything before the 'r'

  3. + str.slice(5)
    Add the rest of the string.

Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s [37 bytes!]

DEMO:

_x000D_
_x000D_
function remove5thR (s) {_x000D_
  s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;_x000D_
  console.log(s); // log output_x000D_
}_x000D_
_x000D_
remove5thR('crt/r2002_2')  // > 'crt/2002_2'_x000D_
remove5thR('crt|r2002_2')  // > 'crt|2002_2'_x000D_
remove5thR('rrrrr')        // > 'rrrr'_x000D_
remove5thR('RRRRR')        // > 'RRRRR' (no change)
_x000D_
_x000D_
_x000D_

msvcr110.dll is missing from computer error while installing PHP

You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679

As mentioned by Stuart McLaughlin, make sure you get the x86 version even if you use a 64-bits OS because PHP needs some 32-bit libraries.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

If emails is the pandas dataframe and emails.message the column for email text

## Helper functions
def get_text_from_email(msg):
    '''To get the content from email objects'''
    parts = []
    for part in msg.walk():
        if part.get_content_type() == 'text/plain':
            parts.append( part.get_payload() )
    return ''.join(parts)

def split_email_addresses(line):
    '''To separate multiple email addresses'''
    if line:
        addrs = line.split(',')
        addrs = frozenset(map(lambda x: x.strip(), addrs))
    else:
        addrs = None
    return addrs 

import email
# Parse the emails into a list email objects
messages = list(map(email.message_from_string, emails['message']))
emails.drop('message', axis=1, inplace=True)
# Get fields from parsed email objects
keys = messages[0].keys()
for key in keys:
    emails[key] = [doc[key] for doc in messages]
# Parse content from emails
emails['content'] = list(map(get_text_from_email, messages))
# Split multiple email addresses
emails['From'] = emails['From'].map(split_email_addresses)
emails['To'] = emails['To'].map(split_email_addresses)

# Extract the root of 'file' as 'user'
emails['user'] = emails['file'].map(lambda x:x.split('/')[0])
del messages

emails.head()

When to use React "componentDidUpdate" method?

Sometimes you might add a state value from props in constructor or componentDidMount, you might need to call setState when the props changed but the component has already mounted so componentDidMount will not execute and neither will constructor; in this particular case, you can use componentDidUpdate since the props have changed, you can call setState in componentDidUpdate with new props.

How to iterate over the file in python

The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:

f = open('test.txt','r')
g = open('test1.txt','w') 
while True:
    x = f.readline()
    x = x.rstrip()
    if not x: break
    print >> g, int(x, 16)

On the other hand it would be better to use for x in f instead of readline. Do not forget to close your files or better to use with that close them for you:

with open('test.txt','r') as f:
    with open('test1.txt','w') as g: 
        for x in f:
            x = x.rstrip()
            if not x: continue
            print >> g, int(x, 16)

How can I list all tags for a Docker image on a remote registry?

You can use:

skopeo inspect docker://<REMOTE_REGISTRY> --authfile <PULL_SECRET> | jq .RepoTags

How to check if a file exists in a folder?

Since nobody said how to check if the file exists AND get the current folder the executable is in (Working Directory):

if (File.Exists(Directory.GetCurrentDirectory() + @"\YourFile.txt")) {
                //do stuff
}

The @"\YourFile.txt" is not case sensitive, that means stuff like @"\YoUrFiLe.txt" and @"\YourFile.TXT" or @"\yOuRfILE.tXt" is interpreted the same.

AngularJs $http.post() does not send data

this is probably a late answer but i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
    $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

Node.js Logging

Log4js is one of the most popular logging library for nodejs application.

It supports many cool features:

  1. Coloured console logging
  2. Replacement of node's console.log functions (optional)
  3. File appender, with log rolling based on file size
  4. SMTP, GELF, hook.io, Loggly appender
  5. Multiprocess appender (useful when you've got worker processes)
  6. A logger for connect/express servers
  7. Configurable log message layout/patterns
  8. Different log levels for different log categories (make some parts of your app log as DEBUG, others only ERRORS, etc.)

Example:

  1. Installation: npm install log4js

  2. Configuration (./config/log4js.json):

    {"appenders": [
        {
            "type": "console",
            "layout": {
                "type": "pattern",
                "pattern": "%m"
            },
            "category": "app"
        },{
            "category": "test-file-appender",
            "type": "file",
            "filename": "log_file.log",
            "maxLogSize": 10240,
            "backups": 3,
            "layout": {
                "type": "pattern",
                "pattern": "%d{dd/MM hh:mm} %-5p %m"
            }
        }
    ],
    "replaceConsole": true }
    
  3. Usage:

    var log4js = require( "log4js" );
    log4js.configure( "./config/log4js.json" );
    var logger = log4js.getLogger( "test-file-appender" );
    // log4js.getLogger("app") will return logger that prints log to the console
    logger.debug("Hello log4js");// store log in file
    

Setting a checkbox as checked with Vue.js

In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

I think you have put command like java -VERSION. This is in capital letters You need to put all command in lowercase letters

javac -version
java -version

All characters must be in lowercase letter

How to inflate one view with a layout

I'm not sure I have followed your question- are you trying to attach a child view to the RelativeLayout? If so you want to do something along the lines of:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

  • Short answer: for "can't find dependent library" error, check your $PATH (corresponds to bullet point #3 below)
  • Long answer:
    1. Pure java world: jvm uses "Classpath" to find class files
    2. JNI world (java/native boundary): jvm uses "java.library.path" (which defaults to $PATH) to find dlls
    3. pure native world: native code uses $PATH to load other dlls

Close popup window

For such a seemingly simple thing this can be a royal pain in the butt! I found a solution that works beautifully (class="video-close" is obviously particular to this button and optional)

 <a href="javascript:window.open('','_self').close();" class="video-close">Close this window</a>

Namenode not getting started

I ran into the same thing after a restart.

for hadoop-2.7.3 all I had to do was format the namenode:

<HadoopRootDir>/bin/hdfs namenode -format

Then a jps command shows

6097 DataNode
755 RemoteMavenServer
5925 NameNode
6293 SecondaryNameNode
6361 Jps

How can I select rows by range?

Using Between condition

SELECT *
FROM TEST
WHERE COLUMN_NAME BETWEEN x AND y ;

Or using Just operators,

SELECT *
FROM TEST
WHERE COLUMN_NAME >= x AND COLUMN_NAME   <= y;

HTML CSS How to stop a table cell from expanding

It's entirely possible if your code has enough relative logic to work with.

Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.

ol {max-width: 10vw; padding: 0; overflow: hidden;}

Apparently max-width on colgroup elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.

Site does not exist error for a2ensite

Solved the issue by adding .conf extension to site configuration files.

Apache a2ensite results in:

Error! Site Does Not Exist

Problem; If you found the error while trying to enable a site using:

sudo a2ensite example.com

but it returns:

Error: example.com does not exist

a2ensite is simply a Perl script that only works with filenames ending .conf

Therefore, I have to rename my setting file for example.com to example.com.conf as might be achieved as follows:

mv /etc/apache2/sites-available/example.com /etc/apache2/sites-available/example.com.conf

Success

Test a weekly cron job

Aside from that you can also use:

http://pypi.python.org/pypi/cronwrap

to wrap up your cron to send you an email upon success or failure.

Why I get 'list' object has no attribute 'items'?

result_list = [int(v) for k,v in qs[0].items()]

qs is a list, qs[0] is the dict which you want!

How to get instance variables in Python?

You can also test if an object has a specific variable with:

>>> hi_obj = hi()
>>> hasattr(hi_obj, "some attribute")

Select a Dictionary<T1, T2> with LINQ

A more explicit option is to project collection to an IEnumerable of KeyValuePair and then convert it to a Dictionary.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);

Styling HTML5 input type number

<input type="number" name="numericInput" size="2" min="0" maxlength="2" value="0" />

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

You can use tee to write to the file without the need for flushing.

/homedir/MyScript 2>&1 | tee some_log.log > /dev/null

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

scanf needs to know the size of the data being pointed at by &d to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf is always getting a double.

Correct way to write line to file?

One can also use the io module as in:

import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)

Android: I am unable to have ViewPager WRAP_CONTENT

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

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

int getMeasureExactly(View child, int widthMeasureSpec) {
    child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    int height = child.getMeasuredHeight();
    return MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;

    final View tab = getChildAt(0);
    if (tab == null) {
        return;
    }

    int width = getMeasuredWidth();
    if (wrapHeight) {
        // Keep the current measured width.
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
    }
    Fragment fragment = ((Fragment) getAdapter().instantiateItem(this, getCurrentItem()));
    heightMeasureSpec = getMeasureExactly(fragment.getView(), widthMeasureSpec);

    //Log.i(Constants.TAG, "item :" + getCurrentItem() + "|height" + heightMeasureSpec);
    // super has to be called again so the new specs are treated as
    // exact measurements.
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

Insert multiple lines into a file after specified pattern using shell script

You can use awk for inserting output of some command in the middle of input.txt.
The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.

awk 'NR==FNR {a[NR]=$0;next}
    {print}
    /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
    <(printf "%s\n" line{1..4}) input.txt

tar: file changed as we read it

Simply using an outer directory for the output, solved the problem for me.

sudo tar czf ./../31OCT18.tar.gz ./

Is it possible to return empty in react render function?

We can return like this,

return <React.Fragment />;

Turning off hibernate logging console output

Important notice: the property (part of hibernate configuration, NOT part of logging framework config!)

hibernate.show_sql

controls the logging directly to STDOUT bypassing any logging framework (which you can recognize by the missing output formatting of the messages). If you use a logging framework like log4j, you should always set that property to false because it gives you no benefit at all.

That circumstance irritated me quite a long time because I never really cared about it until I tried to write some benchmark regarding Hibernate.

Do C# Timers elapse on a separate thread?

It depends. The System.Timers.Timer has two modes of operation.

If SynchronizingObject is set to an ISynchronizeInvoke instance then the Elapsed event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke instances are none other than plain old Control and Form instances that we are all familiar with. So in that case the Elapsed event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer. Otherwise, it really depends on the specific ISynchronizeInvoke instance that was used.

If SynchronizingObject is null then the Elapsed event is invoked on a ThreadPool thread and it behaves similar to the System.Threading.Timer. In fact, it actually uses a System.Threading.Timer behind the scenes and does the marshaling operation after it receives the timer callback if needed.

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If you have a mixture of formats in your date, don't forget to set infer_datetime_format=True to make life easier.

df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)

Source: pd.to_datetime

or if you want a customized approach:

def autoconvert_datetime(value):
    formats = ['%m/%d/%Y', '%m-%d-%y']  # formats to try
    result_format = '%d-%m-%Y'  # output format
    for dt_format in formats:
        try:
            dt_obj = datetime.strptime(value, dt_format)
            return dt_obj.strftime(result_format)
        except Exception as e:  # throws exception when format doesn't match
            pass
    return value  # let it be if it doesn't match

df['date'] = df['date'].apply(autoconvert_datetime)

Angular 6 Material mat-select change method removed

I have this issue today with mat-option-group. The thing which solved me the problem is using in other provided event of mat-select : valueChange

I put here a little code for understanding :

<mat-form-field >
  <mat-label>Filter By</mat-label>
  <mat-select  panelClass="" #choosedValue (valueChange)="doSomething1(choosedValue.value)"> <!-- (valueChange)="doSomething1(choosedValue.value)" instead of (change) or other event-->

    <mat-option >-- None --</mat-option>
      <mat-optgroup  *ngFor="let group of filterData" [label]="group.viewValue"
                    style = "background-color: #0c5460">
        <mat-option *ngFor="let option of group.options" [value]="option.value">
          {{option.viewValue}}
        </mat-option>
      </mat-optgroup>
  </mat-select>
</mat-form-field>

Mat Version:

"@angular/material": "^6.4.7",

Return list from async/await method

you can use the following

private async Task<List<string>> GetItems()
{
    return await Task.FromResult(new List<string> 
    { 
      "item1", "item2", "item3" 
    });
}

Way to get number of digits in an int?

simple solution:

public class long_length {
    long x,l=1,n;
    for (n=10;n<x;n*=10){
        if (x/n!=0){
            l++;
        }
    }
    System.out.print(l);
}

'\r': command not found - .bashrc / .bash_profile

May be you used notepad++ for creating/updating this file.

EOL(Edit->EOL Conversion) Conversion by default is Windows.

Change EOL Conversion in Notepad++

Edit -> EOL Conversion -> Unix (LF)

onActivityResult is not being called in Fragment

FOR NESTED FRAGMENTS (for example, when using a ViewPager)

In your main activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

In your main top level fragment(ViewPager fragment):

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    YourFragment frag = (YourFragment) getChildFragmentManager().getFragments().get(viewPager.getCurrentItem());
    frag.yourMethod(data);  // Method for callback in YourFragment
    super.onActivityResult(requestCode, resultCode, data);
}

In YourFragment (nested fragment):

public void yourMethod(Intent data){
    // Do whatever you want with your data
}

"Object doesn't support property or method 'find'" in IE

Here is a work around. You can use filter instead of find; but filter returns an array of matching objects. find only returns the first match inside an array. So, why not use filter as following;

data.filter(function (x) {
         return x.Id === e
    })[0];

How do I move a redis database from one server to another?

I just published a command line interface utility to npm and github that allows you to copy keys that match a given pattern (even *) from one Redis database to another.

You can find the utility here:

https://www.npmjs.com/package/redis-utils-cli

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has an AjaxSetup() function that allows you to register global ajax handlers such as beforeSend and complete for all ajax calls as well as allow you to access the xhr object to do the progress that you are looking for

How do I trim whitespace from a string?

As pointed out in answers above

my_string.strip()

will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space .

For more flexibility use the following

  • Removes only leading whitespace chars: my_string.lstrip()
  • Removes only trailing whitespace chars: my_string.rstrip()
  • Removes specific whitespace chars: my_string.strip('\n') or my_string.lstrip('\n\r') or my_string.rstrip('\n\t') and so on.

More details are available in the docs.

Get operating system info

Took the following code from php manual for get_browser.

$browser = get_browser(null, true);
print_r($browser);

The $browser array has platform information included which gives you the specific Operating System in use.

Please make sure to see the "Notes" section in that page. This might be something (thismachine.info) is using if not something already pointed in other answers.

A warning - comparison between signed and unsigned integer expressions

I had the exact same problem yesterday working through problem 2-3 in Accelerated C++. The key is to change all variables you will be comparing (using Boolean operators) to compatible types. In this case, that means string::size_type (or unsigned int, but since this example is using the former, I will just stick with that even though the two are technically compatible).

Notice that in their original code they did exactly this for the c counter (page 30 in Section 2.5 of the book), as you rightly pointed out.

What makes this example more complicated is that the different padding variables (padsides and padtopbottom), as well as all counters, must also be changed to string::size_type.

Getting to your example, the code that you posted would end up looking like this:

cout << "Please enter the size of the frame between top and bottom";
string::size_type padtopbottom;
cin >> padtopbottom;

cout << "Please enter size of the frame from each side you would like: ";
string::size_type padsides; 
cin >> padsides;

string::size_type c = 0; // definition of c in the program

if (r == padtopbottom + 1 && c == padsides + 1) { // where the error no longer occurs

Notice that in the previous conditional, you would get the error if you didn't initialize variable r as a string::size_type in the for loop. So you need to initialize the for loop using something like:

    for (string::size_type r=0; r!=rows; ++r)   //If r and rows are string::size_type, no error!

So, basically, once you introduce a string::size_type variable into the mix, any time you want to perform a boolean operation on that item, all operands must have a compatible type for it to compile without warnings.

Simple prime number generator in Python

Just studied the topic, look for the examples in the thread and try to make my version:

from collections import defaultdict
# from pprint import pprint

import re


def gen_primes(limit=None):
    """Sieve of Eratosthenes"""
    not_prime = defaultdict(list)
    num = 2
    while limit is None or num <= limit:
        if num in not_prime:
            for prime in not_prime[num]:
                not_prime[prime + num].append(prime)
            del not_prime[num]
        else:  # Prime number
            yield num
            not_prime[num * num] = [num]
        # It's amazing to debug it this way:
        # pprint([num, dict(not_prime)], width=1)
        # input()
        num += 1


def is_prime(num):
    """Check if number is prime based on Sieve of Eratosthenes"""
    return num > 1 and list(gen_primes(limit=num)).pop() == num


def oneliner_is_prime(num):
    """Simple check if number is prime"""
    return num > 1 and not any([num % x == 0 for x in range(2, num)])


def regex_is_prime(num):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None


def simple_is_prime(num):
    """Simple check if number is prime
    More efficient than oneliner_is_prime as it breaks the loop
    """
    for x in range(2, num):
        if num % x == 0:
            return False
    return num > 1


def simple_gen_primes(limit=None):
    """Prime number generator based on simple gen"""
    num = 2
    while limit is None or num <= limit:
        if simple_is_prime(num):
            yield num
        num += 1


if __name__ == "__main__":
    less1000primes = list(gen_primes(limit=1000))
    assert less1000primes == list(simple_gen_primes(limit=1000))
    for num in range(1000):
        assert (
            (num in less1000primes)
            == is_prime(num)
            == oneliner_is_prime(num)
            == regex_is_prime(num)
            == simple_is_prime(num)
        )
    print("Primes less than 1000:")
    print(less1000primes)

    from timeit import timeit

    print("\nTimeit:")
    print(
        "gen_primes:",
        timeit(
            "list(gen_primes(limit=1000))",
            setup="from __main__ import gen_primes",
            number=1000,
        ),
    )
    print(
        "simple_gen_primes:",
        timeit(
            "list(simple_gen_primes(limit=1000))",
            setup="from __main__ import simple_gen_primes",
            number=1000,
        ),
    )
    print(
        "is_prime:",
        timeit(
            "[is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import is_prime",
            number=100,
        ),
    )
    print(
        "oneliner_is_prime:",
        timeit(
            "[oneliner_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import oneliner_is_prime",
            number=100,
        ),
    )
    print(
        "regex_is_prime:",
        timeit(
            "[regex_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import regex_is_prime",
            number=100,
        ),
    )
    print(
        "simple_is_prime:",
        timeit(
            "[simple_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import simple_is_prime",
            number=100,
        ),
    )

The result of running this code show interesting results:

$ python prime_time.py
Primes less than 1000:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

Timeit:
gen_primes: 0.6738066330144648
simple_gen_primes: 4.738092333020177
is_prime: 31.83770858097705
oneliner_is_prime: 3.3708438930043485
regex_is_prime: 8.692703998007346
simple_is_prime: 0.4686249239894096

So I can see that we have right answers for different questions here; for a prime number generator gen_primes looks like the right answer; but for a prime number check, the simple_is_prime function is better suited.

This works, but I am always open to better ways to make is_prime function.

How to convert QString to std::string?

Best thing to do would be to overload operator<< yourself, so that QString can be passed as a type to any library expecting an output-able type.

std::ostream& operator<<(std::ostream& str, const QString& string) {
    return str << string.toStdString();
}

Showing all session data at once?

echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";

Display yet formatting then you can view properly.

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

For linux users: possible solution.

Build error due to "Failed to delete < any-file-or-folder >" will occur if there is by chance of only delete access provided to root user rather to normal-user.

Fix : type ll command to list file that cannot be deleted, if the file is given root access, change to normal user by :

sudo chown -R user-name:user-name filename

Later try for maven clean and build.

What is an NP-complete in computer science?

It's a class of problems where we must simulate every possibility to be sure we have the optimal solution.

There are a lot of good heuristics for some NP-Complete problems, but they are only an educated guess at best.

Log4j, configuring a Web App to use a relative path

I've finally done it in this way.

Added a ServletContextListener that does the following:

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    System.setProperty("rootPath", context.getRealPath("/"));
}

Then in the log4j.properties file:

log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log

By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.

It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.

What do you think?

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

use this

select * from TableName where DateTimeField > date() and  DateTimeField < date() + 1