Programs & Examples On #Temporary objects

To the power of in C?

#include <math.h>


printf ("%d", (int) pow (3, 4));

JavaScript single line 'if' statement - best syntax, this alternative?

This one line is much cleaner.

if(dog) alert('bark bark');

I prefer this. hope it helps someone

How do I get the value of text input field using JavaScript?

You can read value by

searchTxt.value

_x000D_
_x000D_
function searchURL() {
   let txt = searchTxt.value;
   console.log(txt);
   // window.location = "http://www.myurl.com/search/" + txt; ...
}

document.querySelector('.search').addEventListener("click", ()=>searchURL());
_x000D_
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

<button class="search">Search</button>
_x000D_
_x000D_
_x000D_

UPDATE

I see many downvotes but any comments - however (for future readers) actually this solution works

Vlookup referring to table data in a different sheet

I faced this problem and when i started searching the important point i found is, the value u are looking up i.e M3 column should be present in the first column of the table u want to search https://support.office.com/en-us/article/VLOOKUP-function-0bbc8083-26fe-4963-8ab8-93a18ad188a1 check in lookup_value

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Use "whereis" command.

$ whereis tomcat8
tomcat8: /usr/sbin/tomcat8 /etc/tomcat8 /usr/libexec/tomcat8 /usr/share/tomcat8

How to set Python's default version to 3.x on OS X?

I think when you install python it puts export path statements into your ~/.bash_profile file. So if you do not intend to use Python 2 anymore you can just remove that statement from there. Alias as stated above is also a great way to do it.

Here is how to remove the reference from ~/.bash_profile - vim ./.bash_profile - remove the reference (AKA something like: export PATH="/Users/bla/anaconda:$PATH") - save and exit - source ./.bash_profile to save the changes

How to get the difference between two arrays in JavaScript?

var compare = array1.length > array2.length ? array1 : array2;
var compareWith = array1.length > array2.length ? array2 : array1;
var uniqueValues = compareWith.filter(function(value){
                    if(compare.indexOf(vakye) == -1)
                       return true;
                   });

This will both check which one is the larger one among the arrays and then will do the comparison.

What's the best way to join on the same table twice?

The first method is the proper approach and will do what you need. However, with the inner joins, you will only select rows from Table1 if both phone numbers exist in Table2. You may want to do a LEFT JOIN so that all rows from Table1 are selected. If the phone numbers don't match, then the SomeOtherFields would be null. If you want to make sure you have at least one matching phone number you could then do WHERE t2.PhoneNumber IS NOT NULL OR t3.PhoneNumber IS NOT NULL

The second method could have a problem: what happens if Table2 has both PhoneNumber1 and PhoneNumber2? Which row will be selected? Depending on your data, foreign keys, etc. this may or may not be a problem.

How to enable relation view in phpmyadmin

first ensure that your table storage engine type should be innoDB (you can set it using Table operations Tab) enter image description here

if you are using new phpmyadmin then use new "Relation view" tab to make foreign key relation

enter image description here

if you are using old version of phpmyadmin then the "relation view" button will show on the bottom of the table columns

enter image description here

Jquery Ajax, return success/error from mvc.net controller

 $.ajax({
    type: "POST",
    data: formData,
    url: "/Forms/GetJobData",
    dataType: 'json',
    contentType: false,
    processData: false,               
    success: function (response) {
        if (response.success) {
            alert(response.responseText);
        } else {
            // DoSomethingElse()
            alert(response.responseText);
        }                          
    },
    error: function (response) {
        alert("error!");  // 
    }

});

Controller:

[HttpPost]
public ActionResult GetJobData(Jobs jobData)
{
    var mimeType = jobData.File.ContentType;
    var isFileSupported = IsFileSupported(mimeType);

    if (!isFileSupported){        
         //  Send "false"
        return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        //  Send "Success"
        return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
    }   
}

---Supplement:---

basically you can send multiple parameters this way:

Controller:

 return Json(new { 
                success = true,
                Name = model.Name,
                Phone = model.Phone,
                Email = model.Email                                
            }, 
            JsonRequestBehavior.AllowGet);

Html:

<script> 
     $.ajax({
                type: "POST",
                url: '@Url.Action("GetData")',
                contentType: 'application/json; charset=utf-8',            
                success: function (response) {

                   if(response.success){ 
                      console.log(response.Name);
                      console.log(response.Phone);
                      console.log(response.Email);
                    }


                },
                error: function (response) {
                    alert("error!"); 
                }
            });

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.

JavaScript variable assignments from tuples

This is not intended to be actually used in real life, just an interesting exercise. See Why is using the JavaScript eval function a bad idea? for details.

This is the closest you can get without resorting to vendor-specific extensions:

myArray = [1,2,3];
eval(set('a,b,c = myArray'));

Helper function:

function set(code) {
    var vars=code.split('=')[0].trim().split(',');
    var array=code.split('=')[1].trim();
    return 'var '+vars.map(function(x,i){return x+'='+array+'['+i+']'}).join(',');
}

Proof that it works in arbitrary scope:

(function(){
    myArray = [4,5,6];
    eval(set('x,y,z = myArray'));
    console.log(y);  // prints 5
})()

eval is not supported in Safari.

Get full query string in C# ASP.NET

just a moment ago, i came across with the same issue. and i resolve it in the following manner.

Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);

with reference to the this

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

for me the shortest way is to type ./gradlew signingReport in the terminal command line.

P.s : if you are in Windows use .\gradlew signingReport instead.

Undo git update-index --assume-unchanged <file>

Adding to @adardesign's answer, if you want to reset all files that have been added to assume-unchanged list to no-assume-unchanged in one go, you can do the following:

git ls-files -v | grep '^h' | sed 's/^..//' | sed 's/\ /\\ /g' | xargs -I FILE git update-index --no-assume-unchanged FILE || true

This will just strip out the two characters output from grep i.e. "h ", then escape any spaces that may be present in file names, and finally || true will prevent the command to terminate prematurely in case some files in the loop has errors.

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

How do I disable a Pylint warning?

This is a FAQ:

4.1 Is it possible to locally disable a particular message?

Yes, this feature has been added in Pylint 0.11. This may be done by adding # pylint: disable=some-message,another-one at the desired block level or at the end of the desired line of code.

4.2 Is there a way to disable a message for a particular module only?

Yes, you can disable or enable (globally disabled) messages at the module level by adding the corresponding option in a comment at the top of the file:

# pylint: disable=wildcard-import, method-hidden
# pylint: enable=too-many-lines

You can disable messages by:

  • numerical ID: E1101, E1102, etc.
  • symbolic message: no-member, undefined-variable, etc.
  • the name of a group of checks. You can grab those with pylint --list-groups.
  • category of checks: C, R, W, etc.
  • all the checks with all.

See the documentation (or run pylint --list-msgs in the terminal) for the full list of Pylint's messages. The documentation also provide a nice example of how to use this feature.

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

Why is a div with "display: table-cell;" not affected by margin?

Cause

From the MDN documentation:

[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table

In other words, the margin property is not applicable to display:table-cell elements.

Solution

Consider using the border-spacing property instead.

Note it should be applied to a parent element with a display:table layout and border-collapse:separate.

For example:

HTML

<div class="table">
    <div class="row">
        <div class="cell">123</div>
        <div class="cell">456</div>
        <div class="cell">879</div>
    </div>
</div>

CSS

.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}

See jsFiddle demo


Different margin horizontally and vertically

As mentioned by Diego QuirĂ³s, the border-spacing property also accepts two values to set a different margin for the horizontal and vertical axes.

For example

.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */

What's the difference between Invoke() and BeginInvoke()

Just adding why and when to use Invoke().

Both Invoke() and BeginInvoke() marshal the code you specify to the dispatcher thread.

But unlike BeginInvoke(), Invoke() stalls your thread until the dispatcher executes your code. You might want to use Invoke() if you need to pause an asynchronous operation until the user has supplied some sort of feedback.

For example, you could call Invoke() to run a snippet of code that shows an OK/Cancel dialog box. After the user clicks a button and your marshaled code completes, the invoke() method will return, and you can act upon the user's response.

See Pro WPF in C# chapter 31

How can I install Apache Ant on Mac OS X?

If you have MacPorts installed (https://www.macports.org/), do this:

sudo port install apache-ant

JavaScript: Passing parameters to a callback function

Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:

function tryMe (param1, param2) {
    alert (param1 + " and " + param2);
}

function callbackTester (callback) {
    callback();
}

callbackTester(tryMe.bind(null, "hello", "goodbye"));

You can also use the following code, which adds the method if it isn't available in the current browser:

// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
  Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments),
        object = args.shift(); 
    return function(){ 
      return fn.apply(object, 
        args.concat(Array.prototype.slice.call(arguments))); 
    }; 
  };
}

Example

bind() - PrototypeJS Documentation

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

There are quite a few projects that have settled on the Generic Graphics Toolkit for this. The GMTL in there is nice - it's quite small, very functional, and been used widely enough to be very reliable. OpenSG, VRJuggler, and other projects have all switched to using this instead of their own hand-rolled vertor/matrix math.

I've found it quite nice - it does everything via templates, so it's very flexible, and very fast.


Edit:

After the comments discussion, and edits, I thought I'd throw out some more information about the benefits and downsides to specific implementations, and why you might choose one over the other, given your situation.

GMTL -

Benefits: Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use.

Downsides: API is very focused specifically on rendering and graphics. Doesn't include general purpose (NxM) matrices, matrix decomposition and solving, etc, since these are outside the realm of traditional graphics/geometry applications.

Eigen -

Benefits: Clean API, fairly easy to use. Includes a Geometry module with quaternions and geometric transforms. Low memory overhead. Full, highly performant solving of large NxN matrices and other general purpose mathematical routines.

Downsides: May be a bit larger scope than you are wanting (?). Fewer geometric/rendering specific routines when compared to GMTL (ie: Euler angle definitions, etc).

IMSL -

Benefits: Very complete numeric library. Very, very fast (supposedly the fastest solver). By far the largest, most complete mathematical API. Commercially supported, mature, and stable.

Downsides: Cost - not inexpensive. Very few geometric/rendering specific methods, so you'll need to roll your own on top of their linear algebra classes.

NT2 -

