Programs & Examples On #Yahoo boss api

Yahoo! BOSS (Build your Own Search Service) is an API to the Yahoo! search engine index.

Could not load file or assembly '***.dll' or one of its dependencies

I recently hit this issue, the app would run fine on the developer machines and select others machines but not on recently installed machines. It turned out that the machines it did work on had the Visual C++ 11 Runtime installed while the freshly installed machines didn't. Adding the Visual C++ 11 Runtime redistributable to the app installer fixed the issue...

Is it possible to set async:false to $.getJSON call

Roll your own e.g.

function syncJSON(i_url, callback) {
  $.ajax({
    type: "POST",
    async: false,
    url: i_url,
    contentType: "application/json",
    dataType: "json",
    success: function (msg) { callback(msg) },
    error: function (msg) { alert('error : ' + msg.d); }
  });
}

syncJSON("/pathToYourResouce", function (msg) {
   console.log(msg);
})

PyCharm shows unresolved references error for valid code

I have a project where one file in src/ imports another file in the same directory. To get PyCharm to recognize I had to to go to File > Settings > Project > Project Structure > select src folder and click "Mark as: Sources"

From https://www.jetbrains.com/help/pycharm/configuring-folders-within-a-content-root.html

Source roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports

What is the difference between a 'closure' and a 'lambda'?

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

Disabling browser caching for all browsers from ASP.NET

I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.

What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function () {   
        // This function does nothing.  It won't spawn a confirmation dialog   
        // But it will ensure that the page is not cached by the browser.
    }  
</script>

This has disabled all caching in all browsers for me without fail.

Get the value in an input text box

//Get
var bla = $('#txt_name').val();

//Set
$('#txt_name').val(bla);

Update Query with INNER JOIN between tables in 2 different databases on 1 server

which may be useful

Update
    A INNER JOIN B ON A.COL1=B.COL3
SET
    A.COL2='CHANGED', A.COL4=B.COL4,......
WHERE ....;

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

Convert normal Java Array or ArrayList to Json Array in android

If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.

Something along those lines should work.

String mStringArray[] = { "String1", "String2" };

JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));

Beware that code is written offhand so consider it pseudo-code.

GitHub relative link in Markdown file

As of January 31, 2013 Github markdown supports relative links to files.

[a relative link](markdown_file.md)

However, there are a few deficiencies that have been discussed in this comment thread.

As an alternative, you can use Gitdown to construct full URLs to the repository and even make them branch aware, e.g.

{"gitdown": "gitinfo", "name": "url"} // https://github.com/gajus/gitdown
{"gitdown": "gitinfo", "name": "branch"} // master

Gitdown is a GitHub markdown preprocessor. It streamlines common tasks associated with maintaining a documentation page for a GitHub repository, e.g. generating table of contents, including variables, generating URLs and getting information about the repository itself at the time of processing the input. Gitdown seamlessly integrates with your building scripts.

I am the author of the Gitdown library.

Is there a CSS selector by class prefix?

CSS Attribute selectors will allow you to check attributes for a string. (in this case - a class-name)

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

(looks like it's actually at 'recommendation' status for 2.1 and 3)


Here's an outline of how I *think it works:

  • [ ] : is the container for complex selectors if you will...
  • class : 'class' is the attribute you are looking at in this case.
  • * : modifier(if any): in this case - "wildcard" indicates you're looking for ANY match.
  • test- : the value (assuming there is one) of the attribute - that contains the string "test-" (which could be anything)

So, for example:

[class*='test-'] {
  color: red;
}

You could be more specific if you have good reason, with the element too

ul[class*='test-'] > li { ... }

I've tried to find edge cases, but I see no need to use a combination of ^ and * - as * gets everything...

example: http://codepen.io/sheriffderek/pen/MaaBwp

http://caniuse.com/#feat=css-sel2

Everything above IE6 will happily obey. : )

note that:

[class] { ... }

Will select anything with a class...

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${xx.id} <br>
</c:forEach>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.

So make sure about space. They play crucial role sometimes. :p

Amazon S3 upload file and get URL

@hussachai and @Jeffrey Kemp answers are pretty good. But they have something in common is the url returned is of virtual-host-style, not in path style. For more info regarding to the s3 url style, can refer to AWS S3 URL Styles. In case of some people want to have path style s3 url generated. Here's the step. Basically everything will be the same as @hussachai and @Jeffrey Kemp answers, only with one line setting change as below:

AmazonS3Client s3Client = (AmazonS3Client) AmazonS3ClientBuilder.standard()
                    .withRegion("us-west-2")
                    .withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
                    .withPathStyleAccessEnabled(true)
                    .build();

// Upload a file as a new object with ContentType and title specified.
PutObjectRequest request = new PutObjectRequest(bucketName, stringObjKeyName, fileToUpload);
s3Client.putObject(request);
URL s3Url = s3Client.getUrl(bucketName, stringObjKeyName);
logger.info("S3 url is " + s3Url.toExternalForm());

This will generate url like: https://s3.us-west-2.amazonaws.com/mybucket/myfilename

Angular 4.3 - HttpClient set params

Before 5.0.0-beta.6

let httpParams = new HttpParams();
Object.keys(data).forEach(function (key) {
     httpParams = httpParams.append(key, data[key]);
});

Since 5.0.0-beta.6

Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)

Going forward the object can be passed directly instead of HttpParams.

getCountries(data: any) {
    // We don't need any more these lines
    // let httpParams = new HttpParams();
    // Object.keys(data).forEach(function (key) {
    //     httpParams = httpParams.append(key, data[key]);
    // });

    return this.httpClient.get("/api/countries", {params: data})
}

slideToggle JQuery right to left

You can do this using additional effects as a part of jQuery-ui

$('.show_hide').click(function () {
    $(".slidingDiv").toggle("slide");
});

Test Link

Reading a text file and splitting it into single words in python

What you can do is use nltk to tokenize words and then store all of the words in a list, here's what I did. If you don't know nltk; it stands for natural language toolkit and is used to process natural language. Here's some resource if you wanna get started [http://www.nltk.org/book/]

import nltk 
from nltk.tokenize import word_tokenize 
file = open("abc.txt",newline='')
result = file.read()
words = word_tokenize(result)
for i in words:
       print(i)

The output will be this:

09807754
18
n
03
aristocrat
0
blue_blood
0
patrician

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

ECMAScript 6 introduced String.prototype.includes:

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

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

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

Command to get latest Git commit hash from a branch

In a comment you wrote

i want to show that there is a difference in local and github repo

As already mentioned in another answer, you should do a git fetch origin first. Then, if the remote is ahead of your current branch, you can list all commits between your local branch and the remote with

git log master..origin/master --stat

If your local branch is ahead:

git log origin/master..master --stat

--stat shows a list of changed files as well.

If you want to explicitly list the additions and deletions, use git diff:

git diff master origin/master

Function is not defined - uncaught referenceerror

One more thing. In my experience this error occurred because there was another error previous to the Function is not defined - uncaught referenceerror.

So, look through the console to see if a previous error exists and if so, correct any that exist. You might be lucky in that they were the problem.

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

.Cells(.Rows.Count,"A").End(xlUp).row

I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:

.Cells(Rows.Count,"A").End(xlUp).row

Before the Cells, you can write your worksheet name, for example:

Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row

The worksheet name is not necessary when you operate on the same worksheet.

Best practice for REST token-based authentication with JAX-RS and Jersey

This answer is all about authorization and it is a complement of my previous answer about authentication

Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.


Supporting role-based authorization with the @Secured annotation

Besides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.

Create an enumeration and define the roles according to your needs:

public enum Role {
    ROLE_1,
    ROLE_2,
    ROLE_3
}

Change the @Secured name binding annotation created before to support roles:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
    Role[] value() default {};
}

And then annotate the resource classes and methods with @Secured to perform the authorization. The method annotations will override the class annotations:

@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // But it's declared within a class annotated with @Secured({Role.ROLE_1})
        // So it only can be executed by the users who have the ROLE_1 role
        ...
    }

    @DELETE
    @Path("{id}")    
    @Produces(MediaType.APPLICATION_JSON)
    @Secured({Role.ROLE_1, Role.ROLE_2})
    public Response myOtherMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
        // The method annotation overrides the class annotation
        // So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
        ...
    }
}

Create a filter with the AUTHORIZATION priority, which is executed after the AUTHENTICATION priority filter defined previously.

The ResourceInfo can be used to get the resource Method and resource Class that will handle the request and then extract the @Secured annotations from them:

@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the resource class which matches with the requested URL
        // Extract the roles declared by it
        Class<?> resourceClass = resourceInfo.getResourceClass();
        List<Role> classRoles = extractRoles(resourceClass);

        // Get the resource method which matches with the requested URL
        // Extract the roles declared by it
        Method resourceMethod = resourceInfo.getResourceMethod();
        List<Role> methodRoles = extractRoles(resourceMethod);

        try {

            // Check if the user is allowed to execute the method
            // The method annotations override the class annotations
            if (methodRoles.isEmpty()) {
                checkPermissions(classRoles);
            } else {
                checkPermissions(methodRoles);
            }

        } catch (Exception e) {
            requestContext.abortWith(
                Response.status(Response.Status.FORBIDDEN).build());
        }
    }

    // Extract the roles from the annotated element
    private List<Role> extractRoles(AnnotatedElement annotatedElement) {
        if (annotatedElement == null) {
            return new ArrayList<Role>();
        } else {
            Secured secured = annotatedElement.getAnnotation(Secured.class);
            if (secured == null) {
                return new ArrayList<Role>();
            } else {
                Role[] allowedRoles = secured.value();
                return Arrays.asList(allowedRoles);
            }
        }
    }

    private void checkPermissions(List<Role> allowedRoles) throws Exception {
        // Check if the user contains one of the allowed roles
        // Throw an Exception if the user has not permission to execute the method
    }
}

If the user has no permission to execute the operation, the request is aborted with a 403 (Forbidden).

To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext (which should be already set in the ContainerRequestContext) or inject it using CDI, depending on the approach you go for.

If a @Secured annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.

Supporting role-based authorization with JSR-250 annotations

Alternatively to defining the roles in the @Secured annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed, @PermitAll and @DenyAll.

JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:

So an authorization filter that checks JSR-250 annotations could be like:

@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Method method = resourceInfo.getResourceMethod();

        // @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
        if (method.isAnnotationPresent(DenyAll.class)) {
            refuseRequest();
        }

        // @RolesAllowed on the method takes precedence over @PermitAll
        RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
            return;
        }

        // @PermitAll on the method takes precedence over @RolesAllowed on the class
        if (method.isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // @DenyAll can't be attached to classes

        // @RolesAllowed on the class takes precedence over @PermitAll on the class
        rolesAllowed = 
            resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
        }

        // @PermitAll on the class
        if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // Authentication is required for non-annotated methods
        if (!isAuthenticated(requestContext)) {
            refuseRequest();
        }
    }

    /**
     * Perform authorization based on roles.
     *
     * @param rolesAllowed
     * @param requestContext
     */
    private void performAuthorization(String[] rolesAllowed, 
                                      ContainerRequestContext requestContext) {

        if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
            refuseRequest();
        }

        for (final String role : rolesAllowed) {
            if (requestContext.getSecurityContext().isUserInRole(role)) {
                return;
            }
        }

        refuseRequest();
    }

    /**
     * Check if the user is authenticated.
     *
     * @param requestContext
     * @return
     */
    private boolean isAuthenticated(final ContainerRequestContext requestContext) {
        // Return true if the user is authenticated or false otherwise
        // An implementation could be like:
        // return requestContext.getSecurityContext().getUserPrincipal() != null;
    }

    /**
     * Refuse the request.
     */
    private void refuseRequest() {
        throw new AccessDeniedException(
            "You don't have permissions to perform this action.");
    }
}

Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature. If you use Jersey, you don't need to write your own filter, just use the existing implementation.