Benefits: Provides syntax that is more familiar if you're used to MATLAB. Provides full decomposition and solving for large matrices, etc.

Downsides: Mathematical, not rendering focused. Probably not as performant as Eigen.

LAPACK -

Benefits: Very stable, proven algorithms. Been around for a long time. Complete matrix solving, etc. Many options for obscure mathematics.

Downsides: Not as highly performant in some cases. Ported from Fortran, with odd API for usage.

Personally, for me, it comes down to a single question - how are you planning to use this. If you're focus is just on rendering and graphics, I like Generic Graphics Toolkit, since it performs well, and supports many useful rendering operations out of the box without having to implement your own. If you need general purpose matrix solving (ie: SVD or LU decomposition of large matrices), I'd go with Eigen, since it handles that, provides some geometric operations, and is very performant with large matrix solutions. You may need to write more of your own graphics/geometric operations (on top of their matrices/vectors), but that's not horrible.

Disable Laravel's Eloquent timestamps

If you only need to only to disable updating updated_at just add this method to your model.

public function setUpdatedAtAttribute($value)
{
    // to Disable updated_at
}

This will override the parent setUpdatedAtAttribute() method. created_at will work as usual. Same way you can write a method to disable updating created_at only.

How to run multiple DOS commands in parallel?

You can execute commands in parallel with start like this:

start "" ping myserver
start "" nslookup myserver
start "" morecommands

They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.

Hope this helps!

Find length of 2D array Python

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths

Check if application is installed - Android

If you want to try it without the try catch block, can use the following method, Create a intent and set the package of the app which you want to verify

val intent = Intent(Intent.ACTION_VIEW)
intent.data = uri
intent.setPackage("com.example.packageofapp")

and the call the following method to check if the app is installed

fun isInstalled(intent:Intent) :Boolean{
    val list = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
    return list.isNotEmpty()
}

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I have this issue as well. I am using Mac OSX. The way I fixed that was to login as admin

sudo su

password

How to grant remote access to MySQL for a whole subnet?

EDIT: Consider looking at and upvoting Malvineous's answer on this page. Netmasks are a much more elegant solution.


Simply use a percent sign as a wildcard in the IP address.

From http://dev.mysql.com/doc/refman/5.1/en/grant.html

You can specify wildcards in the host name. For example, user_name@'%.example.com' applies to user_name for any host in the example.com domain, and user_name@'192.168.1.%' applies to user_name for any host in the 192.168.1 class C subnet.

How do I reference a cell within excel named range?

To read a particular date from range EJ_PAYDATES_2021 (index is next to the last "1")

=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,1,1)  // Jan
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,2,1)  // Feb
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,3,1)  // Mar

This allows reading a particular element of a range [0] etc from another spreadsheet file. Target file need not be open. Range in the above example is named EJ_PAYDATES_2021, with one element for each month contained within that range.

Took me a while to parse this out, but it works, and is the answer to the question asked above.

How to solve PHP error 'Notice: Array to string conversion in...'

<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>

if you want to capture the result in a variable

How can I verify if an AD account is locked?

This ScriptingGuy guest post links to a script by a Microsoft Powershell Expert can help you find this information, but to fully audit why it was locked and which machine triggered the lock you probably need to turn on additional levels of auditing via GPO.

https://gallery.technet.microsoft.com/scriptcenter/Get-LockedOutLocation-b2fd0cab#content

Open button in new window?

Opens a new window with the url you supplied :)

<button class="button" onClick="window.open('http://www.example.com');">
     <span class="icon">Open</span>
</button>

hope that helps :)

Eclipse: The declared package does not match the expected package

Go to src folder of the project and copy all the code from it to some temporary location and build the project. And now copy the actual code from temporary location to project src. And run the build again. Problem will be resolved.

Note: This is specific to eclipse.

What is the difference between SAX and DOM?

Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation

SAX:

  1. Parses node by node

  2. Does not store the XML in memory

  3. We cant insert or delete a node

  4. Top to bottom traversing

DOM

  1. Stores the entire XML document into memory before processing

  2. Occupies more memory

  3. We can insert or delete nodes

  4. Traverse in any direction.

If we need to find a node and does not need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

MVC controller : get JSON object from HTTP body?

Once you define a class (MyDTOClass) indicating what you expect to receive it should be as simple as...

public ActionResult Post([FromBody]MyDTOClass inputData){
 ... do something with input data ...
}

Thx to Julias:

Parsing Json .Net Web Api

Make sure your request is sent with the http header:

Content-Type: application/json

windows batch file rename

I found this solution via PowerShell :

dir | rename-item -NewName {$_.name -replace "replaceME","MyNewTxt"}

This will rename parts of all the files in the current folder.

How to get last 7 days data from current datetime to last 7 days in sql server

Try something like:

 SELECT id, NewsHeadline as news_headline, NewsText as news_text, state CreatedDate as created_on
 FROM News 
 WHERE CreatedDate >= DATEADD(day,-7, GETDATE())

Example of Mockito's argumentCaptor

Here I am giving you a proper example of one callback method . so suppose we have a method like method login() :

 public void login() {
    loginService = new LoginService();
    loginService.login(loginProvider, new LoginListener() {
        @Override
        public void onLoginSuccess() {
            loginService.getresult(true);
        }

        @Override
        public void onLoginFaliure() {
            loginService.getresult(false);

        }
    });
    System.out.print("@@##### get called");
}

I also put all the helper class here to make the example more clear: loginService class

public class LoginService implements Login.getresult{
public void login(LoginProvider loginProvider,LoginListener callback){

    String username  = loginProvider.getUsername();
    String pwd  = loginProvider.getPassword();
    if(username != null && pwd != null){
        callback.onLoginSuccess();
    }else{
        callback.onLoginFaliure();
    }

}

@Override
public void getresult(boolean value) {
    System.out.print("login success"+value);
}}

and we have listener LoginListener as :

interface LoginListener {
void onLoginSuccess();

void onLoginFaliure();

}

now I just wanted to test the method login() of class Login

 @Test
public void loginTest() throws Exception {
    LoginService service = mock(LoginService.class);
    LoginProvider provider = mock(LoginProvider.class);
    whenNew(LoginProvider.class).withNoArguments().thenReturn(provider);
    whenNew(LoginService.class).withNoArguments().thenReturn(service);
    when(provider.getPassword()).thenReturn("pwd");
    when(provider.getUsername()).thenReturn("username");
    login.getLoginDetail("username","password");

    verify(provider).setPassword("password");
    verify(provider).setUsername("username");

    verify(service).login(eq(provider),captor.capture());

    LoginListener listener = captor.getValue();

    listener.onLoginSuccess();

    verify(service).getresult(true);

also dont forget to add annotation above the test class as

@RunWith(PowerMockRunner.class)
@PrepareForTest(Login.class)

Aggregate a dataframe on a given column and display another column

A base R solution is to combine the output of aggregate() with a merge() step. I find the formula interface to aggregate() a little more useful than the standard interface, partly because the names on the output are nicer, so I'll use that:

The aggregate() step is

maxs <- aggregate(Score ~ Group, data = dat, FUN = max)

and the merge() step is simply

merge(maxs, dat)

This gives us the desired output:

R> maxs <- aggregate(Score ~ Group, data = dat, FUN = max)
R> merge(maxs, dat)
  Group Score Info
1     1     3    c
2     2     4    d

You could, of course, stick this into a one-liner (the intermediary step was more for exposition):

merge(aggregate(Score ~ Group, data = dat, FUN = max), dat)

The main reason I used the formula interface is that it returns a data frame with the correct names for the merge step; these are the names of the columns from the original data set dat. We need to have the output of aggregate() have the correct names so that merge() knows which columns in the original and aggregated data frames match.

The standard interface gives odd names, whichever way you call it:

R> aggregate(dat$Score, list(dat$Group), max)
  Group.1 x
1       1 3
2       2 4
R> with(dat, aggregate(Score, list(Group), max))
  Group.1 x
1       1 3
2       2 4

We can use merge() on those outputs, but we need to do more work telling R which columns match up.

How do I remove a CLOSE_WAIT socket connection

As described by Crist Clark.

CLOSE_WAIT means that the local end of the connection has received a FIN from the other end, but the OS is waiting for the program at the local end to actually close its connection.

The problem is your program running on the local machine is not closing the socket. It is not a TCP tuning issue. A connection can (and quite correctly) stay in CLOSE_WAIT forever while the program holds the connection open.

Once the local program closes the socket, the OS can send the FIN to the remote end which transitions you to LAST_ACK while you wait for the ACK of the FIN. Once that is received, the connection is finished and drops from the connection table (if your end is in CLOSE_WAIT you do not end up in the TIME_WAIT state).

Real world use of JMS/message queues?

I've used it to send intraday trades between different fund management systems. If you want to learn more about what a great technology messaging is, I can thoroughly recommend the book "Enterprise Integration Patterns". There are some JMS examples for things like request/reply and publish/subscribe.

Messaging is an excellent tool for integration.

How to convert float value to integer in php?

Use round()

$float_val = 4.5;

echo round($float_val);

You can also set param for precision and rounding mode, for more info

Update (According to your updated question):

$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201

Immutable array in Java

No, this is not possible. However, one could do something like this:

List<Integer> temp = new ArrayList<Integer>();
temp.add(Integer.valueOf(0));
temp.add(Integer.valueOf(2));
temp.add(Integer.valueOf(3));
temp.add(Integer.valueOf(4));
List<Integer> immutable = Collections.unmodifiableList(temp);

This requires using wrappers, and is a List, not an array, but is the closest you will get.

Alternative for PHP_excel

For Writing Excel

  • PEAR's PHP_Excel_Writer (xls only)
  • php_writeexcel from Bettina Attack (xls only)
  • XLS File Generator commercial and xls only
  • Excel Writer for PHP from Sourceforge (spreadsheetML only)
  • Ilia Alshanetsky's Excel extension now on github (xls and xlsx, and requires commercial libXL component)
  • PHP's COM extension (requires a COM enabled spreadsheet program such as MS Excel or OpenOffice Calc running on the server)
  • The Open Office alternative to COM (PUNO) (requires Open Office installed on the server with Java support enabled)
  • PHP-Export-Data by Eli Dickinson (Writes SpreadsheetML - the Excel 2003 XML format, and CSV)
  • Oliver Schwarz's php-excel (SpreadsheetML)
  • Oliver Schwarz's original version of php-excel (SpreadsheetML)
  • excel_xml (SpreadsheetML, despite its name)... link reported as broken
  • The tiny-but-strong (tbs) project includes the OpenTBS tool for creating OfficeOpenXML documents (OpenDocument and OfficeOpenXML formats)
  • SimpleExcel Claims to read and write Microsoft Excel XML / CSV / TSV / HTML / JSON / etc formats
  • KoolGrid xls spreadsheets only, but also doc and pdf
  • PHP_XLSXWriter OfficeOpenXML
  • PHP_XLSXWriter_plus OfficeOpenXML, fork of PHP_XLSXWriter
  • php_writeexcel xls only (looks like it's based on PEAR SEW)
  • spout OfficeOpenXML (xlsx) and CSV
  • Slamdunk/php-excel (xls only) looks like an updated version of the old PEAR Spreadsheet Writer

For Reading Excel

A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.

All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.

Different class for the last element in ng-repeat

<div ng-repeat="file in files" ng-class="!$last ? 'class-for-last' : 'other'">
   {{file.name}}
</div>

That works for me! Good luck!

How to close current tab in a browser window?

As for the people who are still visiting this page, you are only allowed to close a tab that is opened by a script OR by using the anchor tag of HTML with target _blank. Both those can be closed using the

<script>
    window.close();
</script>

CSS: center element within a <div> element

You can use bootstrap flex class name like that:

<div class="d-flex justify-content-center">
    // the elements you want to center
</div>

That will work even with number of elements inside.

How to scale a BufferedImage

scale(..) works a bit differently. You can use bufferedImage.getScaledInstance(..)

ISO C90 forbids mixed declarations and code in C

Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99.

Entity Framework Code First - two Foreign Keys from same table

It's also possible to specify the ForeignKey() attribute on the navigation property:

[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

What I can do to resolve "1 commit behind master"?

If the message is "n commits behind master."

You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.

Steps:

git checkout master
git pull        #this will update your local master
git checkout yourDevBranch
git rebase master

there can be some merge conflicts which you have to resolve.

PostgreSQL: Show tables in PostgreSQL

From the psql command line interface,

First, choose your database

\c database_name

Then, this shows all tables in the current schema:

\dt

Programmatically (or from the psql interface too, of course):

SELECT * FROM pg_catalog.pg_tables;

The system tables live in the pg_catalog database.

How to open a specific port such as 9090 in Google Compute Engine

console.cloud.google.com >> select project >> Networking > VPC network >> firewalls >> create firewall.

To apply the rule to VM instances, select Targets, "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like.

in "Protocols and Ports" enter tcp:9090

Click Save.

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

What's the difference between using CGFloat and float?

As @weichsel stated, CGFloat is just a typedef for either float or double. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode — it will jump to the CGBase.h header where the typedef is defined. The same approach is used for NSInteger and NSUInteger as well.

These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float precision within your own code, you can still use float if you like — it will reduce your memory footprint somewhat. Same goes for integer values.

I suggest you invest the modest time required to make your app 64-bit clean and try running it as such, since most Macs now have 64-bit CPUs and Snow Leopard is fully 64-bit, including the kernel and user applications. Apple's 64-bit Transition Guide for Cocoa is a useful resource.

warning about too many open figures

import matplotlib.pyplot as plt  
plt.rcParams.update({'figure.max_open_warning': 0})

If you use this, you won’t get that error, and it is the simplest way to do that.

Angularjs prevent form submission when input validation fails

I know it's late and was answered, but I'd like to share the neat stuff I made. I created an ng-validate directive that hooks the onsubmit of the form, then it issues prevent-default if the $eval is false:

app.directive('ngValidate', function() {
  return function(scope, element, attrs) {
    if (!element.is('form'))
        throw new Error("ng-validate must be set on a form elment!");

    element.bind("submit", function(event) {
        if (!scope.$eval(attrs.ngValidate, {'$event': event}))
            event.preventDefault();
        if (!scope.$$phase)
            scope.$digest();            
    });
  };
});

In your html:

<form name="offering" method="post" action="offer" ng-validate="<boolean expression">

Renaming files in a folder to sequential numbers

Here a another solution with "rename" command:

find -name 'access.log.*.gz' | sort -Vr | rename 's/(\d+)/$1+1/ge'

Make header and footer files to be included in multiple html pages

Save the HTML you want to include in an .html file:

Content.html

<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">Animated Buttons</a><br>
<a href="howto_css_modals.asp">Modal Boxes</a><br>
<a href="howto_js_animate.asp">Animations</a><br>
<a href="howto_js_progressbar.asp">Progress Bars</a><br>
<a href="howto_css_dropdown.asp">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.asp">Click Dropdowns</a><br>
<a href="howto_css_table_responsive.asp">Responsive Tables</a><br>

Include the HTML

Including HTML is done by using a w3-include-html attribute:

Example

    <div w3-include-html="content.html"></div>

Add the JavaScript

HTML includes are done by JavaScript.

    <script>
    function includeHTML() {
      var z, i, elmnt, file, xhttp;
      /*loop through a collection of all HTML elements:*/
      z = document.getElementsByTagName("*");
      for (i = 0; i < z.length; i++) {
        elmnt = z[i];
        /*search for elements with a certain atrribute:*/
        file = elmnt.getAttribute("w3-include-html");
        if (file) {
          /*make an HTTP request using the attribute value as the file name:*/
          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4) {
              if (this.status == 200) {elmnt.innerHTML = this.responseText;}
              if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
              /*remove the attribute, and call this function once more:*/
              elmnt.removeAttribute("w3-include-html");
              includeHTML();
            }
          } 
          xhttp.open("GET", file, true);
          xhttp.send();
          /*exit the function:*/
          return;
        }
      }
    }
    </script>

Call includeHTML() at the bottom of the page:

Example

<!DOCTYPE html>
<html>
<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};
</script>
<body>

<div w3-include-html="h1.html"></div> 
<div w3-include-html="content.html"></div> 

<script>
includeHTML();
</script>

</body>
</html>

Remove multiple whitespaces

$str='This is   a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

How to substring in jquery

Using .split(). (Second version uses .slice() and .join() on the Array.)

var result = name.split('name')[1];
var result = name.split('name').slice( 1 ).join(''); // May be a little safer

Using .replace().

var result = name.replace('name','');

Using .slice() on a String.

var result = name.slice( 4 );

Extract parameter value from url using regular expressions

You almost had it, just need to escape special regex chars:

regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;

url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'

Edit: Fix for regex by soupagain.

How can I check if a string only contains letters in Python?

(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

How to replace a hash key with another key

h.inject({}) { |m, (k,v)| m[k.sub(/^_/,'')] = v; m }

How do I list one filename per output line in Linux?

Easy, as long as your filenames don't include newlines:

find . -maxdepth 1

If you're piping this into another command, you should probably prefer to separate your filenames by null bytes, rather than newlines, since null bytes cannot occur in a filename (but newlines may):

find . -maxdepth 1 -print0

Printing that on a terminal will probably display as one line, because null bytes are not normally printed. Some programs may need a specific option to handle null-delimited input, such as sort's -z. Your own script similarly would need to account for this.

Error 500: Premature end of script headers

to fix this, I had to change permissions for whole directory to 755 (777 did not work for me), and changed file owners for whole directory

chmod -R 755 public_html
chown -R nobody:nobody public_html

nobody is user that runs php in my computer.

How do you create a remote Git branch?

If you wanna actually just create remote branch without having the local one, you can do it like this:

git push origin HEAD:refs/heads/foo

It pushes whatever is your HEAD to branch foo that did not exist on the remote.

How to run SUDO command in WinSCP to transfer files from Windows to linux

There is an option in WinSCP that does exactly what you are looking for:

enter image description here

enter image description here

Strip off URL parameter with PHP

Here is the actual code for what's described above as the "the safest 'correct' method"...

function reduce_query($uri = '') {
    $kill_params = array('gclid');

    $uri_array = parse_url($uri);
    if (isset($uri_array['query'])) {
        // Do the chopping.
        $params = array();
        foreach (explode('&', $uri_array['query']) as $param) {
          $item = explode('=', $param);
          if (!in_array($item[0], $kill_params)) {
            $params[$item[0]] = isset($item[1]) ? $item[1] : '';
          }
        }
        // Sort the parameter array to maximize cache hits.
        ksort($params);
        // Build new URL (no hosts, domains, or fragments involved).
        $new_uri = '';
        if ($uri_array['path']) {
          $new_uri = $uri_array['path'];
        }
        if (count($params) > 0) {
          // Wish there was a more elegant option.
          $new_uri .= '?' . urldecode(http_build_query($params));
        }
        return $new_uri;
    }
    return $uri;
}

$_SERVER['REQUEST_URI'] = reduce_query($_SERVER['REQUEST_URI']);

However, since this will likely exist prior to the bootstrap of your application, you should probably put it into an anonymous function. Like this...

call_user_func(function($uri) {
    $kill_params = array('gclid');

    $uri_array = parse_url($uri);
    if (isset($uri_array['query'])) {
        // Do the chopping.
        $params = array();
        foreach (explode('&', $uri_array['query']) as $param) {
          $item = explode('=', $param);
          if (!in_array($item[0], $kill_params)) {
            $params[$item[0]] = isset($item[1]) ? $item[1] : '';
          }
        }
        // Sort the parameter array to maximize cache hits.
        ksort($params);
        // Build new URL (no hosts, domains, or fragments involved).
        $new_uri = '';
        if ($uri_array['path']) {
          $new_uri = $uri_array['path'];
        }
        if (count($params) > 0) {
          // Wish there was a more elegant option.
          $new_uri .= '?' . urldecode(http_build_query($params));
        }
        // Update server variable.
        $_SERVER['REQUEST_URI'] = $new_uri;

    }
}, $_SERVER['REQUEST_URI']);

NOTE: Updated with urldecode() to avoid double encoding via http_build_query() function. NOTE: Updated with ksort() to allow params with no value without an error.

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

If the problem is with the index as the staging area for commits (i.e. .git/index), you can simply remove the index (make a backup copy if you want), and then restore index to version in the last commit:

On OSX/Linux:

rm -f .git/index
git reset

On Windows:

del .git\index
git reset

(The reset command above is the same as git reset --mixed HEAD)

You can alternatively use lower level plumbing git read-tree instead of git reset.


If the problem is with index for packfile, you can recover it using git index-pack.

Android studio- "SDK tools directory is missing"

I had this issue when I was trying to reinstall Android Studio through its wizard. I already had a "tools" folder though.

In my case, while the "tools" directory already existed, it will deliver the "sdk tools directory is missing" error for its subfolders also. Somehow my sdk folder only had a libs subdirectory.

When I pasted in sdk/ant, sdk/apps, sdk/proguard, sdk/qemu, sdk/support, and sdk/templates the wizard was finally happy with this configuration and went to download some more files.

Android Studio was unable to find a valid Jvm (Related to MAC OS)

On Mac OS X Yosemite just install:

Java SE Development Kit 8

and

Java Version 8 Update 25

It's all, work for me too! like gehev said , so simple !

Access to Image from origin 'null' has been blocked by CORS policy

Under the covers there will be some form of URL loading request. You can't load images or any other content via this method from a local file system.

Your image needs to be loaded via a web server, so accessed via a proper http URL.

Load an image from a url into a PictureBox

The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

Pip - Fatal error in launcher: Unable to create process using '"'

I got the same error but when using tensorboard:

Fatal error in launcher: Unable to create process using '"'

I found out that the problem was caused by existing two copies of tensotboard.exe in two different directories and both directories were added to the path:

C:\Program Files\Python36\Scripts

and

C:\Users\...\AppData\Local\Programs\Python\Python36\Scripts

I removed the first one from the path and it fixed the problem.

Why is the Java main method static?

there is the simple reason behind it that is because object is not required to call static method , if It were non-static method, java virtual machine creates object first then call main() method that will lead to the problem of extra memory allocation.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

How to know if other threads have finished?

Many things have been changed in last 6 years on multi-threading front.

Instead of using join() and lock API, you can use

1.ExecutorService invokeAll() API

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

2.CountDownLatch

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

3.ForkJoinPool or newWorkStealingPool() in Executors is other way

4.Iterate through all Future tasks from submit on ExecutorService and check the status with blocking call get() on Future object

Have a look at related SE questions:

How to wait for a thread that spawns it's own thread?

Executors: How to synchronously wait until all tasks have finished if tasks are created recursively?

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

Check and make sure that you do not have another values folder that references theme.styled and does not use AppCompat theme

ie values-v11 folder

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

JavaScript loop through json array?

var arr = [
  {
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "[email protected]"
  }, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "[email protected]"
  }
];