How do I install SciPy on 64 bit Windows?

It is terrible to install such Python data science packages independently on Windows. Try Anaconda (one installer, 400 more Python packages, py2 & py3 support). Anaconda really helps me a lot!

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

Unable to set default python version to python3 in ubuntu

As an added extra, you can add an alias for pip as well (in .bashrc or bash_aliases):

alias pip='pip3'

You many find that a clean install of python3 actually points to python3.x so you may need:

alias pip='pip3.6'
alias python='python3.6'

How do I set the background color of Excel cells using VBA?

You can use either:

ActiveCell.Interior.ColorIndex = 28

or

ActiveCell.Interior.Color = RGB(255,0,0)

syntaxerror: unexpected character after line continuation character in python

You need to quote that filename:

f = open("D\\python\\HW\\2_1 - Copy.cp", "r")

Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:

print "This is a long",\
      "line of text",\
      "that I'm printing."

Also, you shouldn't have semicolons (;) at the end of your statements in Python.

Select option padding not working in chrome

You can use font-size property for option if you need.

T-SQL datetime rounded to nearest minute and nearest hours with using functions

"Rounded" down as in your example. This will return a varchar value of the date.

DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'

SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15

linux find regex

Note that -regex depends on whole path.

 -regex pattern
              File name matches regular expression pattern.  
              This is a match on the whole path, not a search.

You don't actually have to use -regex for what you are doing.

find . -iname "*[0-9]"

SQL select everything in an array

// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');

// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';

// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;

// see what you get
var_dump($sql);

Update: (a short version and update missing comma)

$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';

Getting the PublicKeyToken of .Net assemblies

You can get this easily via c#

private static string GetPublicKeyTokenFromAssembly(Assembly assembly)
{
    var bytes = assembly.GetName().GetPublicKeyToken();
    if (bytes == null || bytes.Length == 0)
        return "None";

    var publicKeyToken = string.Empty;
    for (int i = 0; i < bytes.GetLength(0); i++)
        publicKeyToken += string.Format("{0:x2}", bytes[i]);

    return publicKeyToken;
}

How to enable SOAP on CentOS

I installed php-soap to CentOS Linux release 7.1.1503 (Core) using following way.

1) yum install php-soap

================================================================================
 Package              Arch           Version                 Repository    Size
================================================================================
Installing:
 php-soap             x86_64         5.4.16-36.el7_1         base         157 k
Updating for dependencies:
 php                  x86_64         5.4.16-36.el7_1         base         1.4 M
 php-cli              x86_64         5.4.16-36.el7_1         base         2.7 M
 php-common           x86_64         5.4.16-36.el7_1         base         563 k
 php-devel            x86_64         5.4.16-36.el7_1         base         600 k
 php-gd               x86_64         5.4.16-36.el7_1         base         126 k
 php-mbstring         x86_64         5.4.16-36.el7_1         base         503 k
 php-mysql            x86_64         5.4.16-36.el7_1         base          99 k
 php-pdo              x86_64         5.4.16-36.el7_1         base          97 k
 php-xml              x86_64         5.4.16-36.el7_1         base         124 k

Transaction Summary
================================================================================
Install  1 Package
Upgrade             ( 9 Dependent packages)

Total download size: 6.3 M
Is this ok [y/d/N]: y
Downloading packages:
------
------
------

Installed:
  php-soap.x86_64 0:5.4.16-36.el7_1

Dependency Updated:
  php.x86_64 0:5.4.16-36.el7_1          php-cli.x86_64 0:5.4.16-36.el7_1
  php-common.x86_64 0:5.4.16-36.el7_1   php-devel.x86_64 0:5.4.16-36.el7_1
  php-gd.x86_64 0:5.4.16-36.el7_1       php-mbstring.x86_64 0:5.4.16-36.el7_1
  php-mysql.x86_64 0:5.4.16-36.el7_1    php-pdo.x86_64 0:5.4.16-36.el7_1
  php-xml.x86_64 0:5.4.16-36.el7_1

Complete!

2) yum search php-soap

============================ N/S matched: php-soap =============================
php-soap.x86_64 : A module for PHP applications that use the SOAP protocol

3) service httpd restart

To verify run following

4) php -m | grep -i soap

soap

Difference between AutoPostBack=True and AutoPostBack=False?

AutoPostBack = true permits control to post back to the server. It is associated with an Event.

Example:

<asp:DropDownList id="id" runat="server" AutoPostBack="true" OnSelectIndexChanged="..."/>

The aspx page with the above drop down list does not need an asp:button to do the post back. When you change an option in the drop down list, the page gets posted back to the server.

Default value of AutoPostBack on control is false.

Create a dropdown component

If you want something with a dropdown (some list of values) and a user specified value that can be filled into the selected input as well. This custom dropdown in angular also has a filter dropdown list on key value entered. Please check this stackblitzlink -> https://stackblitz.com/edit/angular-l9guzo?embed=1&file=src/app/custom-textarea.component.ts

Header set Access-Control-Allow-Origin in .htaccess doesn't work

try this:

<IfModule mod_headers.c>
     Header set Access-Control-Allow-Credentials true
     Header set Access-Control-Allow-Origin "your domain"
     Header set Access-Control-Allow-Headers "X-Requested-With"
</IfModule>

It's preferable to allow a list of know trusted host.

Using scp to copy a file to Amazon EC2 instance?

The process of using SCP to copy files from a local machine to an AWS EC2 Linux instance is covered step-by-step (including the points mentioned below) in this video.

To correct this particular issue with using SCP:

  1. You need to specify the correct Linux user. From Amazon:

    • For Amazon Linux, the user name is ec2-user.
    • For RHEL, the user name is ec2-user or root.
    • For Ubuntu, the user name is ubuntu or root.
    • For Centos, the user name is centos.
    • For Fedora, the user name is ec2-user.
    • For SUSE, the user name is ec2-user or root.
    • Otherwise, if ec2-user and root don't work, check with your AMI provider.
  2. Your private key must not be publicly visible. Run the following command so that only the root user can read the file.

    chmod 400 /path/to/yourKeyFile.pem
    

How to vertically align elements in a div?

To position block elements to the center (works in IE9 and above), needs a wrapper div:

.vcontainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
}

SQL Server® 2016, 2017 and 2019 Express full download

Download the developer edition. There you can choose Express as license when installing.

enter image description here

jQuery - Increase the value of a counter when a button is clicked

$(document).ready(function() {
var count = 0;

  $("#update").click(function() {
    count++;
    $("#counter").html("My current count is: "+count);
  }

});

<div id="counter"></div>

Convert timedelta to total seconds

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.

(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.

(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:

gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.

I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow() which won't jump by an hour when DST goes on/off and may give you more precision than time.time()

Does swift have a trim method on String?

In Swift3 XCode 8 Final

Notice that the CharacterSet.whitespaces is not a function anymore!

(Neither is NSCharacterSet.whitespaces)

extension String {
    func trim() -> String {
        return self.trimmingCharacters(in: CharacterSet.whitespaces)
    }
}

How to open every file in a folder

you should try using os.walk

yourpath = 'path'

import os
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        print(os.path.join(root, name))
        stuff
    for name in dirs:
        print(os.path.join(root, name))
        stuff

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%' 

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

ExecuteNonQuery: Connection property has not been initialized.

You are not initializing connection.That's why this kind of error is coming to you.

Your code:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");

Corrected code:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);

How to filter Android logcat by application?

Edit: The original is below. When one Android Studio didn't exist. But if you want to filter on your entire application I would use pidcat for terminal viewing or Android Studio. Using pidcat instead of logcat then the tags don't need to be the application. You can just call it with pidcat com.your.application

You should use your own tag, look at: http://developer.android.com/reference/android/util/Log.html

Like.

Log.d("AlexeysActivity","what you want to log");

And then when you want to read the log use>

adb logcat -s AlexeysActivity 

That filters out everything that doesn't use the same tag.

ValueError: math domain error

Your code is doing a log of a number that is less than or equal to zero. That's mathematically undefined, so Python's log function raises an exception. Here's an example:

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    log(-1)
ValueError: math domain error

Without knowing what your newtonRaphson2 function does, I'm not sure I can guess where the invalid x[2] value is coming from, but hopefully this will lead you on the right track.

Python 3 turn range to a list

Python 3:

my_list = [*range(1001)]

How to install a private NPM module without my own registry?

This was what I was looking for:

# Get the latest from GitHub, public repo:
$ npm install username/my-new-project --save-dev
# Bitbucket, private repo:
$ npm install git+https://token:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master

# … or from Bitbucket, public repo:
$ npm install git+ssh://[email protected]/username/my-new-project.git#master --save-dev
# Bitbucket, private repo:
$ npm install git+https://username:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master
# Or, if you published as npm package:
$ npm install my-new-project --save-dev

How to copy a folder via cmd?

xcopy  "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i

Probably the problem is the space.Try with quotes.

Specifying number of decimal places in Python

This standard library solution likely has not been mentioned because the question is so dated. While these answers may scale to the other use cases beyond currency where differing levels of decimals are required, it seems you need it for currency.

I recommend you use the standard library locale.currency object. It seems to have been created to address this problem of currency representation.

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

locale.currency(1.23)
>>>'$1.23'
locale.currency(1.53251)
>>>'$1.23'
locale.currency(1)
>>>'$1.00'

locale.currency(mealPrice)

Currency generalizes to other countries as well.

rake assets:precompile RAILS_ENV=production not working as required

Have you added this gem to your gemfile?

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

move that gem out of assets group and then run bundle again, I hope that would help!

How do I check if an object has a specific property in JavaScript?

if (x.key !== undefined)

Armin Ronacher seems to have already beat me to it, but:

Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};

x = {'key': 1};

if (x.hasOwnProperty('key')) {
    alert('have key!');
}

if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}

A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:

Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};

Sending a file over TCP sockets in Python

you may change your loop condition according to following code, when length of l is smaller than buffer size it means that it reached end of file

while (True):
    print "Receiving..."
    l = c.recv(1024)        
    f.write(l)
    if len(l) < 1024:
        break

Parse HTML in Android

Have you tried using Html.fromHtml(source)?

I think that class is pretty liberal with respect to source quality (it uses TagSoup internally, which was designed with real-life, bad HTML in mind). It doesn't support all HTML tags though, but it does come with a handler you can implement to react on tags it doesn't understand.

Java: is there a map function?

This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/

sequence(1, 2).map(toString); // lazily returns "1", "2"

How to style a JSON block in Github Wiki?

2019 Github Solution