forEach method for easy implementation.

arr.forEach(function(item){
  console.log('ID: ' + item.id);
  console.log('MSG: ' + item.msg);
  console.log('TID: ' + item.tid);
  console.log('FROMWHO: ' + item.fromWho);
});

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

I had this same error in python 3.2.

I have script for email sending and:

csv.reader(open('work_dir\uslugi1.csv', newline='', encoding='utf-8'))

when I remove first char in file uslugi1.csv works fine.

R dplyr: Drop multiple columns

also try

## Notice the lack of quotes
iris %>% select (-c(Sepal.Length, Sepal.Width))

jquery can't get data attribute value

Iyap . Its work Case sensitive in data name data-x10

var variable = $('#myButton').data("x10"); // we get the value of custom data attribute

PDO Prepared Inserts multiple rows in single query

what about something like this:

        if(count($types_of_values)>0){
         $uid = 1;
         $x = 0;
         $sql = "";
         $values = array();
          foreach($types_of_values as $k=>$v){
            $sql .= "(:id_$k,:kind_of_val_$k), ";
            $values[":id_$k"] = $uid;
            $values[":kind_of_val_$k"] = $v;
          }
         $sql = substr($sql,0,-2);
         $query = "INSERT INTO table (id,value_type) VALUES $sql";
         $res = $this->db->prepare($query);
         $res->execute($values);            
        }

The idea behind this is to cycle through your array values, adding "id numbers" to each loop for your prepared statement placeholders while at the same time, you add the values to your array for the binding parameters. If you don't like using the "key" index from the array, you could add $i=0, and $i++ inside the loop. Either works in this example, even if you have associative arrays with named keys, it would still work providing the keys were unique. With a little work it would be fine for nested arrays too..

**Note that substr strips the $sql variables last space and comma, if you don't have a space you'd need to change this to -1 rather than -2.

How to check java bit version on Linux?

Why don't you examine System.getProperty("os.arch") value in your code?

How do I make a batch file terminate upon encountering an error?

Here is a polyglot program for BASH and Windows CMD that runs a series of commands and quits out if any of them fail:

#!/bin/bash 2> nul

:; set -o errexit
:; function goto() { return $?; }

command 1 || goto :error

command 2 || goto :error

command 3 || goto :error

:; exit 0
exit /b 0

:error
exit /b %errorlevel%

I have used this type of thing in the past for a multiple platform continuous integration script.

How to use continue in jQuery each() loop?

$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});

How to print Two-Dimensional Array like table

You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".

Passing struct to function

This is how to pass the struct by reference. This means that your function can access the struct outside of the function and modify its values. You do this by passing a pointer to the structure to the function.

#include <stdio.h>
/* card structure definition */
struct card
{
    int face; // define pointer face
}; // end structure card

typedef struct card Card ;

/* prototype */
void passByReference(Card *c) ;

int main(void)
{
    Card c ;
    c.face = 1 ;
    Card *cptr = &c ; // pointer to Card c

    printf("The value of c before function passing = %d\n", c.face);
    printf("The value of cptr before function = %d\n",cptr->face);

    passByReference(cptr);

    printf("The value of c after function passing = %d\n", c.face);

    return 0 ; // successfully ran program
}

void passByReference(Card *c)
{
    c->face = 4;
}

This is how you pass the struct by value so that your function receives a copy of the struct and cannot access the exterior structure to modify it. By exterior I mean outside the function.

#include <stdio.h>


/* global card structure definition */
struct card
{
    int face ; // define pointer face
};// end structure card

typedef struct card Card ;

/* function prototypes */
void passByValue(Card c);

int main(void)
{
    Card c ;
    c.face = 1;

    printf("c.face before passByValue() = %d\n", c.face);

    passByValue(c);

    printf("c.face after passByValue() = %d\n",c.face);
    printf("As you can see the value of c did not change\n");
    printf("\nand the Card c inside the function has been destroyed"
        "\n(no longer in memory)");
}


void passByValue(Card c)
{
    c.face = 5;
}

Read a local text file using Javascript

Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!

<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">

  var x;
  if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
  else { x = new XMLHttpRequest(); }

  function getdata() {
    x.open('get', 'data1.txt', true); 
    x.onreadystatechange= showdata;
    x.send(null);
  }

  function showdata() {
    if(x.readyState==4) {
      var el = document.getElementById('content');
      el.innerHTML = x.responseText;
    }
  }

  </script>
</head>
<body onload="getdata();showdata();">

  <div id="content"></div>

</body>
</html>

How can I check whether an array is null / empty?

I tested as below. Hope it helps.

Integer[] integers1 = new Integer[10];
        System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
        for (Integer integer : integers1) {
            System.out.println(integer); //prints all 0s
        }

//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
//        integers1[2] = 0;
        for (Integer integer : integers1) {
            System.out.println(integer); //Still it prints all 0s but it is not empty
            //but that manually added 0 is different
        }

//Even we manually add 0, still we need to treat it as null. This is semantic logic.

        Integer[] integers2 = new Integer[20];
        integers2 = null; //array is nullified
//        integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line. 
        if (integers2 == null) {
            System.out.println("null Array");
        }   

Send XML data to webservice using php curl

Check this one. It will work.

function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I> 
                <i1>'.$i1.'</i1> 
                <i2>'.$i2.'</i2> 
                <i3>'.$i2.'</i3> 
                <i4>'.$i3.'</i4> 
              </I>';
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8080",
  CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input_data,
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/xml"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
}

fetch('i1','i2','i3','i4');

How to add shortcut keys for java code in eclipse

The feature is called "code templates" in Eclipse. You can add templates with:

Window->Preferences->Java->Editor->Templates.

Two good articles:

Also, this SO question:

System.out.println() is already mapped to sysout, so you may save time by learning a few of the existing templates first.

NULL values inside NOT IN clause

Whenever you use NULL you are really dealing with a Three-Valued logic.

Your first query returns results as the WHERE clause evaluates to:

    3 = 1 or 3 = 2 or 3 = 3 or 3 = null
which is:
    FALSE or FALSE or TRUE or UNKNOWN
which evaluates to 
    TRUE

The second one:

    3 <> 1 and 3 <> 2 and 3 <> null
which evaluates to:
    TRUE and TRUE and UNKNOWN
which evaluates to:
    UNKNOWN

The UNKNOWN is not the same as FALSE you can easily test it by calling:

select 'true' where 3 <> null
select 'true' where not (3 <> null)

Both queries will give you no results

If the UNKNOWN was the same as FALSE then assuming that the first query would give you FALSE the second would have to evaluate to TRUE as it would have been the same as NOT(FALSE).
That is not the case.

There is a very good article on this subject on SqlServerCentral.

The whole issue of NULLs and Three-Valued Logic can be a bit confusing at first but it is essential to understand in order to write correct queries in TSQL

Another article I would recommend is SQL Aggregate Functions and NULL.

Return a "NULL" object if search result not found

There are several possible answers here. You want to return something that might exist. Here are some options, ranging from my least preferred to most preferred:

  • Return by reference, and signal can-not-find by exception.

    Attr& getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            throw no_such_attribute_error;
    }

It's likely that not finding attributes is a normal part of execution, and hence not very exceptional. The handling for this would be noisy. A null value cannot be returned because it's undefined behaviour to have null references.

  • Return by pointer

    Attr* getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return &attributes[i];
       //if not found
            return nullptr;
    }

It's easy to forget to check whether a result from getAttribute would be a non-NULL pointer, and is an easy source of bugs.

  • Use Boost.Optional

    boost::optional<Attr&> getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            return boost::optional<Attr&>();
    }

A boost::optional signifies exactly what is going on here, and has easy methods for inspecting whether such an attribute was found.


Side note: std::optional was recently voted into C++17, so this will be a "standard" thing in the near future.

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

I did some research on this by using different methods to assign values to a nullable int. Here is what happened when I did various things. Should clarify what's going on. Keep in mind: Nullable<something> or the shorthand something? is a struct for which the compiler seems to be doing a lot of work to let us use with null as if it were a class.
As you'll see below, SomeNullable == null and SomeNullable.HasValue will always return an expected true or false. Although not demonstrated below, SomeNullable == 3 is valid too (assuming SomeNullable is an int?).
While SomeNullable.Value gets us a runtime error if we assigned null to SomeNullable. This is in fact the only case where nullables could cause us a problem, thanks to a combination of overloaded operators, overloaded object.Equals(obj) method, and compiler optimization and monkey business.

Here is a description of some code I ran, and what output it produced in labels:

int? val = null;
lbl_Val.Text = val.ToString(); //Produced an empty string.
lbl_ValVal.Text = val.Value.ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValEqNull.Text = (val == null).ToString(); //Produced "True" (without the quotes)
lbl_ValNEqNull.Text = (val != null).ToString(); //Produced "False"
lbl_ValHasVal.Text = val.HasValue.ToString(); //Produced "False"
lbl_NValHasVal.Text = (!(val.HasValue)).ToString(); //Produced "True"
lbl_ValValEqNull.Text = (val.Value == null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValValNEqNull.Text = (val.Value != null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")

Ok, lets try the next initialization method:

int? val = new int?();
lbl_Val.Text = val.ToString(); //Produced an empty string.
lbl_ValVal.Text = val.Value.ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValEqNull.Text = (val == null).ToString(); //Produced "True" (without the quotes)
lbl_ValNEqNull.Text = (val != null).ToString(); //Produced "False"
lbl_ValHasVal.Text = val.HasValue.ToString(); //Produced "False"
lbl_NValHasVal.Text = (!(val.HasValue)).ToString(); //Produced "True"
lbl_ValValEqNull.Text = (val.Value == null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValValNEqNull.Text = (val.Value != null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")

All the same as before. Keep in mind that initializing with int? val = new int?(null);, with null passed to the constructor, would have produced a COMPILE time error, since the nullable object's VALUE is NOT nullable. It is only the wrapper object itself that can equal null.

Likewise, we would get a compile time error from:

int? val = new int?();
val.Value = null;

not to mention that val.Value is a read-only property anyway, meaning we can't even use something like:

val.Value = 3;

but again, polymorphous overloaded implicit conversion operators let us do:

val = 3;

No need to worry about polysomthing whatchamacallits though, so long as it works right? :)

How do I plot in real-time in a while loop using matplotlib?

Here's the working version of the code in question (requires at least version Matplotlib 1.1.0 from 2011-11-14):

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 1])

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.05)

plt.show()

Note some of the changes:

  1. Call plt.pause(0.05) to both draw the new data and it runs the GUI's event loop (allowing for mouse interaction).

Can not connect to local PostgreSQL

In my case none of previous solutions was good. Instead of using socket, you can use TCP host + port number in Rails config file. So in database.yml file just add two lines like here:

...
adapter: postgresql
encoding: unicode
pool: 5
host: localhost
port: 5432

This solved my problem :)

Before I used this fix:

sudo mkdir /var/run/postgresql
sudo ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432

But after each reboot /tmp/.s.PGSQL.5432 was deleted and I had to repeat these commands. Solution works, but it is horrible, so better just modify Rails database config file :)

How to get index in Handlebars each helper?

In handlebar version 3.0 onwards,