```yaml
{
   "this-json": "looks awesome..."
}

Result

enter image description here

If you want to have keys a different colour to the parameters, set your language as yaml

@Ankanna's answer gave me the idea of going through github's supported language list and yaml was my best find.

Select from one table matching criteria in another?

You should make tags their own table with a linking table.

items:
id    object
1     lamp  
2     table   
3     stool  
4     bench 

tags:
id     tag
1      furniture
2      chair

items_tags:
item_id tag_id
1       1
2       1
3       1
4       1
3       2
4       2

Passing a variable from one php include file to another: global vs. not

Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.

include('front.inc');
global $name;

function foo() {
  echo $name;
}

function bar() {
  echo $name;
}

foo();
bar();

will only show errors. The correct way to do that would be:

include('front.inc');

function foo() {
  global $name;
  echo $name;
}

function bar() {
  global $name;
  echo $name;
}

foo();
bar();

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

In Addition to Ben's Answer, You can try Below Queries as per your need

USE {database-name};  
GO  
-- Truncate the log by changing the database recovery model to SIMPLE.  
ALTER DATABASE {database-name}
SET RECOVERY SIMPLE;  
GO  
-- Shrink the truncated log file to 1 MB.  
DBCC SHRINKFILE ({database-file-name}, 1);  
GO  
-- Reset the database recovery model.  
ALTER DATABASE {database-name}
SET RECOVERY FULL;  
GO 

Update Credit @cema-sp

To find database file names use below query

select * from sys.database_files;

Randomize numbers with jQuery?

Others have answered the question, but just for the fun of it, here is a visual dice throwing example, using the Math.random javascript method, a background image and some recursive timeouts.

http://www.jsfiddle.net/zZUgF/3/

A project with an Output Type of Class Library cannot be started directly

Just needs to go:

Solution Explorer-->Go to Properties --->change(Single Startup project) from.dll to .web

Then try to debug it.

Surely your problem will be solved.

Difference between Console.Read() and Console.ReadLine()?

These are the methods of system.console

  • ReadKey() (returns a character): reads only one single character from the standard input stream or command line. Usually used when you're giving options to the user in the console to select from, such as select A, B or C. Another prominent example, Press Y or n to continue.
  • ReadLine() (returns a string): or Console.Readline() reads a single line from the standard input stream or the command line. As an example, it can be used to ask the user enter their name or age. It reads all the character till we press enter.
  • Read() (returns an int): or Console.Read() reads only one single character from the standard input stream. Similar to ReadKey except that it returns an integer. It returns the next character from the input stream, or returns (-1) if there is no more character to be read.

(There are more system.console methods like write() and writeline() as well which are used to write in command line, behaving similarly as read() and readline() methods)

This was clearly described with examples in the MSDN documentation (links are included above).

Effective way to find any file's Encoding

It may be useful

string path = @"address/to/the/file.extension";

using (StreamReader sr = new StreamReader(path))
{ 
    Console.WriteLine(sr.CurrentEncoding);                        
}

how to realize countifs function (excel) in R

Here an example with 100000 rows (occupations are set here from A to Z):

> a = data.frame(sex=sample(c("M", "F"), 100000, replace=T), occupation=sample(LETTERS, 100000, replace=T))
> sum(a$sex == "M" & a$occupation=="A")
[1] 1882

returns the number of males with occupation "A".

EDIT

As I understand from your comment, you want the counts of all possible combinations of sex and occupation. So first create a dataframe with all combinations:

combns = expand.grid(c("M", "F"), LETTERS)

and loop with apply to sum for your criteria and append the results to combns:

combns = cbind (combns, apply(combns, 1, function(x)sum(a$sex==x[1] & a$occupation==x[2])))
colnames(combns) = c("sex", "occupation", "count")

The first rows of your result look as follows:

  sex occupation count
1   M          A  1882
2   F          A  1869
3   M          B  1866
4   F          B  1904
5   M          C  1979
6   F          C  1910

Does this solve your problem?

OR:

Much easier solution suggested by thelatemai:

table(a$sex, a$occupation)


       A    B    C    D    E    F    G    H    I    J    K    L    M    N    O
  F 1869 1904 1910 1907 1894 1940 1964 1907 1918 1892 1962 1933 1886 1960 1972
  M 1882 1866 1979 1904 1895 1845 1946 1905 1999 1994 1933 1950 1876 1856 1911

       P    Q    R    S    T    U    V    W    X    Y    Z
  F 1908 1907 1883 1888 1943 1922 2016 1962 1885 1898 1889
  M 1928 1938 1916 1927 1972 1965 1946 1903 1965 1974 1906

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,

  • Xpath engines are different in each browser, hence make them inconsistent
  • IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
  • Xpath tend to become complex and hence make hard to read in my opinion

However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).

You can read blog from Simon here . He also recommends CSS over Xpath.

If you are testing content then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles etc. Here is my blog that explains it in detail.

edit 1

Thanks to @parishodak, here is the link which provides the numbers proving that CSS performance is better

What is the difference between baud rate and bit rate?

This topic is confusing because there are 3 terms in use when people think there are just 2, namely:

"bit rate": units are bits per second

"baud": units are symbols per second

"Baud rate": units are bits per second

"Baud rate" is really a marketing term rather than an engineering term. "Baud rate" was used by modem manufactures in a similar way to megapixels is used for digital cameras. So the higher the "Baud rate" the better the modem was perceived to be.

The engineering unit "baud" is already a rate (symbols per second) which distinguishes it from the "Baud rate" term. However, you can see from the answers that people are confusing these 2 terms together such as baud/sec which is wrong.

From an engineering point of view, I recommend people use the term "bit rate" for "RS-232" and consign to history the term "Baud rate". Use the term "baud" for modulation schemes but avoid it for "RS-232".

In other words, "bit rate" and "Baud rate" are the same thing which means how many bits are transmitted along a wire in one second. Note that bits per second (bps) is the low-level line rate and not the information data rate because asynchronous "RS-232" has start and stop bits that frame the 8 data bits of information so bps includes all bits transmitted.

C++ unordered_map using a custom class type as the key

I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:

  1. You can define a comparison function for an unordered_map separately, instead of using the equality comparison operator (operator==). This might be helpful, for example, if you want to use the latter for comparing all members of two Node objects to each other, but only some specific members as key of an unordered_map.
  2. You can also use lambda expressions instead of defining the hash and comparison functions.

All in all, for your Node class, the code could be written as follows:

using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);

Notes:

  • I just reused the hashing method at the end of jogojapan's answer, but you can find the idea for a more general solution here (if you don't want to use Boost).
  • My code is maybe a bit too minified. For a slightly more readable version, please see this code on Ideone.

TypeScript: Interfaces vs Types

Examples with Types:

// create a tree structure for an object. You can't do the same with interface because of lack of intersection (&)

type Tree<T> = T & { parent: Tree<T> };

// type to restrict a variable to assign only a few values. Interfaces don't have union (|)

type Choise = "A" | "B" | "C";

// thanks to types, you can declare NonNullable type thanks to a conditional mechanism.

type NonNullable<T> = T extends null | undefined ? never : T;

Examples with Interface:

// you can use interface for OOP and use 'implements' to define object/class skeleton

interface IUser {
    user: string;
    password: string;
    login: (user: string, password: string) => boolean;
}

class User implements IUser {
    user = "user1"
    password = "password1"

    login(user: string, password: string) {
        return (user == user && password == password)
    }
}

// you can extend interfaces with other interfaces

    interface IMyObject {
        label: string,
    }

    interface IMyObjectWithSize extends IMyObject{
        size?: number
    }

Javascript add method to object

You can make bar a function making it a method.

Foo.bar = function(passvariable){  };

As a property it would just be assigned a string, data type or boolean

Foo.bar = "a place";

Shortcut to exit scale mode in VirtualBox

If Right Ctrl (Host Key) + C does not work (there have been some issues on Ubuntu), do the following:

1) File > Preferences > Input on the Virtual Machine which is stuck in Scale Mode

2) Change or Reset the Host Key. There's no need to even save after changing the settings

3) Re-open the Virtual Machine and it should be reset!

Disable/enable an input with jQuery?

this works for me

$("#values:input").attr("disabled",true);
$("#values:input").attr("disabled",false);

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/> button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )

btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs

Chrome - ERR_CACHE_MISS

This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.

Regular Expression For Duplicate Words

The below expression should work correctly to find any number of consecutive words. The matching can be case insensitive.

String regex = "\\b(\\w+)(\\s+\\1\\b)*";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

Matcher m = p.matcher(input);

// Check for subsequences of input that match the compiled pattern
while (m.find()) {
     input = input.replaceAll(m.group(0), m.group(1));
}

Sample Input : Goodbye goodbye GooDbYe

Sample Output : Goodbye

Explanation:

The regex expression:

\b : Start of a word boundary

\w+ : Any number of word characters

(\s+\1\b)* : Any number of space followed by word which matches the previous word and ends the word boundary. Whole thing wrapped in * helps to find more than one repetitions.

Grouping :

m.group(0) : Shall contain the matched group in above case Goodbye goodbye GooDbYe

m.group(1) : Shall contain the first word of the matched pattern in above case Goodbye

Replace method shall replace all consecutive matched words with the first instance of the word.

Storing a Key Value Array into a compact JSON string

For use key/value pair in json use an object and don't use array

Find name/value in array is hard but in object is easy

Ex:

_x000D_
_x000D_
var exObj = {_x000D_
  "mainData": {_x000D_
    "slide0001.html": "Looking Ahead",_x000D_
    "slide0008.html": "Forecast",_x000D_
    "slide0021.html": "Summary",_x000D_
    // another THOUSANDS KEY VALUE PAIRS_x000D_
    // ..._x000D_
  },_x000D_
  "otherdata" : { "one": "1", "two": "2", "three": "3" }_x000D_
};_x000D_
var mainData = exObj.mainData;_x000D_
// for use:_x000D_
Object.keys(mainData).forEach(function(n,i){_x000D_
  var v = mainData[n];_x000D_
  console.log('name' + i + ': ' + n + ', value' + i + ': ' + v);_x000D_
});_x000D_
_x000D_
// and string length is minimum_x000D_
console.log(JSON.stringify(exObj));_x000D_
console.log(JSON.stringify(exObj).length);
_x000D_
_x000D_
_x000D_

live output from subprocess command

Based on all the above I suggest a slightly modified version (python3):

  • while loop calling readline (The iter solution suggested seemed to block forever for me - Python 3, Windows 7)
  • structered so handling of read data does not need to be duplicated after poll returns not-None
  • stderr piped into stdout so both output outputs are read
  • Added code to get exit value of cmd.

Code:

import subprocess
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT, universal_newlines=True)
while True:
    rd = proc.stdout.readline()
    print(rd, end='')  # and whatever you want to do...
    if not rd:  # EOF
        returncode = proc.poll()
        if returncode is not None:
            break
        time.sleep(0.1)  # cmd closed stdout, but not exited yet

# You may want to check on ReturnCode here

Java Multiple Inheritance

Ehm, your class can be the subclass for only 1 other, but still, you can have as many interfaces implemented, as you wish.

A Pegasus is in fact a horse (it is a special case of a horse), which is able to fly (which is the "skill" of this special horse). From the other hand, you can say, the Pegasus is a bird, which can walk, and is 4legged - it all depends, how it is easier for you to write the code.

Like in your case you can say:

abstract class Animal {
   private Integer hp = 0; 
   public void eat() { 
      hp++; 
   }
}
interface AirCompatible { 
   public void fly(); 
}
class Bird extends Animal implements AirCompatible { 
   @Override
   public void fly() {  
       //Do something useful
   }
} 
class Horse extends Animal {
   @Override
   public void eat() { 
      hp+=2; 
   }

}
class Pegasus extends Horse implements AirCompatible {
   //now every time when your Pegasus eats, will receive +2 hp  
   @Override
   public void fly() {  
       //Do something useful
   }
}

MySQL: how to get the difference between two timestamps in seconds

Note that the TIMEDIFF() solution only works when the datetimes are less than 35 days apart! TIMEDIFF() returns a TIME datatype, and the max value for TIME is 838:59:59 hours (=34,96 days)

base_url() function not working in codeigniter

I encountered with this issue spending couple of hours, however solved it in different ways. You can see, I have just created an assets folder outside application folder. Finally I linked my style sheet in the page header section. Folder structure are below images.

enter image description here enter image description here

Before action this you should include url helper file either in your controller class method/__constructor files or by in autoload.php file. Also change $config['base_url'] = 'http://yoursiteurl'; in the following file application/config/config.php

If you include it in controller class method/__constructor then it look like

public function __construct()
{
    $this->load->helper('url');
}

or If you load in autoload file then it would looks like

$autoload['helper'] = array('url'); 

Finally, add your stylesheet file. You can link a style sheet by different ways, include it in your inside section

-><link rel="stylesheet" href="<?php echo base_url();?>assets/css/style.css" type="text/css" />

-> or

<?php

    $main = array(
    'href'       => 'assets/css/style.css',
    'rel'        => 'stylesheet',
    'type'       => 'text/css',
    'title'      => 'main stylesheet',
    'media'      => 'all',
    'index_page' => true
    );


echo link_tag($main); ?>

-> or

finally I get more reliable code cleaner concept. Just create a config file, named styles.php in you application/config/styles.php folder. Then add some links in styles.php file looks like below

<?php
 $config['style'] = array(
    'main' => array(
        'href'       => 'assets/css/style.css',
        'rel'        => 'stylesheet',
        'type'       => 'text/css',
        'title'      => 'main stylesheet',
        'media'      => 'all',
        'index_page' => true
    )
 );

?>

call/add this config to your controller class method looks like below

$this->config->load('styles');
$data['style'] = $this->config->config['style'];

Pass this data in your header template looks like below.

$this->load->view('templates/header', $data);

And finally add or link your css file looks like below.

<?php echo link_tag($style['main']); ?>

Subtract two variables in Bash

You just need a little extra whitespace around the minus sign, and backticks:

COUNT=`expr $FIRSTV - $SECONDV`

Be aware of the exit status:

The exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null or 0.

Keep this in mind when using the expression in a bash script in combination with set -e which will exit immediately if a command exits with a non-zero status.

SQL: How to get the id of values I just INSERTed?

From the site i found out the following things:

SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record March 25, 2007 by pinaldave

SELECT @@IDENTITY It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY() It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

SELECT IDENT_CURRENT(‘tablename’) It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How does a Breadth-First Search work when looking for Shortest Path?

Based on acheron55 answer I posted a possible implementation here.
Here is a brief summery of it:

All you have to do, is to keep track of the path through which the target has been reached. A simple way to do it, is to push into the Queue the whole path used to reach a node, rather than the node itself.
The benefit of doing so is that when the target has been reached the queue holds the path used to reach it.
This is also applicable to cyclic graphs, where a node can have more than one parent.

How to access pandas groupby dataframe by key

You can use the get_group method:

In [21]: gb.get_group('foo')
Out[21]: 
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

Note: This doesn't require creating an intermediary dictionary / copy of every subdataframe for every group, so will be much more memory-efficient than creating the naive dictionary with dict(iter(gb)). This is because it uses data-structures already available in the groupby object.


You can select different columns using the groupby slicing:

In [22]: gb[["A", "B"]].get_group("foo")
Out[22]:
     A         B
0  foo  1.624345
2  foo -0.528172
4  foo  0.865408

In [23]: gb["C"].get_group("foo")
Out[23]:
0     5
2    11
4    14
Name: C, dtype: int64

Getting data from Yahoo Finance

As from the answer from BrianC use the YQL console. But after selecting the "Show Community Tables" go to the bottom of the tables list and expand yahoo where you find plenty of yahoo.finance tables:

Stock Quotes:

  • yahoo.finance.quotes
  • yahoo.finance.historicaldata

Fundamental analysis:

  • yahoo.finance.keystats
  • yahoo.finance.balancesheet
  • yahoo.finance.incomestatement
  • yahoo.finance.analystestimates
  • yahoo.finance.dividendhistory

Technical analysis:

  • yahoo.finance.historicaldata
  • yahoo.finance.quotes
  • yahoo.finance.quant
  • yahoo.finance.option*

General financial information:

  • yahoo.finance.industry
  • yahoo.finance.sectors
  • yahoo.finance.isin
  • yahoo.finance.quoteslist
  • yahoo.finance.xchange

2/Nov/2017: Yahoo finance has apparently killed this API, for more info and alternative resources see https://news.ycombinator.com/item?id=15616880

Most efficient way to increment a Map value in Java

I suggest to use Java 8 Map::compute(). It considers the case when a key doesn't exist, too.

Map.compute(num, (k, v) -> (v == null) ? 1 : v + 1);

How can I customize the tab-to-space conversion factor?

You want to make sure your editorconfig is not conflicting with your user or workspace settings configuration, as I just had a bit of annoyance thinking the settings files settings were not being applied when it was my editor configuration undoing those changes.

Take n rows from a spark dataframe and pass to toPandas()

You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])

df_pandas = pd.DataFrame(df.head(3), columns=df.columns)

In [4]: df_pandas
Out[4]: 
     name  age
0   Alice    1
1     Jim    2
2  Sandra    3

Simple VBA selection: Selecting 5 cells to the right of the active cell

This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.

Sub Copy5CellsToRight()
    ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub

If you want to include the activecell in the range that gets copied, you don't need the offset:

Sub ExtendAndCopy5CellsToRight()
    ActiveCell.Resize(1, 6).Copy
End Sub

Note that you don't need to select before copying.

Regex in JavaScript for validating decimal numbers

 function CheckValidAmount() {
        var amounttext = document.getElementById('txtRemittanceNumber').value;            
        if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
            alert('Please enter only numbers into amount textbox.')
            document.getElementById('txtRemittanceNumber').value = "10.00";
        }
    }

This is the function which will take decimal number with any number of decimal places and without any decimal places.

Thanks ... :)

How do I convert a column of text URLs into active hyperlinks in Excel?

Put the URLs into an HTML table, load the HTML page into a browser, copy the contents of that page, paste into Excel. At this point the URLs are preserved as active links.

Solution was proposed on http://answers.microsoft.com/en-us/mac/forum/macoffice2008-macexcel/how-to-copy-and-paste-to-mac-excel-2008-a-list-of/c5fa2890-acf5-461d-adb5-32480855e11e by (Jim Gordon Mac MVP)[http://answers.microsoft.com/en-us/profile/75a2b744-a259-49bb-8eb1-7db61dae9e78]

I found that it worked.

I had these URLs:

https://twitter.com/keeseter/status/578350771235872768/photo/1 https://instagram.com/p/ys5ASPCDEV/ https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/10881854_329617847240910_1814142151_n.jpg https://twitter.com/ranadotson/status/539485028712189952/photo/1 https://instagram.com/p/0OgdvyxMhW/ https://instagram.com/p/1nynTiiLSb/

I put them into an HTML file (links.html) like this:

<table>
<tr><td><a href="https://twitter.com/keeseter/status/578350771235872768/photo/1">https://twitter.com/keeseter/status/578350771235872768/photo/1</a></td></tr>
<tr><td><a href="https://instagram.com/p/ys5ASPCDEV/">https://instagram.com/p/ys5ASPCDEV/</a></td></tr>
<tr><td><a href="https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/10881854_329617847240910_1814142151_n.jpg">https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/10881854_329617847240910_1814142151_n.jpg</a></td></tr>
<tr><td><a href="https://twitter.com/ranadotson/status/539485028712189952/photo/1">https://twitter.com/ranadotson/status/539485028712189952/photo/1</a></td></tr>
<tr><td><a href="https://instagram.com/p/0OgdvyxMhW/">https://instagram.com/p/0OgdvyxMhW/</a></td></tr>
</table>

Then I loaded the links.html into my browser, copied, pasted into Excel, and the links were active.

Writing BMP image in pure c/c++ without other libraries

Note that the lines are saved from down to up and not the other way around.

Additionally, the scanlines must have a byte-length of multiples of four, you should insert fill bytes at the end of the lines to ensure this.

customize Android Facebook Login button

  1. Create custom facebook button and change visability on native facebook button:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    
        <Button
                android:id="@+id/facebookView"
                android:layout_width="300dp"
                android:layout_height="48dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="12dp"
                android:background="@drawable/btn_frame"
                android:gravity="center"
                android:text="@string/Sign_in_facebook_button"
                android:textColor="@color/colorAccent" />
    
        <com.facebook.login.widget.LoginButton
                android:id="@+id/facebookButton"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="invisible"
                android:layout_marginBottom="12dp" />
    
     </LinearLayout>
    
  2. Add listener to your fake button and simulate click:

    facebookView.setOnClickListener(this);
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.facebookView){
           facebookButton.performClick();
        }
    }
    

What's the simplest way to print a Java array?

I came across this post in Vanilla #Java recently. It's not very convenient writing Arrays.toString(arr);, then importing java.util.Arrays; all the time.

Please note, this is not a permanent fix by any means. Just a hack that can make debugging simpler.

Printing an array directly gives the internal representation and the hashCode. Now, all classes have Object as the parent-type. So, why not hack the Object.toString()? Without modification, the Object class looks like this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

What if this is changed to:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This modded class may simply be added to the class path by adding the following to the command line: -Xbootclasspath/p:target/classes.

Now, with the availability of deepToString(..) since Java 5, the toString(..) can easily be changed to deepToString(..) to add support for arrays that contain other arrays.

I found this to be a quite useful hack and it would be great if Java could simply add this. I understand potential issues with having very large arrays since the string representations could be problematic. Maybe pass something like a System.outor a PrintWriter for such eventualities.

Clearing content of text file using C#

File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();

What is the difference between ports 465 and 587?

SMTP protocol: smtps (port 465) v. msa (port 587)

Ports 465 and 587 are intended for email client to email server communication - sending out email using SMTP protocol.

Port 465 is for smtps
SSL encryption is started automatically before any SMTP level communication.

Port 587 is for msa
It is almost like standard SMTP port. MSA should accept email after authentication (e.g. after SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port (port 25).
SSL encryption may be started by STARTTLS command at SMTP level if server supports it and your ISP does not filter server's EHLO reply (reported 2014).


Port 25 is used by MTA to MTA communication (mail server to mail server). It may be used for client to server communication but it is not currently the most recommended. Standard SMTP port accepts email from other mail servers to its "internal" mailboxes without authentication.

List(of String) or Array or ArrayList

You can do something like this,

  Dim lstOfStrings As New List(Of String) From {"Value1", "Value2", "Value3"}

Collection Initializers

Laravel - Form Input - Multiple select for a one to many relationship

@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

On your controller

$dogs = Dog::lists('name', 'id');

On customer create view you can use.

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}

Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}

Update For Laravel 5.1

The lists method now returns a Collection. Upgrading To 5.1.0

{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}

Relation between CommonJS, AMD and RequireJS?

Quoting

AMD:

  • One browser-first approach
  • Opting for asynchronous behavior and simplified backwards compatibility
  • It doesn't have any concept of File I/O.
  • It supports objects, functions, constructors, strings, JSON and many other types of modules.

CommonJS:

  • One server-first approach
  • Assuming synchronous behavior
  • Cover a broader set of concerns such as I/O, File system, Promises and more.
  • Supports unwrapped modules, it can feel a little more close to the ES.next/Harmony specifications, freeing you of the define() wrapper that AMD enforces.
  • Only support objects as modules.

HtmlSpecialChars equivalent in Javascript?

Chances are you don't need such a function. Since your code is already in the browser*, you can access the DOM directly instead of generating and encoding HTML that will have to be decoded backwards by the browser to be actually used.

Use innerText property to insert plain text into the DOM safely and much faster than using any of the presented escape functions. Even faster than assigning a static preencoded string to innerHTML.

Use classList to edit classes, dataset to set data- attributes and setAttribute for others.

All of these will handle escaping for you. More precisely, no escaping is needed and no encoding will be performed underneath**, since you are working around HTML, the textual representation of DOM.

_x000D_
_x000D_
// use existing element_x000D_
var author = 'John "Superman" Doe <[email protected]>';_x000D_
var el = document.getElementById('first');_x000D_
el.dataset.author = author;_x000D_
el.textContent = 'Author: '+author;_x000D_
_x000D_
// or create a new element_x000D_
var a = document.createElement('a');_x000D_
a.classList.add('important');_x000D_
a.href = '/search?q=term+"exact"&n=50';_x000D_
a.textContent = 'Search for "exact" term';_x000D_
document.body.appendChild(a);_x000D_
_x000D_
// actual HTML code_x000D_
console.log(el.outerHTML);_x000D_
console.log(a.outerHTML);
_x000D_
.important { color: red; }
_x000D_
<div id="first"></div>
_x000D_
_x000D_
_x000D_

* This answer is not intended for server-side JavaScript users (Node.js, etc.)

** Unless you explicitly convert it to actual HTML afterwards. E.g. by accessing innerHTML - this is what happens when you run $('<div/>').text(value).html(); suggested in other answers. So if your final goal is to insert some data into the document, by doing it this way you'll be doing the work twice. Also you can see that in the resulting HTML not everything is encoded, only the minimum that is needed for it to be valid. It is done context-dependently, that's why this jQuery method doesn't encode quotes and therefore should not be used as a general purpose escaper. Quotes escaping is needed when you're constructing HTML as a string with untrusted or quote-containing data at the place of an attribute's value. If you use the DOM API, you don't have to care about escaping at all.

Find Active Tab using jQuery and Twitter Bootstrap

Twitter Bootstrap assigns the active class to the li element that represents the active tab:

$("ul#sampleTabs li.active")

An alternative is to bind the shown event of each tab, and save the active tab:

var activeTab = null;
$('a[data-toggle="tab"]').on('shown', function (e) {
  activeTab = e.target;
})

How do I debug error ECONNRESET in Node.js?

Had the same problem today. After some research i found a very useful --abort-on-uncaught-exception node.js option. Not only it provides much more verbose and useful error stack trace, but also saves core file on application crash allowing further debug.

How to make use of SQL (Oracle) to count the size of a string?

Regardless to Your example

select length('Burger') from dual;

I hope this will help :)

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

convert base64 to image in javascript/jquery

One quick and easy way:

function paintSvgToCanvas(uSvg, uCanvas) {

    var pbx = document.createElement('img');

    pbx.style.width  = uSvg.style.width;
    pbx.style.height = uSvg.style.height;

    pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML);
    uCanvas.getContext('2d').drawImage(pbx, 0, 0);

}

How to use UIScrollView in Storyboard

Here's how to setup a scrollview using Xcode 11

1 - Add scrollview and set top,bottom,leading and trailing constraints

enter image description here

2 - Add a Content View to the scrollview, drag a connection to the Content Layout Guide and select Leading, Top, Bottom and Trailing. Make sure to set its' values to 0 or the constants you want.

enter image description here

3 - Drag from the Content View to the Frame Layout Guide and select Equal Widths

enter image description here

4 - Set a height constraint constant to the Content View

How do I declare a namespace in JavaScript?

JavaScript doesn’t support namespace by default. So if you create any element(function, method, object, variable) then it becomes global and pollute the global namespace. Let's take an example of defining two functions without any namespace,

function func1() {
    console.log("This is a first definition");

}
function func1() {
    console.log("This is a second definition");
}
func1(); // This is a second definition

It always calls the second function definition. In this case, namespace will solve the name collision problem.

Tomcat manager/html is not available?

Once try by replacing localhost to your 'computer name' i.e, http://localhost:8080 to http://system09:8080

Include jQuery in the JavaScript Console

intuitive one-liner

document.write(unescape('%3Cscript src="https://code.jquery.com/jquery-3.1.1.min.js"%3E%3C/script%3E’))

You can change the src address.
I referred to ReferenceError: Can't find variable: jQuery

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

Programmatically generate video or animated GIF in Python?

I'd recommend not using images2gif from visvis because it has problems with PIL/Pillow and is not actively maintained (I should know, because I am the author).

Instead, please use imageio, which was developed to solve this problem and more, and is intended to stay.

Quick and dirty solution:

import imageio
images = []
for filename in filenames:
    images.append(imageio.imread(filename))
imageio.mimsave('/path/to/movie.gif', images)

For longer movies, use the streaming approach:

import imageio
with imageio.get_writer('/path/to/movie.gif', mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)

How to detect DataGridView CheckBox event change?

following Killercam'answer, My code

private void dgvProducts_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        dgvProducts.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }

and :

private void dgvProducts_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (dgvProducts.DataSource != null)
        {
            if (dgvProducts.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "True")
            {
                //do something
            }
            else
            {
               //do something
            }
        }
    }

Is Constructor Overriding Possible?

Constructors are not normal methods and they cannot be "overridden". Saying that a constructor can be overridden would imply that a superclass constructor would be visible and could be called to create an instance of a subclass. This isn't true... a subclass doesn't have any constructors by default (except a no-arg constructor if the class it extends has one). It has to explicitly declare any other constructors, and those constructors belong to it and not to its superclass, even if they take the same parameters that the superclass constructors take.

The stuff you mention about default no arg constructors is just an aspect of how constructors work and has nothing to do with overriding.

Notepad++ - How can I replace blank lines

  1. Press Ctrl+H (Replace)

  2. Select Extended from SearchMode

  3. Put \r\n\r\n in Find What

  4. Put \r\n in ReplaceWith

  5. Click on Replace All

Replace multiple line breaks

Are "while(true)" loops so bad?

It's your gun, your bullet and your foot...

It's bad because you are asking for trouble. It won't be you or any of the other posters on this page who have examples of short/simple while loops.

The trouble will start at some very random time in the future. It might be caused by another programmer. It might be the person installing the software. It might be the end user.

Why? I had to find out why a 700K LOC app would gradually start burning 100% of the CPU time until every CPU was saturated. It was an amazing while (true) loop. It was big and nasty but it boiled down to:

x = read_value_from_database()
while (true) 
 if (x == 1)
  ...
  break;
 else if (x ==2)
  ...
  break;
and lots more else if conditions
}

There was no final else branch. If the value did not match an if condition the loop kept running until the end of time.

Of course, the programmer blamed the end users for not picking a value the programmer expected. (I then eliminated all instances of while(true) in the code.)

IMHO it is not good defensive programming to use constructs like while(true). It will come back to haunt you.

(But I do recall professors grading down if we did not comment every line, even for i++;)

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Select Project / Specific Folder --> Right Click --> Add Files to Project -- > Select the File you want to add.

This worked for me.

What are Covering Indexes and Covered Queries in SQL Server?

a covering index is the one which gives every required column and in which SQL server don't have hop back to the clustered index to find any column. This is achieved using non-clustered index and using INCLUDE option to cover columns. Non-key columns can be included only in non-clustered indexes. Columns can’t be defined in both the key column and the INCLUDE list. Column names can’t be repeated in the INCLUDE list. Non-key columns can be dropped from a table only after the non-key index is dropped first. Please see details here

MySQL: How to set the Primary Key on phpMyAdmin?

You can set a primary key on a text column. In phpMyAdmin, display the Structure of your table, click on Indexes, then ask to create the index on one column. Then choose PRIMARY, pick your TEXT column, but you have to put a length big enough so that its unique.

Can I use multiple versions of jQuery on the same page?

Yes, it's doable due to jQuery's noconflict mode. http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/

<!-- load jQuery 1.1.3 -->
<script type="text/javascript" src="http://example.com/jquery-1.1.3.js"></script>
<script type="text/javascript">
var jQuery_1_1_3 = $.noConflict(true);
</script>

<!-- load jQuery 1.3.2 -->
<script type="text/javascript" src="http://example.com/jquery-1.3.2.js"></script>
<script type="text/javascript">
var jQuery_1_3_2 = $.noConflict(true);
</script>

Then, instead of $('#selector').function();, you'd do jQuery_1_3_2('#selector').function(); or jQuery_1_1_3('#selector').function();.

SQL Server replace, remove all after certain character

For situations when I need to replace or match(find) something against string I prefer using regular expressions.

Since, the regular expressions are not fully supported in T-SQL you can implement them using CLR functions. Furthermore, you do not need any C# or CLR knowledge at all as all you need is already available in the MSDN String Utility Functions Sample.

In your case, the solution using regular expressions is:

SELECT [dbo].[RegexReplace] ([MyColumn], '(;.*)', '')
FROM [dbo].[MyTable]

But implementing such function in your database is going to help you solving more complex issues at all.


The example below shows how to deploy only the [dbo].[RegexReplace] function, but I will recommend to you to deploy the whole String Utility class.

  1. Enabling CLR Integration. Execute the following Transact-SQL commands:

    sp_configure 'clr enabled', 1
    GO
    RECONFIGURE
    GO  
    
  2. Bulding the code (or creating the .dll). Generraly, you can do this using the Visual Studio or .NET Framework command prompt (as it is shown in the article), but I prefer to use visual studio.

    • create new class library project:

      enter image description here

    • copy and paste the following code in the Class1.cs file:

      using System;
      using System.IO;
      using System.Data.SqlTypes;
      using System.Text.RegularExpressions;
      using Microsoft.SqlServer.Server;
      
      public sealed class RegularExpression
      {
          public static string Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
          {
              string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
              string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
              string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
              return Regex.Replace(input, pattern, replacement);
          }
      }
      
    • build the solution and get the path to the created .dll file:

      enter image description here

    • replace the path to the .dll file in the following T-SQL statements and execute them:

      IF OBJECT_ID(N'RegexReplace', N'FS') is not null
      DROP Function RegexReplace;
      GO
      
      IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'StringUtils')
      DROP ASSEMBLY StringUtils;
      GO
      
      DECLARE @SamplePath nvarchar(1024)
      -- You will need to modify the value of the this variable if you have installed the sample someplace other than the default location.
      Set @SamplePath = 'C:\Users\gotqn\Desktop\StringUtils\StringUtils\StringUtils\bin\Debug\'
      CREATE ASSEMBLY [StringUtils] 
      FROM @SamplePath + 'StringUtils.dll'
      WITH permission_set = Safe;
      GO
      
      
      CREATE FUNCTION [RegexReplace] (@input nvarchar(max), @pattern nvarchar(max), @replacement nvarchar(max))
      RETURNS nvarchar(max)
      AS EXTERNAL NAME [StringUtils].[RegularExpression].[Replace]
      GO
      
    • That's it. Test your function:

      declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
      insert into @MyTable ([id], MyText)
      select 1, 'some text; some more text'
      union all select 2, 'text again; even more text'
      union all select 3, 'text without a semicolon'
      union all select 4, null -- test NULLs
      union all select 5, '' -- test empty string
      union all select 6, 'test 3 semicolons; second part; third part'
      union all select 7, ';' -- test semicolon by itself    
      
      SELECT [dbo].[RegexReplace] ([MyText], '(;.*)', '')
      FROM @MyTable
      
      select * from @MyTable
      

Why am I getting "void value not ignored as it ought to be"?

    int a = srand(time(NULL))
        arr[i] = a;

Should be

        arr[i] = rand();

And put srand(time(NULL)) somewhere at the very beginning of your program.

How to write a std::string to a UTF-8 text file

Use Glib::ustring from glibmm.

It is the only widespread UTF-8 string container (AFAIK). While glyph (not byte) based, it has the same method signatures as std::string so the port should be simple search and replace (just make sure that your data is valid UTF-8 before loading it into a ustring).

Guid.NewGuid() vs. new Guid()

[I understand this is an old thread, just adding some more detail] The two answers by Mark and Jon Hanna sum up the differences, albeit it may interest some that

Guid.NewGuid()

Eventually calls CoCreateGuid (a COM call to Ole32) (reference here) and the actual work is done by UuidCreate.

Guid.Empty is meant to be used to check if a Guid contains all zeroes. This could also be done via comparing the value of the Guid in question with new Guid()

So, if you need a unique identifier, the answer is Guid.NewGuid()

Check if a string contains a string in C++

You can try using the find function:

string str ("There are two needles in this haystack.");
string str2 ("needle");

if (str.find(str2) != string::npos) {
//.. found.
} 

An invalid XML character (Unicode: 0xc) was found

Today, I've got a similar error:

Servlet.service() for servlet [remoting] in context with path [/***] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: buildDocument failed.] with root cause org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 91; An invalid XML character (Unicode: 0xc) was found in the value of attribute "text" and element is "label".


After my first encouter with the error, I had re-typed the entire line by hand, so that there was no way for a special character to creep in, and Notepad++ didn't show any non-printable characters (black on white), nevertheless I got the same error over and over.

When I looked up what I've done different than my predecessors, it turned out it was one additional space just before the closing /> (as I've heard was recommended for older parsers, but it shouldn't make any difference anyway, by the XML standards):

<label text="this label's text" layout="cell 0 0, align left" />

When I removed the space:

<label text="this label's text" layout="cell 0 0, align left"/>

everything worked just fine.


So it's definitely a misleading error message.

Closing a Userform with Unload Me doesn't work

It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.

Show hide div using codebehind

There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.

Rendering and Visibility

There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.

Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.

<div id="myDiv" runat="server"></div>

The decision to render the div or not can now be done in the code behind class like so:

myDiv.Visible = someConditionalBool;

If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.

Client Side Hiding

Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.

Hiding in the Code Behind Class

To hide an element that you want rendered to the page but hidden is another simple single line of code:

myDiv.Style["display"] = "none";

If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).

myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

// then to show again
myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

// ... and to show 
myDiv.show();

How to upload (FTP) files to server in a bash script?

No need to complicate stuff - this should work:

#/bin/bash
echo "
 verbose
 open ftp.mydomain.net
 user myusername mypassword
 ascii
 put textfile1
 put textfile2
 bin
 put binaryfile1
 put binaryfile2
 bye
" | ftp -n > ftp_$$.log

or you can use mput if you have many files ...

How to get started with Windows 7 gadgets

Combining and organizing all the current answers into one answer, then adding my own research:

Brief summary of Microsoft gadget development:

What are they written in? Windows Vista/Seven gadgets are developed in a mix of XML, HTML, CSS, and some IE scripting language. It is also possible to use C# with the latest release of Script#.

How are they packaged/deployed? The actual gadgets are stored in *.gadget files, which are simply the text source files listed above compressed into a single zip file.

Useful references for gadget development:

where do I start? Good introductory references to Windows Vista/Seven gadget development:

If you are willing to use offline resources, this book appears to be an excellent resource:

What do I need to know? Some other useful references; not necessarily instructional


Update: Well, this has proven to be a popular answer~ Sharing my own recent experience with Windows 7 gadget development:

Perhaps the easiest way to get started with Windows 7 gadget development is to modify a gadget that has already been developed. I recently did this myself because I wanted a larger clock gadget. Unable to find any, I tinkered with a copy of the standard Windows clock gadget until it was twice as large. I recommend starting with the clock gadget because it is fairly small and well-written. Here is the process I used:

  1. Locate the gadget you wish to modify. They are located in several different places. Search for folders named *.gadget. Example: C:\Program Files\Windows Sidebar\Gadgets\Clock.Gadget\
  2. Make a copy of this folder (installed gadgets are not wrapped in zip files.)
  3. Rename some key parts:
    1. The folder name
    2. The name inside the gadget.xml file. It looks like:<name>Clock</name> This is the name that will be displayed in the "Gadgets Gallery" window.
  4. Zip up the entire *.gadget directory.
  5. Change the file extension from "zip" to "gadget" (Probably just need to remove the ".zip" extension.)
  6. Install your new copy of the gadget by double clicking the new *.gadget file. You can now add your gadget like any other gadget (right click desktop->Gadgets)
  7. Locate where this gadget is installed (probably to %LOCALAPPDATA%\Microsoft\Windows Sidebar\)
  8. Modify the files in this directory. The gadget is very similar to a web page: HTML, CSS, JS, and image files. The gadget.xml file specifies which file is opened as the "index" page for the gadget.
  9. After you save the changes, view the results by installing a new instance of the gadget. You can also debug the JavaScript (The rest of that article is pretty informative, too).

How should I choose an authentication library for CodeIgniter?

I'm the developer of Redux Auth and some of the issues you mentioned have been fixed in the version 2 beta. You can download this off the offcial website with a sample application too.

  • Requires autoloading (impeding performance)
  • Uses the inherently unsafe concept of 'security questions'. Dealbreaker!

Security questions are now not used and a simpler forgotten password system has been put in place.

  • Return types are a bit of a hodgepodge of true, false, error and success codes

This was fixed in version 2 and returns boolean values. I hated the hodgepodge as much as you.

  • Doesn't hook into CI's validation system

The sample application uses the CI's validation system.

  • Doesn't allow a user to resend a 'lost password' code

Work in progress

I also implemented some other features such as email views, this gives you the choice of being able to use the CodeIgniter helpers in your emails.

It's still a work in progress so if have any more suggestions please keep them coming.

-Popcorn

Ps : Thanks for recommending Redux.

Reverse a string in Java

Having surrogate pairs in input string, you have to leave them not reversed, so good and generic way of reversing the string is using StringBuilder.reverse as it handles extended character set correctly. So called supplementary characters consisting of surrogate pairs are unicode values up to U+10FFFF encoded as two consecutive chars.

Here is my solution:

String aString = "abcdef";
String reversedString = aString
       .codePoints()
       .boxed()
       .map(Character::toString)
       .collect(Collectors.collectingAndThen(Collectors.toList(), aList -> {
           Collections.reverse(aList);
           return String.join("", aList);
       }));
  • String.codepoints returns stream of integers surrogate pair (double chars) packed in one integer, this is different that String.chars for which one integer = one char
  • as of Java 11 Character.toString also accepts codepoint, and returns either String of length 1 or 2 if there is surrogate pair

Mysql: Select rows from a table that are not in another

Try this simple query. It works perfectly.

select * from Table1 where (FirstName,LastName,BirthDate) not in (select * from Table2);

How can I see which Git branches are tracking which remote / upstream branch?

Based on Olivier Refalo's answer

if [ $# -eq 2 ] 
then
    echo "Setting tracking for branch " $1 " -> " $2
    git branch --set-upstream $1 $2
else
    echo "-- Local --" 
    git for-each-ref --shell --format="[ %(upstream:short) != '' ] && echo -e '\t%(refname:short) <--> %(upstream:short)'" refs/heads | sh
    echo "-- Remote --" 
    REMOTES=$(git remote -v) 
    if [ "$REMOTES" != '' ]
    then
        echo $REMOTES
    fi  
fi

It shows only local with track configured.

Write it on a script called git-track on your path an you will get a git track command

A more elaborated version on https://github.com/albfan/git-showupstream

Static array vs. dynamic array in C++

You could have a pseudo dynamic array where the size is set by the user at runtime, but then is fixed after that.

int size;
cin >> size;
int dynamicArray[size];

How to write a simple Html.DropDownListFor()?

@using (Html.BeginForm()) {
    <p>Do you like pizza?
        @Html.DropDownListFor(x => x.likesPizza, new[] {
            new SelectListItem() {Text = "Yes", Value = bool.TrueString},
            new SelectListItem() {Text = "No", Value = bool.FalseString}
        }, "Choose an option") 
    </p>
    <input type = "submit" value = "Submit my answer" />
} 

I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.

Some notes for beginners:

  • Don't worry about what 'x' is called - it is created here, for the first time, and doesn't link to anything else anywhere else in the MVC app, so you can call it what you want - 'x', 'model', 'm' etc.
  • The placeholder that users will see in the dropdown list is "Choose an option", so you can change this if you want.
  • There's a bit of text preceding the drop down which says "Do you like pizza?"
  • This should be complete text for a form, including a submit button, I think

Hope this helps someone,

Make an image width 100% of parent div, but not bigger than its own width

Found this post on a Google search, and it solved my issue thanks to @jwal reply, but I made one addition to his solution.

img.content.x700 {
  width: auto !important; /*override the width below*/
  width: 100%;
  max-width: 678px;
  float: left;
  clear: both;
}

With the above I changed the max-width to the dimensions of the content container that my image is in. In this case it is: container width - padding - boarder = max width

This way my image won't break out of the containing div, and I can still float the image within the content div.

I've tested in IE 9, FireFox 18.0.2 and Chrome 25.0.1364.97, Safari iOS and seems to work.

Additional: I tested this on an image 1024px wide displayed at 678px (the max width), and an image 500px wide displayed at 500px (width of the image).

How do you resize a form to fit its content automatically?

From MSDN:

To maximize productivity, the Windows Forms Designer shadows the AutoSize property for the Form class. At design time, the form behaves as though the AutoSize property is set to false, regardless of its actual setting. At runtime, no special accommodation is made, and the AutoSize property is applied as specified by the property setting.

Ruby, Difference between exec, system and %x() or Backticks

They do different things. exec replaces the current process with the new process and never returns. system invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

How do you implement a class in C?

you can take a look at GOBject. it's an OS library that give you a verbose way to do an object.

http://library.gnome.org/devel/gobject/stable/

How do I accomplish an if/else in mustache.js?

You can define a helper in the view. However, the conditional logic is somewhat limited. Moxy-Stencil (https://github.com/dcmox/moxyscript-stencil) seems to address this with "parameterized" helpers, eg:

{{isActive param}}

and in the view:

view.isActive = function (path: string){ return path === this.path ? "class='active'" : '' }

Difference between .on('click') vs .click()

They've now deprecated click(), so best to go with on('click')

Can I set max_retries for requests.request?

Be careful, Martijn Pieters's answer isn't suitable for version 1.2.1+. You can't set it globally without patching the library.

You can do this instead:

import requests
from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://www.github.com', HTTPAdapter(max_retries=5))
s.mount('https://www.github.com', HTTPAdapter(max_retries=5))

Standard way to embed version into python package?

Using setuptools and pbr

There is not a standard way to manage version, but the standard way to manage your packages is setuptools.

The best solution I've found overall for managing version is to use setuptools with the pbr extension. This is now my standard way of managing version.

Setting up your project for full packaging may be overkill for simple projects, but if you need to manage version, you are probably at the right level to just set everything up. Doing so also makes your package releasable at PyPi so everyone can download and use it with Pip.

PBR moves most metadata out of the setup.py tools and into a setup.cfg file that is then used as a source for most metadata, which can include version. This allows the metadata to be packaged into an executable using something like pyinstaller if needed (if so, you will probably need this info), and separates the metadata from the other package management/setup scripts. You can directly update the version string in setup.cfg manually, and it will be pulled into the *.egg-info folder when building your package releases. Your scripts can then access the version from the metadata using various methods (these processes are outlined in sections below).

When using Git for VCS/SCM, this setup is even better, as it will pull in a lot of the metadata from Git so that your repo can be your primary source of truth for some of the metadata, including version, authors, changelogs, etc. For version specifically, it will create a version string for the current commit based on git tags in the repo.

As PBR will pull version, author, changelog and other info directly from your git repo, so some of the metadata in setup.cfg can be left out and auto generated whenever a distribution is created for your package (using setup.py)



Get the current version in real-time

setuptools will pull the latest info in real-time using setup.py:

python setup.py --version

This will pull the latest version either from the setup.cfg file, or from the git repo, based on the latest commit that was made and tags that exist in the repo. This command doesn't update the version in a distribution though.



Updating the version metadata

When you create a distribution with setup.py (i.e. py setup.py sdist, for example), then all the current info will be extracted and stored in the distribution. This essentially runs the setup.py --version command and then stores that version info into the package.egg-info folder in a set of files that store distribution metadata.

Note on process to update version meta-data:

If you are not using pbr to pull version data from git, then just update your setup.cfg directly with new version info (easy enough, but make sure this is a standard part of your release process).

If you are using git, and you don't need to create a source or binary distribution (using python setup.py sdist or one of the python setup.py bdist_xxx commands) the simplest way to update the git repo info into your <mypackage>.egg-info metadata folder is to just run the python setup.py install command. This will run all the PBR functions related to pulling metadata from the git repo and update your local .egg-info folder, install script executables for any entry-points you have defined, and other functions you can see from the output when you run this command.

Note that the .egg-info folder is generally excluded from being stored in the git repo itself in standard Python .gitignore files (such as from Gitignore.IO), as it can be generated from your source. If it is excluded, make sure you have a standard "release process" to get the metadata updated locally before release, and any package you upload to PyPi.org or otherwise distribute must include this data to have the correct version. If you want the Git repo to contain this info, you can exclude specific files from being ignored (i.e. add !*.egg-info/PKG_INFO to .gitignore)



Accessing the version from a script

You can access the metadata from the current build within Python scripts in the package itself. For version, for example, there are several ways to do this I have found so far:

## This one is a new built-in as of Python 3.8.0 should become the standard
from importlib-metadata import version

v0 = version("mypackage")
print('v0 {}'.format(v0))

## I don't like this one because the version method is hidden
import pkg_resources  # part of setuptools

v1 = pkg_resources.require("mypackage")[0].version
print('v1 {}'.format(v1))

# Probably best for pre v3.8.0 - the output without .version is just a longer string with
# both the package name, a space, and the version string
import pkg_resources  # part of setuptools

v2 = pkg_resources.get_distribution('mypackage').version
print('v2 {}'.format(v2))

## This one seems to be slower, and with pyinstaller makes the exe a lot bigger
from pbr.version import VersionInfo

v3 = VersionInfo('mypackage').release_string()
print('v3 {}'.format(v3))

You can put one of these directly in your __init__.py for the package to extract the version info as follows, similar to some other answers:

__all__ = (
    '__version__',
    'my_package_name'
)

import pkg_resources  # part of setuptools

__version__ = pkg_resources.get_distribution("mypackage").version

Getting GET "?" variable in laravel

It is not very nice to use native php resources like $_GET as Laravel gives us easy ways to get the variables. As a matter of standard, whenever possible use the resources of the laravel itself instead of pure PHP.

There is at least two modes to get variables by GET in Laravel ( Laravel 5.x or greater):

Mode 1

Route:

Route::get('computers={id}', 'ComputersController@index');

Request (POSTMAN or client...):

http://localhost/api/computers=500

Controler - You can access the {id} paramter in the Controlller by:

public function index(Request $request, $id){
   return $id;
}

Mode 2

Route:

Route::get('computers', 'ComputersController@index');

Request (POSTMAN or client...):

http://localhost/api/computers?id=500

Controler - You can access the ?id paramter in the Controlller by:

public function index(Request $request){
   return $request->input('id');
}

Can a table have two foreign keys?

Yes, MySQL allows this. You can have multiple foreign keys on the same table.

Get more details here FOREIGN KEY Constraints

How should I use try-with-resources with JDBC?

Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:

try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
    PreparedStatement stmt = ((Supplier<PreparedStatement>)() -> {
    try {
        PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
        s.setInt(1, userid);
        return s;
    } catch (SQLException e) { throw new RuntimeException(e); }
    }).get();
    ResultSet resultSet = stmt.executeQuery()) {
}

How do you round a floating point number in Perl?

If you decide to use printf or sprintf, note that they use the Round half to even method.

foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {
    printf "$i -> %.0f\n", $i;
}
__END__
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4

Check if string matches pattern

Please try the following:

import re

name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]

# Match names.
for element in name:
     m = re.match("(^[A-Z]\d[A-Z]\d)", element)
     if m:
        print(m.groups())

How to specify more spaces for the delimiter using cut?

As an alternative, there is always perl:

ps aux | perl -lane 'print $F[3]'

Or, if you want to get all fields starting at field #3 (as stated in one of the answers above):

ps aux | perl -lane 'print @F[3 .. scalar @F]'

"Error: Main method not found in class MyClass, please define the main method as..."

Few min back i was facing " main method not defined".Now its resolved.I tried all above thing but nothing was working.There was not compilation error in my java file. I followed below things

  • simply did maven update in all dependent project (alt+F5).

Now problem solved.Getting required result.

Downloading an entire S3 bucket?

Another option that could help some OS X users is Transmit.

It's an FTP program that also let you connect to your S3 files. And, it has an option to mount any FTP or S3 storage as a folder in the Finder, but it's only for a limited time.

How to parse date string to Date?

I had this issue, and I set the Locale to US, then it work.

static DateFormat visitTimeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US);

for String "Sun Jul 08 00:06:30 UTC 2012"

PackagesNotFoundError: The following packages are not available from current channels:

Try adding the conda-forge channel to your list of channels with this command:
conda config --append channels conda-forge. It tells conda to also look on the conda-forge channel when you search for packages. You can then simply install the two packages with conda install slycot control.

Channels are basically servers for people to host packages on and the community-driven conda-forge is usually a good place to start when packages are not available via the standard channels. I checked and both slycot and control seem to be available there.

Get selected text from a drop-down list (select box) using jQuery

Try:

$var = jQuery("#dropdownid option:selected").val();
   alert ($var);

Or to get the text of the option, use text():

$var = jQuery("#dropdownid option:selected").text();
   alert ($var);

More Info:

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

RESTful URL design for search

There are a lot of good options for your case here. Still you should considering using the POST body.

The query string is perfect for your example, but if you have something more complicated, e.g. an arbitrary long list of items or boolean conditionals, you might want to define the post as a document, that the client sends over POST.

This allows a more flexible description of the search, as well as avoids the Server URL length limit.

jQuery, checkboxes and .is(":checked")

In addition to Nick Craver's answer, for this to work properly on IE 8 you need to add a additional click handler to the checkbox:

// needed for IE 8 compatibility
if ($.browser.msie)
    $("#myCheckbox").click(function() { $(this).trigger('change'); });

$("#myCheckbox").change( function() {
    alert($(this).is(":checked"));
});

//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');

Otherwise the callback will only be triggered when the checkbox loses focus, as IE 8 keeps focus on checkboxes and radios when they are clicked.

Haven't tested on IE 9 though.

How to print Boolean flag in NSLog?

Apple's FixIt supplied %hhd, which correctly gave me the value of my BOOL.

What is a PDB file?

I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.

Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace string. I included the PDB file in the executable folder and now all is fine.

How can I restore the MySQL root user’s full privileges?

If the GRANT ALL doesn't work, try:

  1. Stop mysqld and restart it with the --skip-grant-tables option.
  2. Connect to the mysqld server with just: mysql (i.e. no -p option, and username may not be required).
  3. Issue the following commands in the mysql client:

    UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

    FLUSH PRIVILEGES;

After that, you should be able to run GRANT ALL ON *.* TO 'root'@'localhost'; and have it work.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

Try to add like this:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

instead of having

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

Here is my one liner. Here 'c' is the name of the column

df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()

Merge some list items in a Python List

my telepathic abilities are not particularly great, but here is what I think you want:

def merge(list_of_strings, indices):
    list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
    list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
    return list_of_strings

I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.

How to print a int64_t type in C

//VC6.0 (386 & better)

    __int64 my_qw_var = 0x1234567890abcdef;

    __int32 v_dw_h;
    __int32 v_dw_l;

    __asm
        {
            mov eax,[dword ptr my_qw_var + 4]   //dwh
            mov [dword ptr v_dw_h],eax

            mov eax,[dword ptr my_qw_var]   //dwl
            mov [dword ptr v_dw_l],eax

        }
        //Oops 0.8 format
    printf("val = 0x%0.8x%0.8x\n", (__int32)v_dw_h, (__int32)v_dw_l);

Regards.

Compiling with g++ using multiple cores

I'm not sure about g++, but if you're using GNU Make then "make -j N" (where N is the number of threads make can create) will allow make to run multple g++ jobs at the same time (so long as the files do not depend on each other).

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Reference the handle of the associated control in its creator, like so:

Note: Be wary of this solution.If a control has a handle it is much slower to do things like set the size and location of it. This makes InitializeComponent much slower. A better solution is to not background anything before the control has a handle.

PyTorch: How to get the shape of a Tensor as a list of int

If you're a fan of NumPyish syntax, then there's tensor.shape.

In [3]: ar = torch.rand(3, 3)

In [4]: ar.shape
Out[4]: torch.Size([3, 3])

# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]

# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]

# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]

P.S.: Note that tensor.shape is an alias to tensor.size(), though tensor.shape is an attribute of the tensor in question whereas tensor.size() is a function.

Getting multiple keys of specified value of a generic Dictionary?

Many of these answers are now outdated, here is a modern C# approach, using LINQ

Since values aren't necessarily unique, you may get multiple results. You can return an IEnumerable<KeyValuePair<int, string>>:

var betaKeys = greek.Where(x => x.Value == "beta");

To transform this into an IEnumerable<int> type, just use .Select():

var betaKeys = greek.Where(x => x.Value == "beta").Select(x => x.Key);

How to get a unique device ID in Swift?

class func uuid(completionHandler: @escaping (String) -> ()) {
    if let uuid = UIDevice.current.identifierForVendor?.uuidString {
        completionHandler(uuid)
    }
    else {
        // If the value is nil, wait and get the value again later. This happens, for example, after the device has been restarted but before the user has unlocked the device.
        // https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor?language=objc
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            uuid(completionHandler: completionHandler)
        }
    }
}

How to properly stop the Thread in Java?

Using Thread.interrupt() is a perfectly acceptable way of doing this. In fact, it's probably preferrable to a flag as suggested above. The reason being that if you're in an interruptable blocking call (like Thread.sleep or using java.nio Channel operations), you'll actually be able to break out of those right away.

If you use a flag, you have to wait for the blocking operation to finish and then you can check your flag. In some cases you have to do this anyway, such as using standard InputStream/OutputStream which are not interruptable.

In that case, when a thread is interrupted, it will not interrupt the IO, however, you can easily do this routinely in your code (and you should do this at strategic points where you can safely stop and cleanup)

if (Thread.currentThread().isInterrupted()) {
  // cleanup and stop execution
  // for example a break in a loop
}

Like I said, the main advantage to Thread.interrupt() is that you can immediately break out of interruptable calls, which you can't do with the flag approach.

Why does my 'git branch' have no master?

Most Git repositories use master as the main (and default) branch - if you initialize a new Git repo via git init, it will have master checked out by default.

However, if you clone a repository, the default branch you have is whatever the remote's HEAD points to (HEAD is actually a symbolic ref that points to a branch name). So if the repository you cloned had a HEAD pointed to, say, foo, then your clone will just have a foo branch.

The remote you cloned from might still have a master branch (you could check with git ls-remote origin master), but you wouldn't have created a local version of that branch by default, because git clone only checks out the remote's HEAD.

Addition for BigDecimal

BigDecimal no = new BigDecimal(10); //you can add like this also
no = no.add(new BigDecimal(10));
System.out.println(no);

20

RadioGroup: How to check programmatically

You may need to declare the radio buttons in the onCreate method of your code and use them.

RadioButton rb1 = (RadioButton) findViewById(R.id.option1);
rb1.setChecked(true);

Delete dynamically-generated table row using jQuery

I know this is old but I've used a function similar to this...

deleteRow: function (ctrl) {

    //remove the row from the table
    $(ctrl).closest('tr').remove();

}

... with markup like this ...

<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>

...and it works fine

Setting default value for TypeScript object passed as argument

Object destructuring the parameter object is what many of the answers above are aiming for and Typescript now has the methods in place to make it much easier to read and intuitively understand.

Destructuring Basics: By destructuring an object, you can choose properties from an object by key name. You can define as few or as many of the properties you like, and default values are set by a basic syntax of let {key = default} = object.

let {firstName, lastName = 'Smith'} = myParamsObject;

//Compiles to:
var firstName = myParamsObject.firstName, 
_a = myParamsObject.lastName, 
lastName = _a === void 0 ? 'Smith' : _a;

Writing an interface, type or class for the parameter object improves legibility.

_x000D_
_x000D_
type FullName = {_x000D_
  firstName: string;_x000D_
   _x000D_
  /** @default 'Smith' */_x000D_
  lastName ? : string;_x000D_
}_x000D_
_x000D_
function sayName(params: FullName) {_x000D_
_x000D_
  // Set defaults for parameter object_x000D_
  var { firstName, lastName = 'Smith'} = params;_x000D_
_x000D_
  // Do Stuff_x000D_
  var name = firstName + " " + lastName;_x000D_
  alert(name);_x000D_
}_x000D_
_x000D_
// Use it_x000D_
sayName({_x000D_
  firstName: 'Bob'_x000D_
});
_x000D_
_x000D_
_x000D_

Upload Image using POST form data in Python-requests

Use this snippet

import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
  name_img= os.path.basename(path_img)
  files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
  with requests.Session() as s:
    r = s.post(url,files=files)
    print(r.status_code)

How do I connect to mongodb with node.js (and authenticate)?

I recommend mongoskin I just created.

var mongo = require('mongoskin');
var db = mongo.db('admin:pass@localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
   // do something with items
});

Is mongoskin sync? Nop, it is async.

How to customize the back button on ActionBar

I have checked the question. Here is the steps that I follow. The source code is hosted on GitHub: https://github.com/jiahaoliuliu/sherlockActionBarLab

Override the actual style for the pre-v11 devices.

Copy and paste the follow code in the file styles.xml of the default values folder.

<resources>
    <style name="MyCustomTheme" parent="Theme.Sherlock.Light">
    <item name="homeAsUpIndicator">@drawable/ic_home_up</item>
    </style>
</resources>

Note that the parent could be changed to any Sherlock theme.

Override the actual style for the v11+ devices.

On the same folder where the folder values is, create a new folder called values-v11. Android will automatically look for the content of this folder for devices with API or above.

Create a new file called styles.xml and paste the follow code into the file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCustomTheme" parent="Theme.Sherlock.Light">
    <item name="android:homeAsUpIndicator">@drawable/ic_home_up</item>
    </style>
</resources>

Note tha the name of the style must be the same as the file in the default values folder and instead of the item homeAsUpIndicator, it is called android:homeAsUpIndicator.

The item issue is because for devices with API 11 or above, Sherlock Action Bar use the default Action Bar which comes with Android, which the key name is android:homeAsUpIndicator. But for the devices with API 10 or lower, Sherlock Action Bar uses its own ActionBar, which the home as up indicator is called simple "homeAsUpIndicator".

Use the new theme in the manifest

Replace the theme for the application/activity in the AndroidManifest file:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyCustomTheme" >

Validate that a string is a positive integer

This is how I validate that a string is a positive integer.

_x000D_
_x000D_
var str = "123";
var str1 = "1.5";
var str2 = "-123";

console.log("is str positive integer: ", Number.isInteger(Number(str)) && Number(str) > 0)
console.log("is str1 positive integer: ", Number.isInteger(Number(str1)) && Number(str1) > 0)
console.log("is str2 positive integer: ", Number.isInteger(Number(str2)) && Number(str2) > 0)
_x000D_
_x000D_
_x000D_

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

$_POST Array from html form

Change

$info=$_POST['id[]'];

to

$info=$_POST['id'];

by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.

removing html element styles via javascript

In JavaScript:

document.getElementById("id").style.display = null;

In jQuery:

$("#id").css('display',null);

How to find day of week in php in a specific timezone

$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);

This should work (didn't test it, so YMMV). It works by storing the script's current timezone, changing it to the one specified by the user, getting the day of the week from the date() function at the specified timestamp, and then setting the script's timezone back to what it was to begin with.

You might have some adventures with timezone identifiers, though.

How can I call a WordPress shortcode within a template?

echo do_shortcode('[CONTACT-US-FORM]');

Use this in your template.

Look here for more: Do Shortcode

An item with the same key has already been added

I had 2 model properties like this

public int LinkId {get;set;}
public int LinkID {get;set;}

it is strange that it threw this error for these 2 haha..

Sorting JSON by values

Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.

$scope.sortMyData = function (a, b)
{
  var retVal = 0, key;
  for (var i = 0; i < $scope.sortKeys.length; i++)
  {
    if (retVal !== 0)
    {
      break;
    }
    else
    {
      key = $scope.sortKeys[i];
      if ('asc' === key.direction)
      {
        retVal = (a[key.field] < b[key.field]) ? -1 : (a[key.field] > b[key.field]) ? 1 : 0;
      }
      else
      {
        retVal = (a[key.field] < b[key.field]) ? 1 : (a[key.field] > b[key.field]) ? -1 : 0;
      }
    }
  }
  return retVal;
};

Count lines in large files

find  -type f -name  "filepattern_2015_07_*.txt" -exec ls -1 {} \; | cat | awk '//{ print $0 , system("cat " $0 "|" "wc -l")}'

Output:

Enable & Disable a Div and its elements in Javascript

You should be able to set these via the attr() or prop() functions in jQuery as shown below:

jQuery (< 1.7):

// This will disable just the div
$("#dcacl").attr('disabled','disabled');

or

// This will disable everything contained in the div
$("#dcacl").children().attr("disabled","disabled");

jQuery (>= 1.7):

// This will disable just the div
$("#dcacl").prop('disabled',true);

or

// This will disable everything contained in the div
$("#dcacl").children().prop('disabled',true);

or

//  disable ALL descendants of the DIV
$("#dcacl *").prop('disabled',true);

Javascript:

// This will disable just the div
document.getElementById("dcalc").disabled = true;

or

// This will disable all the children of the div
var nodes = document.getElementById("dcalc").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++){
     nodes[i].disabled = true;
}

How to convert JSON object to an Typescript array?

To convert any JSON to array, use the below code:

const usersJson: any[] = Array.of(res.json());

echo that outputs to stderr

Another option

echo foo >>/dev/stderr

The maximum message size quota for incoming messages (65536) has been exceeded

For me, the settings in web.config / app.config were ignored. I ended up creating my binding manually, which solved the issue for me:

var httpBinding = new BasicHttpBinding()
{
    MaxBufferPoolSize = Int32.MaxValue,
    MaxBufferSize = Int32.MaxValue,
    MaxReceivedMessageSize = Int32.MaxValue,
    ReaderQuotas = new XmlDictionaryReaderQuotas()
    {
        MaxArrayLength = 200000000,
        MaxDepth = 32,
        MaxStringContentLength = 200000000
    }
};

How do I wait for an asynchronously dispatched block to finish?

Sometimes, Timeout loops are also helpful. May you wait until you get some (may be BOOL) signal from async callback method, but what if no response ever, and you want to break out of that loop? Here below is solution, mostly answered above, but with an addition of Timeout.

#define CONNECTION_TIMEOUT_SECONDS      10.0
#define CONNECTION_CHECK_INTERVAL       1

NSTimer * timer;
BOOL timeout;

CCSensorRead * sensorRead ;

- (void)testSensorReadConnection
{
    [self startTimeoutTimer];

    dispatch_semaphore_t sema = dispatch_semaphore_create(0);

    while (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW)) {

        /* Either you get some signal from async callback or timeout, whichever occurs first will break the loop */
        if (sensorRead.isConnected || timeout)
            dispatch_semaphore_signal(sema);

        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate dateWithTimeIntervalSinceNow:CONNECTION_CHECK_INTERVAL]];

    };

    [self stopTimeoutTimer];

    if (timeout)
        NSLog(@"No Sensor device found in %f seconds", CONNECTION_TIMEOUT_SECONDS);

}

-(void) startTimeoutTimer {

    timeout = NO;

    [timer invalidate];
    timer = [NSTimer timerWithTimeInterval:CONNECTION_TIMEOUT_SECONDS target:self selector:@selector(connectionTimeout) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

-(void) stopTimeoutTimer {
    [timer invalidate];
    timer = nil;
}

-(void) connectionTimeout {
    timeout = YES;

    [self stopTimeoutTimer];
}

Convert JSONArray to String Array

You might want to take a look at JSONArray.toList(), which returns a List containing Maps and Lists, which represent your JSON structure. So you can use it with Java Streams like this:

JSONArray array = new JSONArray(jsonString);
List<String> result = array.toList().stream()
        .filter(Map.class::isInstance)
        .map(Map.class::cast)
        .map(o -> o.get("name"))
        .filter(String.class::isInstance)
        .map(String.class::cast)
        .collect(Collectors.toList());

This might just be useful even for more complex objects.

Alternatively you can just use an IntStream to iterate over all items in the JSONArray and map all names:

JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
        .mapToObj(array::getJSONObject)
        .map(o -> o.getString("name"))
        .collect(Collectors.toList());

How to enable ASP classic in IIS7.5

I found some detailed instructions here: http://digitallibraryworld.com/?p=6

The key piece of advice seems to be, don't use the 64-bit ASP.DLL (found in system32) if you've configured the app pool to run 32-bit applications (instead, use the 32-bit ASP.DLL).

Add a script map using the following setting:

Request Path: *.asp
Executable: C:\Windows\system32\inetsrv\asp.dll
Name: whatever you want. I named my Classic ASP

The executable above is 64 BIT ASP handler for your asp script. If you want your ASP script to be handled in 32 bit environment, you need to use executable from this location: C:\Windows\SysWOW64\inetsrv\asp.dll.

Of course, if you don't need to load any 32-bit libraries (or data providers, etc.), just make your life easier by running the 64-bit ASP.DLL!

Can I configure a subdomain to point to a specific port on my server

If you only got one IP on the server, there is no chance to do that. DNS is a simple name to number (IP) resolver. If you have two IPs on the server, you can point each subdomain to each of the IP-addresses and run both servers on the default port on each IP.
one.example.com -> 127.0.0.1 (server: 127.0.0.1:25565)
two.example.com -> 127.0.0.2 (server: 127.0.0.2:25565)

Extracting an attribute value with beautifulsoup

In Python 3.x, simply use get(attr_name) on your tag object that you get using find_all:

xmlData = None

with open('conf//test1.xml', 'r') as xmlFile:
    xmlData = xmlFile.read()

xmlDecoded = xmlData

xmlSoup = BeautifulSoup(xmlData, 'html.parser')

repElemList = xmlSoup.find_all('repeatingelement')

for repElem in repElemList:
    print("Processing repElem...")
    repElemID = repElem.get('id')
    repElemName = repElem.get('name')

    print("Attribute id = %s" % repElemID)
    print("Attribute name = %s" % repElemName)

against XML file conf//test1.xml that looks like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <singleElement>
        <subElementX>XYZ</subElementX>
    </singleElement>
    <repeatingElement id="11" name="Joe"/>
    <repeatingElement id="12" name="Mary"/>
</root>

prints:

Processing repElem...
Attribute id = 11
Attribute name = Joe
Processing repElem...
Attribute id = 12
Attribute name = Mary