{{#each users as |user userId|}}
  Id: {{userId}} Name: {{user.name}}
{{/each}}

In this particular example, user will have the same value as the current context and userId will have the index value for the iteration. Refer - http://handlebarsjs.com/block_helpers.html in block helpers section

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

The best way to solve this is to use Vanilla JS, but if you are already using jQuery, there´s a very easy solution:

<script type="text/javascript">
    function doOnClick() {
        $('#linkid').click();
    }
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>

Tested in IE8-10, Chrome, Firefox.

Convert Array to Object

You could use a function like this:

var toObject = function(array) {
    var o = {};
    for (var property in array) {
        if (String(property >>> 0) == property && property >>> 0 != 0xffffffff) {
            o[i] = array[i];
        }
    }
    return o;
};

This one should handle sparse arrays more efficiently.

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

Are there best practices for (Java) package organization?

I prefer feature before layers, but I guess it depends on you project. Consider your forces:

  • Dependencies
    Try minimize package dependencies, especially between features. Extract APIs if necessary.
  • Team organization
    In some organizations teams work on features and in others on layers. This influence how code is organized, use it to formalize APIs or encourage cooperation.
  • Deployment and versioning
    Putting everything into a module make deployment and versioning simpler, but bug fixing harder. Splitting things enable better control, scalability and availability.
  • Respond to change
    Well organized code is much simpler to change than a big ball of mud.
  • Size (people and lines of code)
    The bigger the more formalized/standardized it needs to be.
  • Importance/quality
    Some code is more important than other. APIs should be more stable then the implementation. Therefore it needs to be clearly separated.
  • Level of abstraction and entry point
    It should be possible for an outsider to know what the code is about, and where to start reading from looking at the package tree.

Example:

com/company/module
  + feature1/
    - MainClass          // The entry point for exploring
    + api/               // Public interface, used by other features
    + domain/
      - AggregateRoot
      + api/             // Internal API, complements the public, used by web
      + impl/ 
    + persistence/       
    + web/               // presentation layer 
    + services/          // Rest or other remote API 
    + support/            
  + feature2/
  + support/             // Any support or utils used by more than on feature
    + io
    + config
    + persistence
    + web

This is just an example. It is quite formal. For example it defines 2 interfaces for feature1. Normally that is not required, but could be a good idea if used differently by different people. You may let the internal API extend the public.

I do not like the 'impl' or 'support' names, but they help separate the less important stuff from the important (domain and API). When it comes to naming I like to be as concrete as possible. If you have a package called 'utils' with 20 classes, move StringUtils to support/string, HttpUtil to support/http and so on.

how to get the one entry from hashmap without iterating

I got the answer:(It's simple )

Take a ArrayList then cast it and find the size of the arraylist. Here it is :

    ArrayList count = new ArrayList();
    count=(ArrayList) maptabcolname.get("k1"); //here "k1" is Key
    System.out.println("number of elements="+count.size());

It will show the size. (Give suggestion). It's working.

remove item from stored array in angular 2

This can be achieved as follows:

this.itemArr = this.itemArr.filter( h => h.id !== ID);

How to get array keys in Javascript?

Your original example works just fine for me:

<html>
<head>
</head>
<body>
<script>
var widthRange = new Array();
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

var i = 1;
for (var key in widthRange)
{
    document.write("Key #" + i + " = " + key + "; &nbsp;&nbsp;&nbsp; min/max = " + widthRange[key].min + "/" + widthRange[key].max + "<br />");
    i++;
}
</script>
</html>

Results in the browser (Firefox 3.6.2 on Windows XP):

Key #1 = 46;     min/max = 0/52
Key #2 = 66;     min/max = 52/70
Key #3 = 90;     min/max = 70/94

How can I merge properties of two JavaScript objects dynamically?

The given solutions should be modified to check source.hasOwnProperty(property) in the for..in loops before assigning - otherwise, you end up copying the properties of the whole prototype chain, which is rarely desired...

From a Sybase Database, how I can get table description ( field names and types)?

When finding user table, in case if want the table owner name also, you can use the following:

select su.name + '.' + so.name
from   sysobjects so,
       sysusers   su
where  so.type = 'U' and
       so.uid  = su.uid
order  by su.name,
          so.name

Python constructor and default value

Let's illustrate what's happening here:

Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __init__(self, x=[]):
...         x.append(1)
... 
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)

You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.

As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.

How to lock specific cells but allow filtering and sorting

I just came up with a tricky way to get almost the same functionality. Instead of protecting the sheet the normal way, use an event handler to undo anything the user tries to do.

Add the following to the worksheet's module:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Locked = True Then
        Application.EnableEvents = False
        Application.Undo
        Application.EnableEvents = True
    End If
End Sub

If the user does anything to change a cell that's locked, the action will get immediately undone. The temporary disabling of events is to keep the undoing itself from triggering this event, resulting in an infinite loop.

Sorting and filtering do not trigger the Change event, so those functions remain enabled.

Note that this solution prevents changing or clearing cell contents, but does not prevent changing formats. A determined user could get around it by simply setting the cells to be unlocked.

How to show and update echo on same line

My favorite way is called do the sleep to 50. here i variable need to be used inside echo statements.

for i in $(seq 1 50); do
  echo -ne "$i%\033[0K\r"
  sleep 50
done
echo "ended"

How can I regenerate ios folder in React Native project?

Simply remove/delete android and ios (keep backup android and ios folder) and run following command:

  react-native eject

Supported version : 
    react-native <= 0.59.10
    react-native-cli <= 1.3.0 



   react-native upgrade --legacy true

Supported version : 
        react-native >= 0.60.0
        react-native-cli >= 2.1.0 

Ref : link

Executing a batch file in a remote machine through PsExec

You have an extra -c you need to get rid of:

psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"

Error:Cause: unable to find valid certification path to requested target

For me this worked:

buildscript {
    repositories {
        maven { url "http://jcenter.bintray.com"}
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
...
}

allprojects {
    repositories {
        mavenCentral()
        jcenter{ url "http://jcenter.bintray.com/" }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I have a project that uses generators a lot and needed this to be automatic, so I copied the index_name function from the rails source to override it. I added this in config/initializers/generated_index_name.rb:

# make indexes shorter for postgres
require "active_record/connection_adapters/abstract/schema_statements"
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module SchemaStatements
      def index_name(table_name, options) #:nodoc:
        if Hash === options
          if options[:column]
            "ix_#{table_name}_on_#{Array(options[:column]) * '__'}".slice(0,63)
          elsif options[:name]
            options[:name]
          else
            raise ArgumentError, "You must specify the index name"
          end
        else
          index_name(table_name, index_name_options(options))
        end
      end
    end
  end
end

It creates indexes like ix_assignments_on_case_id__project_id and just truncates it to 63 characters if it's still too long. That's still going to be non-unique if the table name is very long, but you can add complications like shortening the table name separately from the column names or actually checking for uniqueness.

Note, this is from a Rails 5.2 project; if you decide to do this, copy the source from your version.

changing the language of error message in required field in html5 contact form

<input type="text" id="inputName"  placeholder="Enter name"  required  oninvalid="this.setCustomValidity('Your Message')" oninput="this.setCustomValidity('') />

this can help you even more better, Fast, Convenient & Easiest.

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

How to query as GROUP BY in django?

The following module allows you to group Django models and still work with a QuerySet in the result: https://github.com/kako-nawao/django-group-by

For example:

from django_group_by import GroupByMixin

class BookQuerySet(QuerySet, GroupByMixin):
    pass

class Book(Model):
    title = TextField(...)
    author = ForeignKey(User, ...)
    shop = ForeignKey(Shop, ...)
    price = DecimalField(...)

class GroupedBookListView(PaginationMixin, ListView):
    template_name = 'book/books.html'
    model = Book
    paginate_by = 100

    def get_queryset(self):
        return Book.objects.group_by('title', 'author').annotate(
            shop_count=Count('shop'), price_avg=Avg('price')).order_by(
            'name', 'author').distinct()

    def get_context_data(self, **kwargs):
        return super().get_context_data(total_count=self.get_queryset().count(), **kwargs)

'book/books.html'

<ul>
{% for book in object_list %}
    <li>
        <h2>{{ book.title }}</td>
        <p>{{ book.author.last_name }}, {{ book.author.first_name }}</p>
        <p>{{ book.shop_count }}</p>
        <p>{{ book.price_avg }}</p>
    </li>
{% endfor %}
</ul>

The difference to the annotate/aggregate basic Django queries is the use of the attributes of a related field, e.g. book.author.last_name.

If you need the PKs of the instances that have been grouped together, add the following annotation:

.annotate(pks=ArrayAgg('id'))

NOTE: ArrayAgg is a Postgres specific function, available from Django 1.9 onwards: https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/aggregates/#arrayagg

How do I generate a stream from a string?

A good combination of String extensions:

public static byte[] GetBytes(this string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

public static Stream ToStream(this string str)
{
    Stream StringStream = new MemoryStream();
    StringStream.Read(str.GetBytes(), 0, str.Length);
    return StringStream;
}

Facebook Post Link Image

If you used any plugin for seo then Check 1st your seo plugin settings.Then find out Noindex setting if Enable Media for Noindex then disable it.

How to set default value for HTML select?

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

First check for gmail's security related issues. You may have enabled double authentication in gmail. Also check your gmail inbox if you are getting any security alerts. In such cases check other answer of @mjb as below

Below is the very general thing that i always check first for such issues

client.UseDefaultCredentials = true;

set it to false.

Note @Joe King's answer - you must set client.UseDefaultCredentials before you set client.Credentials

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

The Python 3 range() object doesn't produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration.

The object also implements the object.__contains__ hook, and calculates if your number is part of its range. Calculating is a (near) constant time operation *. There is never a need to scan through all possible integers in the range.

From the range() object documentation:

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

So at a minimum, your range() object would do:

class my_range:
    def __init__(self, start, stop=None, step=1, /):
        if stop is None:
            start, stop = 0, start
        self.start, self.stop, self.step = start, stop, step
        if step < 0:
            lo, hi, step = stop, start, -step
        else:
            lo, hi = start, stop
        self.length = 0 if lo > hi else ((hi - lo - 1) // step) + 1

    def __iter__(self):
        current = self.start
        if self.step < 0:
            while current > self.stop:
                yield current
                current += self.step
        else:
            while current < self.stop:
                yield current
                current += self.step

    def __len__(self):
        return self.length

    def __getitem__(self, i):
        if i < 0:
            i += self.length
        if 0 <= i < self.length:
            return self.start + i * self.step
        raise IndexError('my_range object index out of range')

    def __contains__(self, num):
        if self.step < 0:
            if not (self.stop < num <= self.start):
                return False
        else:
            if not (self.start <= num < self.stop):
                return False
        return (num - self.start) % self.step == 0

This is still missing several things that a real range() supports (such as the .index() or .count() methods, hashing, equality testing, or slicing), but should give you an idea.

I also simplified the __contains__ implementation to only focus on integer tests; if you give a real range() object a non-integer value (including subclasses of int), a slow scan is initiated to see if there is a match, just as if you use a containment test against a list of all the contained values. This was done to continue to support other numeric types that just happen to support equality testing with integers but are not expected to support integer arithmetic as well. See the original Python issue that implemented the containment test.


* Near constant time because Python integers are unbounded and so math operations also grow in time as N grows, making this a O(log N) operation. Since it’s all executed in optimised C code and Python stores integer values in 30-bit chunks, you’d run out of memory before you saw any performance impact due to the size of the integers involved here.

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

Can I use a min-height for table, tr or td?

Simply use the css entry of min-height to one of the cells of your table row. Works on old browsers too.

.rowNumberColumn {
    background-color: #e6e6e6;
    min-height: 22;
}

<table width="100%" cellspacing="0" class="htmlgrid-table">
    <tr id="tr_0">
            <td width="3%" align="center" class="readOnlyCell rowNumberColumn">1</td>
            <td align="left" width="40%" id="td_0_0" class="readOnlyCell gContentSection">411978430-Intimate:Ruby:Small</td>

How to create a CPU spike with a bash command

:(){ :|:& };:

This fork bomb will cause havoc to the CPU and will likely crash your computer.

Margin while printing html page

I'd personally suggest using a different unit of measurement than px. I don't think that pixels have much relevance in terms of print; ideally you'd use:

  • point (pt)
  • centimetre (cm)

I'm sure there are others, and one excellent article about print-css can be found here: Going to Print, by Eric Meyer.

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

Column/Vertical selection with Keyboard in SublimeText 3

Commenting just so people can have a solution to the intended question.

You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.

In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.

The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.

Python NoneType object is not callable (beginner)

You want to pass the function object hi to your loop() function, not the result of a call to hi() (which is None since hi() doesn't return anything).

So try this:

>>> loop(hi, 5)
hi
hi
hi
hi
hi

Perhaps this will help you understand better:

>>> print hi()
hi
None
>>> print hi
<function hi at 0x0000000002422648>

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

What's the difference between Unicode and UTF-8?

UTF-16 and UTF-8 are both encodings of Unicode. They are both Unicode; one is not more Unicode than the other.

Don't let an unfortunate historical artifact from Microsoft confuse you.

Overwriting txt file in java

This simplifies it a bit and it behaves as you want it.

FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");

try {
 f.write(source);
 ...
} catch(...) {
} finally {
 //close it here
}

Excel CSV. file with more than 1,048,576 rows of data

Use MS Access. I have a file of 2,673,404 records. It will not open in notepad++ and excel will not load more than 1,048,576 records. It is tab delimited since I exported the data from a mysql database and I need it in csv format. So I imported it into Access. Change the file extension to .txt so MS Access will take you through the import wizard.

MS Access will link to your file so for the database to stay intact keep the csv file

What is the equivalent to getLastInsertId() in Cakephp?

$this->Model->field('id', null, 'id DESC')

How to use (install) dblink in PostgreSQL?

Installing modules usually requires you to run an sql script that is included with the database installation.

Assuming linux-like OS

find / -name dblink.sql

Verify the location and run it

How do I download a file using VBA (without Internet Explorer)

This solution is based from this website: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

It is slightly modified to overwrite existing file and to pass along login credentials.

Sub DownloadFile()

Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send

If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

End Sub

How should I unit test multithreaded code?

I spent most of last week at a university library studying debugging of concurrent code. The central problem is concurrent code is non-deterministic. Typically, academic debugging has fallen into one of three camps here:

  1. Event-trace/replay. This requires an event monitor and then reviewing the events that were sent. In a UT framework, this would involve manually sending the events as part of a test, and then doing post-mortem reviews.
  2. Scriptable. This is where you interact with the running code with a set of triggers. "On x > foo, baz()". This could be interpreted into a UT framework where you have a run-time system triggering a given test on a certain condition.
  3. Interactive. This obviously won't work in an automatic testing situation. ;)

Now, as above commentators have noticed, you can design your concurrent system into a more deterministic state. However, if you don't do that properly, you're just back to designing a sequential system again.

My suggestion would be to focus on having a very strict design protocol about what gets threaded and what doesn't get threaded. If you constrain your interface so that there is minimal dependancies between elements, it is much easier.

Good luck, and keep working on the problem.

Press Enter to move to next control

private void txt_invoice_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            txt_date.Focus();
    }

    private void txt_date_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            txt_patientname.Focus();
    }

}

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

Prevent overwriting a file using cmd if exist

I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...

CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"

two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult. also...

start \\filer\repo\lab\"software"\"myapp"\setup.exe

the start code here, can be set up like that, but the correct syntax is

start "\\filter\repo\lab\software\myapp\" setup.exe

This will run: setup.exe, located in: \filter\repo\lab...etc.\

The name 'ViewBag' does not exist in the current context

For MVC5, in case you are building an application from scratch. You need to add a web.config file to the Views folder and paste the following code in it.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
</configuration>

Note that for MVC 3 you will have to change version to 3.0.0.0 at

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

You may have to close and open the *.cshtml page again to see the changes.

How to create a dynamic array of integers

int* array = new int[size];

Is there a Subversion command to reset the working copy?

Pure Windows cmd/bat solution:

svn cleanup .
svn revert -R .
For /f "tokens=1,2" %%A in ('svn status --no-ignore') Do (
     If [%%A]==[?] ( Call :UniDelete %%B
     ) Else If [%%A]==[I] Call :UniDelete %%B
   )
svn update .
goto :eof

:UniDelete delete file/dir
IF EXIST "%1\*" (
    RD /S /Q "%1"
) Else (
    If EXIST "%1" DEL /S /F /Q "%1"
)
goto :eof

Clicking a button within a form causes page refresh

I also had the same problem, but gladelly I fixed this by changing the type like from type="submit" to type="button" and it worked.

Adding to an ArrayList Java

Instantiate a new ArrayList:

List<String> myList = new ArrayList<String>();

Iterate over your data structure (with a for loop, for instance, more details on your code would help.) and for each element (yourElement):

myList.add(yourElement);

how to stop a running script in Matlab

Consider having multiple matlab sessions. Keep the main session window (the pretty one with all the colours, file manager, command history, workspace, editor etc.) for running stuff that you know will terminate.

Stuff that you are experimenting with, say you are messing with ode suite and you get lots of warnings: matrix singular, because you altered some parameter and didn't predict what would happen, run in a separate session:

dos('matlab -automation -r &')

You can kill that without having to restart the whole of Matlab.

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Edit the configuration and then in the box: Script path, select your .py file!

Confirmation before closing of tab/browser

The shortest solution for the year 2020 (for those happy people who don't need to support IE)

Tested in Chrome, Firefox, Safari.

function onBeforeUnload(e) {
    if (thereAreUnsavedChanges()) {
        e.preventDefault();
        e.returnValue = '';
        return;
    }

    delete e['returnValue'];
}

window.addEventListener('beforeunload', onBeforeUnload);

Actually no one modern browser (Chrome, Firefox, Safari) displays the "return value" as a question to user. Instead they show their own confirmation text (it depends on browser). But we still need to return some (even empty) string to trigger that confirmation on Chrome.

More explanations see on MDN here and here.

Saving images in Python at a very high quality

Just to add my results, also using Matplotlib.

.eps made all my text bold and removed transparency. .svg gave me high-resolution pictures that actually looked like my graph.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Do the plot code
fig.savefig('myimage.svg', format='svg', dpi=1200)

I used 1200 dpi because a lot of scientific journals require images in 1200 / 600 / 300 dpi, depending on what the image is of. Convert to desired dpi and format in GIMP or Inkscape.

Obviously the dpi doesn't matter since .svg are vector graphics and have "infinite resolution".

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.

You should pass your connection object in as a dependency, eg

function getPosts(mysqli $con) {
    // etc

I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");

getPosts($con);

How do I choose grid and block dimensions for CUDA kernels?

The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

What is the difference between document.location.href and document.location?

typeof document.location; // 'object'
typeof document.location.href; // 'string'

The href property is a string, while document.location itself is an object.

Accessing Google Account Id /username via Android

This Method to get Google Username:

 public String getUsername() {
    AccountManager manager = AccountManager.get(this);
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> possibleEmails = new LinkedList<String>();

    for (Account account : accounts) {
        // TODO: Check possibleEmail against an email regex or treat
        // account.name as an email address only for certain account.type
        // values.
        possibleEmails.add(account.name);
    }

    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        String email = possibleEmails.get(0);
        String[] parts = email.split("@");
        if (parts.length > 0 && parts[0] != null)
            return parts[0];
        else
            return null;
    } else
        return null;
}

simple this method call ....

And Get Google User in Gmail id::

 accounts = AccountManager.get(this).getAccounts();
    Log.e("", "Size: " + accounts.length);
    for (Account account : accounts) {

        String possibleEmail = account.name;
        String type = account.type;

        if (type.equals("com.google")) {
            strGmail = possibleEmail;

            Log.e("", "Emails: " + strGmail);
            break;
        }
    }

After add permission in manifest;

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

How to store an output of shell script to a variable in Unix?

You should probably re-write the script to return a value rather than output it. Instead of:

a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
   success) echo script succeeded;;
   Failed) echo script failed;;
esac

you would be able to do:

if script.sh > /dev/null; then
    echo script succeeded
else
    echo script failed
fi

It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0 instead of printing success, and exit 1 instead of printing Failed. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.

Row count where data exists

I've implemented it like this:

Public Function LastRowWithData(ByVal strCol As String, ByVal intRow As Integer) As Long
    Range(strCol & intRow).Select
    LastRowWithData= ActiveSheet.Cells(ActiveSheet.Rows.Count, strCol).End(xlUp).Row
End Function

Spring Boot - inject map from application.yml

You can make it even simplier, if you want to avoid extra structures.

service:
  mappings:
    key1: value1
    key2: value2
@Configuration
@EnableConfigurationProperties
public class ServiceConfigurationProperties {

  @Bean
  @ConfigurationProperties(prefix = "service.mappings")
  public Map<String, String> serviceMappings() {
    return new HashMap<>();
  }

}

And then use it as usual, for example with a constructor:

public class Foo {

  private final Map<String, String> serviceMappings;

  public Foo(Map<String, String> serviceMappings) {
    this.serviceMappings = serviceMappings;
  }

}

Can I change the Android startActivity() transition animation?

Use overridePendingTransition

startActivity();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);

fadein.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
</set>

fadeout.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/anticipate_interpolator"
        android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
</set>

Python POST binary data

You can use unirest, It provides easy method to post request. `

import unirest
 
def callback(response):
 print "code:"+ str(response.code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "body:"+ str(response.body)
 print "******************"
 print "raw_body:"+ str(response.raw_body)
 
# consume async post request
def consumePOSTRequestASync():
 params = {'test1':'param1','test2':'param2'}
 
 # we need to pass a dummy variable which is open method
 # actually unirest does not provide variable to shift between
 # application-x-www-form-urlencoded and
 # multipart/form-data
  
 params['dummy'] = open('dummy.txt', 'r')
 url = 'http://httpbin.org/post'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 unirest.post(url, headers = headers,params = params, callback = callback)
 
 
# post async request multipart/form-data
consumePOSTRequestASync()

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

Passing data through intent using Serializable

In kotlin: Object class implements Serializable:

class MyClass: Serializable {
//members
}

At the point where the object sending:

val fragment = UserDetailFragment()
val bundle = Bundle()
bundle.putSerializable("key", myObject)
fragment.arguments = bundle

At the fragment, where we want to get our object:

val bundle: Bundle? = arguments
    bundle?.let {
        val myObject = it.getSerializable("key") as MyClass
        myObject.memberName?.let { it1 -> showShortToast(it1) }
    }

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

Get visible items in RecyclerView

You can use recyclerView.getChildAt() to get each visible child, and setting some tag convertview.setTag(index) on these view in adapter code will help you to relate it with adapter data.

Regular expression for floating point numbers

what you need is:

[\-\+]?[0-9]*(\.[0-9]+)?

I escaped the "+" and "-" sign and also grouped the decimal with its following digits since something like "1." is not a valid number.

The changes will allow you to match integers and floats. for example:

0
+1
-2.0
2.23442

Using jquery to delete all elements with a given id

All your elements should have a unique IDs, so there should not be more than one element with #myid

An "id" is a unique identifier. Each time this attribute is used in a document it must have a different value. If you are using this attribute as a hook for style sheets it may be more appropriate to use classes (which group elements) than id (which are used to identify exactly one element).

Neverthless, try this:

$("span[id=myid]").remove();

Why can't I use background image and color together?

To tint an image, you can use CSS3 background to stack images and a linear-gradient. In the example below, I use a linear-gradient with no actual gradient. The browser treats gradients as images (I think it actually generates a bitmap and overlays it) and thus, is actually stacking multiple images.

background: linear-gradient(0deg, rgba(2,173,231,0.5), rgba(2,173,231,0.5)), url(images/mba-grid-5px-bg.png) repeat;

Will yield a graph-paper with light blue tint, if you had the png. Note that the stacking order might work in reverse to your mental model, with the first item being on top.

Excellent documentation by Mozilla, here:

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

Tool for building the gradients:

http://www.colorzilla.com/gradient-editor/

Note - doesn't work in IE11! I'll post an update when I find out why, since its supposed to.

TreeMap sort by value

In Java 8:

LinkedHashMap<Integer, String> sortedMap = 
    map.entrySet().stream().
    sorted(Entry.comparingByValue()).
    collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                             (e1, e2) -> e1, LinkedHashMap::new));

How to always show scrollbar

There are 2 ways:

  • from Java code: ScrollView.setScrollbarFadingEnabled(false);
  • from XML code: android:fadeScrollbars="false"

Simple as that!

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:

split -l 100000 database.sql database-

It will give files like:

database-aaa
database-aab
database-aac
...

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

Visual Studio: How to show Overloads in IntelliSense?

The default key binding for this is Ctrl+Shift+Space. The underlying Visual Studio command is Edit.ParameterInfo.

If the standard keybinding doesn't work for you (possible in some profiles) then you can change it via the keyboard options page

  • Tools -> Options
  • Keyboard
  • Type in Edit.ParameterInfo
  • Change the shortcut key
  • Hit Assign

TortoiseGit-git did not exit cleanly (exit code 1)

I was heard that, one of the reasons is , the project is too large, so increasing the post buffer could solve the problem. so open the editSystemWideGitConfig, and add the following statements under [http] , postBuffer = 524288000. maybe work.

Android RatingBar change star colors

From the API 21 on it's very easy to change the color of the stars with this three lines of code:

android:progressTint="@android:color/holo_red_dark"
android:progressBackgroundTint="@android:color/holo_red_dark"
android:secondaryProgressTint="@android:color/holo_red_dark" 

Doing it like this, you'll change:

  • the filled stars color (progressTint)
  • the unfilled stars color (progressBackgroundTint)
  • and the border color (secondaryProgressTint) of the stars

Change window location Jquery

Assuming you want to change the url to another within the same domain, you can use this:

history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');

Remove whitespaces inside a string in javascript

You can use Strings replace method with a regular expression.

"Hello World ".replace(/ /g, "");

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp

RegExp

  • / / - Regular expression matching spaces

  • g - Global flag; find all matches rather than stopping after the first match

_x000D_
_x000D_
const str = "H    e            l l       o  World! ".replace(/ /g, "");_x000D_
document.getElementById("greeting").innerText = str;
_x000D_
<p id="greeting"><p>
_x000D_
_x000D_
_x000D_

Only local connections are allowed Chrome and Selenium webdriver

This is just an informational message. Your issue might be a missmatch between the versions of chromedriver and selenium-server-standalone.

Try with the latest selenium version 3.0, it is working for me.

Please not that for selenium 3.0 you need to specify the driver first and after the selenium server.

With the new selenium, which is 3.0 you should use:

java -Dwebdriver.chrome.driver=path_to_chrome_driver -jar selenium-server-standalone-3.0.0-beta2.jar If you are using selenium version below 3.0 you need to reverse the order of selenium with the driver, like:

java -Dwebdriver.chrome.driver=path_to_chrome_driver -jar selenium_server.jar

When you are starting the selenium server, open a console in the directory with chromedriver and selenium server and execute the above command.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah and have to specify it every time or use another syntax/approach,

ECMAScript 6 class destructor

If there is no such mechanism, what is a pattern/convention for such problems?

The term 'cleanup' might be more appropriate, but will use 'destructor' to match OP

Suppose you write some javascript entirely with 'function's and 'var's. Then you can use the pattern of writing all the functions code within the framework of a try/catch/finally lattice. Within finally perform the destruction code.

Instead of the C++ style of writing object classes with unspecified lifetimes, and then specifying the lifetime by arbitrary scopes and the implicit call to ~() at scope end (~() is destructor in C++), in this javascript pattern the object is the function, the scope is exactly the function scope, and the destructor is the finally block.

If you are now thinking this pattern is inherently flawed because try/catch/finally doesn't encompass asynchronous execution which is essential to javascript, then you are correct. Fortunately, since 2018 the asynchronous programming helper object Promise has had a prototype function finally added to the already existing resolve and catch prototype functions. That means that that asynchronous scopes requiring destructors can be written with a Promise object, using finally as the destructor. Furthermore you can use try/catch/finally in an async function calling Promises with or without await, but must be aware that Promises called without await will be execute asynchronously outside the scope and so handle the desctructor code in a final then.

In the following code PromiseA and PromiseB are some legacy API level promises which don't have finally function arguments specified. PromiseC DOES have a finally argument defined.

async function afunc(a,b){
    try {
        function resolveB(r){ ... }
        function catchB(e){ ... }
        function cleanupB(){ ... }
        function resolveC(r){ ... }
        function catchC(e){ ... }
        function cleanupC(){ ... }
        ...
        // PromiseA preced by await sp will finish before finally block.  
        // If no rush then safe to handle PromiseA cleanup in finally block 
        var x = await PromiseA(a);
        // PromiseB,PromiseC not preceded by await - will execute asynchronously
        // so might finish after finally block so we must provide 
        // explicit cleanup (if necessary)
        PromiseB(b).then(resolveB,catchB).then(cleanupB,cleanupB);
        PromiseC(c).then(resolveC,catchC,cleanupC);
    }
    catch(e) { ... }
    finally { /* scope destructor/cleanup code here */ }
}

I am not advocating that every object in javascript be written as a function. Instead, consider the case where you have a scope identified which really 'wants' a destructor to be called at its end of life. Formulate that scope as a function object, using the pattern's finally block (or finally function in the case of an asynchronous scope) as the destructor. It is quite like likely that formulating that functional object obviated the need for a non-function class which would otherwise have been written - no extra code was required, aligning scope and class might even be cleaner.

Note: As others have written, we should not confuse destructors and garbage collection. As it happens C++ destructors are often or mainly concerned with manual garbage collection, but not exclusively so. Javascript has no need for manual garbage collection, but asynchronous scope end-of-life is often a place for (de)registering event listeners, etc..

ini_set("memory_limit") in PHP 5.3.3 is not working at all

If you have the suhosin extension enabled, it can prevent scripts from setting the memory limit beyond what it started with or some defined cap.

http://www.hardened-php.net/suhosin/configuration.html#suhosin.memory_limit

Difference between Static and final?

static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.

public class MyClass {
    public static int myVariable = 0; 
}

//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances

MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();

MyClass.myVariable = 5;  //This change is reflected in both instances

final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.

note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.

Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.

public class MyClass {

    public static List<String> cars = new ArrayList<String>();

    static {
        cars.add("Ferrari");
        cars.add("Scoda");
    }

}

public class TestClass {

    public static void main(String args[]) {
        System.out.println(MyClass.cars.get(0));  //This will print Ferrari
    }
}

You must not get this confused with instance initializer blocks which are called before the constructor per instance.

Confirm Password with jQuery Validate

Just a quick chime in here to hopefully help others... Especially with the newer version (since this is 2 years old)...

Instead of having some static fields defined in JS, you can also use the data-rule-* attributes. You can use built-in rules as well as custom rules.

See http://jqueryvalidation.org/documentation/#link-list-of-built-in-validation-methods for built-in rules.

Example:

<p><label>Email: <input type="text" name="email" id="email" data-rule-email="true" required></label></p>
<p><label>Confirm Email: <input type="text" name="email" id="email_confirm" data-rule-email="true" data-rule-equalTo="#email" required></label></p>

Note the data-rule-* attributes.

Google reCAPTCHA: How to get user response and validate in the server side?

A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.

Check the success field for true or false

private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
    JsonObject jsonObject = null;
    URLConnection connection = null;
    InputStream is = null;
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();

    String url = "https://www.google.com/recaptcha/api/siteverify";
    try {            
        String query = String.format("secret=%s&response=%s&remoteip=%s", 
        URLEncoder.encode(secret, charset), 
        URLEncoder.encode(response, charset),
        URLEncoder.encode(remoteip, charset));

        connection = new URL(url + "?" + query).openConnection();
        is = connection.getInputStream();
        JsonReader rdr = Json.createReader(is);
        jsonObject = rdr.readObject();

    } catch (IOException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }

        }
    }
    return jsonObject;
}

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

Cannot create PoolableConnectionFactory

This is the actual cause of the problem:

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

You have a database communication link problem. Make sure that your application have network access to your database (and the firewall isn't blocking ports to your database).

Detach (move) subdirectory into separate Git repository

Update: This process is so common, that the git team made it much simpler with a new tool, git subtree. See here: Detach (move) subdirectory into separate Git repository


You want to clone your repository and then use git filter-branch to mark everything but the subdirectory you want in your new repo to be garbage-collected.

  1. To clone your local repository:

    git clone /XYZ /ABC
    

    (Note: the repository will be cloned using hard-links, but that is not a problem since the hard-linked files will not be modified in themselves - new ones will be created.)

  2. Now, let us preserve the interesting branches which we want to rewrite as well, and then remove the origin to avoid pushing there and to make sure that old commits will not be referenced by the origin:

    cd /ABC
    for i in branch1 br2 br3; do git branch -t $i origin/$i; done
    git remote rm origin
    

    or for all remote branches:

    cd /ABC
    for i in $(git branch -r | sed "s/.*origin\///"); do git branch -t $i origin/$i; done
    git remote rm origin
    
  3. Now you might want to also remove tags which have no relation with the subproject; you can also do that later, but you might need to prune your repo again. I did not do so and got a WARNING: Ref 'refs/tags/v0.1' is unchanged for all tags (since they were all unrelated to the subproject); additionally, after removing such tags more space will be reclaimed. Apparently git filter-branch should be able to rewrite other tags, but I could not verify this. If you want to remove all tags, use git tag -l | xargs git tag -d.

  4. Then use filter-branch and reset to exclude the other files, so they can be pruned. Let's also add --tag-name-filter cat --prune-empty to remove empty commits and to rewrite tags (note that this will have to strip their signature):

    git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC -- --all
    

    or alternatively, to only rewrite the HEAD branch and ignore tags and other branches:

    git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC HEAD
    
  5. Then delete the backup reflogs so the space can be truly reclaimed (although now the operation is destructive)

    git reset --hard
    git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
    git reflog expire --expire=now --all
    git gc --aggressive --prune=now
    

    and now you have a local git repository of the ABC sub-directory with all its history preserved.

Note: For most uses, git filter-branch should indeed have the added parameter -- --all. Yes that's really --space-- all. This needs to be the last parameters for the command. As Matli discovered, this keeps the project branches and tags included in the new repo.

Edit: various suggestions from comments below were incorporated to make sure, for instance, that the repository is actually shrunk (which was not always the case before).

Node: log in a file instead of the console

Update 2013 - This was written around Node v0.2 and v0.4; There are much better utilites now around logging. I highly recommend Winston

Update Late 2013 - We still use winston, but now with a logger library to wrap the functionality around logging of custom objects and formatting. Here is a sample of our logger.js https://gist.github.com/rtgibbons/7354879


Should be as simple as this.

var access = fs.createWriteStream(dir + '/node.access.log', { flags: 'a' })
      , error = fs.createWriteStream(dir + '/node.error.log', { flags: 'a' });

// redirect stdout / stderr
proc.stdout.pipe(access);
proc.stderr.pipe(error);

How to kill an application with all its activities?

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "LoginActivity".

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.

    if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }

The answer you get to this question from the Android platform is: "Don't make an exit button. Finish activities the user no longer wants, and the Activity manager will clean them up as it sees fit."

_DEBUG vs NDEBUG

Unfortunately DEBUG is overloaded heavily. For instance, it's recommended to always generate and save a pdb file for RELEASE builds. Which means one of the -Zx flags, and -DEBUG linker option. While _DEBUG relates to special debug versions of runtime library such as calls to malloc and free. Then NDEBUG will disable assertions.

The following untracked working tree files would be overwritten by merge, but I don't care

If you have the files written under .gitignore, remove the files and run git pull again. That helped me out.

Gerrit error when Change-Id in commit messages are missing

under my .git/hooks folder, some sample files were missing. like commit-msg,post-commit.sample,post-update.sample...adding these files resolved my change id missing issue.

How to split a string with angularJS

Thx guys, I finally found the solution, a really basic one.. In my controller I have

$scope.mySplit = function(string, nb) {
    var array = string.split(',');
    return array[nb];
}

and in my view

{{mySplit(string,0)}}

Changing capitalization of filenames in Git

Set ignorecase to false in git config

As the original post is about "Changing capitalization of filenames in Git":

If you are trying to change capitalisation of a filename in your project, you do not need to force rename it from Git. IMO, I would rather change the capitalisation from my IDE/editor and make sure that I configure Git properly to pick up the renaming.

By default, a Git template is set to ignore case (Git case insensitive). To verify you have the default template, use --get to retrieve the value for a specified key. Use --local and --global to indicate to Git whether to pick up a configuration key-value from your local Git repository configuration or global one. As an example, if you want to lookup your global key core.ignorecase:

git config --global --get core.ignorecase

If this returns true, make sure to set it as:

git config --global core.ignorecase false

(Make sure you have proper permissions to change global.) And there you have it; now your Git installation would not ignore capitalisations and treat them as changes.

As a suggestion, if you are working on multi-language projects and you feel not all projects should be treated as case-sensitive by Git, just update the local core.ignorecase file.