Programs & Examples On #Scriptom

Scriptom is a java library for scripting COM objects

How to determine previous page URL in Angular?

Using pairwise from rxjx you can achieve this easier. import { filter,pairwise } from 'rxjs/operators';

previousUrl: string;
constructor(router: Router) {
router.events
  .pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
  .subscribe((events: RoutesRecognized[]) => {
  console.log('previous url', events[0].urlAfterRedirects);
  console.log('current url', events[1].urlAfterRedirects);
  this.previousUrl = events[0].urlAfterRedirects;
});

}

SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

The server certificate is invalid, either because it is signed by an invalid CA (internal CA, self signed,...), doesn't match the server's name or because it is expired.

Either way, you need to find how to tell to the Python library that you are using that it must not stop at an invalid certificate if you really want to download files from this server.

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

What is the difference between "mvn deploy" to a local repo and "mvn install"?

From the Maven docs, sounds like it's just a difference in which repository you install the package into:

  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Maybe there is some confusion in that "install" to the CI server installs it to it's local repository, which then you as a user are sharing?

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

nodeJs callbacks simple example

Try this example as simple as you can read, just copy save newfile.js do node newfile to run the application.

function myNew(next){
    console.log("Im the one who initates callback");
    next("nope", "success");
}


myNew(function(err, res){
    console.log("I got back from callback",err, res);
});

Java: Integer equals vs. ==

As well for correctness of using == you can just unbox one of compared Integer values before doing == comparison, like:

if ( firstInteger.intValue() == secondInteger ) {..

The second will be auto unboxed (of course you have to check for nulls first).

How to view DLL functions?

Use dumpbin command-line.

  • dumpbin /IMPORTS <path-to-file> should provide the function imported into that DLL.
  • dumpbin /EXPORTS <path-to-file> should provide the functions it exports.

Scale iFrame css width 100% like an image

None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.

CSS

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
  padding-top: 75%;
}

HTML

<div class="iframe-container">
  <iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>

java create date object using a value string

What you're basically trying to do is this:-

Calendar cal = Calendar.getInstance();
Date date = cal.getTime();

The reason being, the String which you're printing is just a String representation of the Date in your required format. If you try to convert it to date, you'll eventually end up doing what I've mentioned above.

Formatting Date(cal.getTime()) to a String and trying to get back a Date from it - makes no sense. Date has no format as such. You can only get a String representation of that using the SDF.

Fatal Error :1:1: Content is not allowed in prolog

There are certainly some weird characters (e.g. BOM) or some whitespace before the XML preamble (<?xml ...?>)?

Does IE9 support console.log, and is it a real function?

console.log is only defined when the console is open. If you want to check for it in your code make sure you check for for it within the window property

if (window.console)
    console.log(msg)

this throws an exception in IE9 and will not work correctly. Do not do this

if (console) 
    console.log(msg)

Why does ANT tell me that JAVA_HOME is wrong when it is not?

The semicolon was throwing me off: I had JAVA_HOME set to "C:\jdk1.6.0_26;" instead of "C:\jdk1.6.0_26". I removed the trailing semicolon after following Jon Skeet's suggestion to examine the ant.bat file. This is part of that file:

if "%JAVA_HOME%" == "" goto noJavaHome
if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome

So the semi-colon wasn't being trimmed off the end, causing this to fail to find the file, therefore defaulting to "C:\Java\jre6" or something like that.

The confusing part is that the HowtoBuild page states to use the semi-colon, but that seems to break it.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

What is the difference between 'git pull' and 'git fetch'?

Git obtains the branch of the latest version from the remote to the local using two commands:

  1. git fetch: Git is going to get the latest version from remote to local, but it do not automatically merge.      git fetch origin master git log -p master..origin/master git merge origin/master

         The commands above mean that download latest version of the main branch from origin from the remote to origin master branch. And then compares the local master branch and origin master branch. Finally, merge.

  2. git pull: Git is going to get the latest version from the remote and merge into the local.

        git pull origin master

         The command above is the equivalent to git fetch and git merge. In practice, git fetch maybe more secure because before the merge we can see the changes and decide whether to merge.

Fastest way to serialize and deserialize .NET objects

The binary serializer included with .net should be faster that the XmlSerializer. Or another serializer for protobuf, json, ...

But for some of them you need to add Attributes, or some other way to add metadata. For example ProtoBuf uses numeric property IDs internally, and the mapping needs to be somehow conserved by a different mechanism. Versioning isn't trivial with any serializer.

Current date and time - Default in MVC razor

Isn't this what default constructors are for?

class MyModel
{

    public MyModel()
    {
        this.ReturnDate = DateTime.Now;
    }

    public date ReturnDate {get; set;};

}

Check/Uncheck all the checkboxes in a table

$(document).ready(function () {

            var someObj = {};

            $("#checkAll").click(function () {
                $('.chk').prop('checked', this.checked);
            });

            $(".chk").click(function () {

                $("#checkAll").prop('checked', ($('.chk:checked').length == $('.chk').length) ? true : false);
            });

            $("input:checkbox").change(function () {
                debugger;

                someObj.elementChecked = [];

                $("input:checkbox").each(function () {
                    if ($(this).is(":checked")) {
                        someObj.elementChecked.push($(this).attr("id"));

                    }

                });             
            });

            $("#button").click(function () {
                debugger;

                alert(someObj.elementChecked);

            });

        });
    </script>
</head>

<body>

    <ul class="chkAry">
        <li><input type="checkbox" id="checkAll" />Select All</li>

        <li><input class="chk" type="checkbox" id="Delhi">Delhi</li>

        <li><input class="chk" type="checkbox" id="Pune">Pune</li>

        <li><input class="chk" type="checkbox" id="Goa">Goa</li>

        <li><input class="chk" type="checkbox" id="Haryana">Haryana</li>

        <li><input class="chk" type="checkbox" id="Mohali">Mohali</li>

    </ul>
    <input type="button" id="button" value="Get" />

</body>

CSS fixed width in a span

Well, there's always the brute force method:

<li><pre>    The lazy dog.</pre></li>
<li><pre>AND The lazy cat.</pre></li>
<li><pre>OR  The active goldfish.</pre></li>

Or is that what you meant by "padding" the text? That's an ambiguous work in this context.

This sounds kind of like a homework question. I hope you're not trying to get us to do your homework for you?

How can I compile my Perl script so it can be executed on systems without perl installed?

On MaxOSX there may be perlcc. Type man perlcc. On my system (10.6.8) it's in /usr/bin. YMMV

See http://search.cpan.org/~nwclark/perl-5.8.9/utils/perlcc.PL

Identifying country by IP address

Yes, countries have specific IP address ranges as you mentioned.

For example, Australia is between 16777216 - 16777471. China is between 16777472 - 16778239. But one country may have multiple ranges. For example, Australia also has this range between 16778240 - 16779263

(These are numerical conversions of IP addresses. It depends whether you use IPv4 or IPv6)

More information about these ranges can be seen here: http://software77.net/cidr-101.html

We get the ip addresses of our website visitors and sometimes want to make relevant campaign for a specific country. We were using bulk conversion tools but later on decided to define the rules in an Excel file and convert it in the tool. And we have built this Excel template: https://www.someka.net/excel-template/ip-to-country-converter/

Now we use this for our own needs and also sell it. I don't want it to be a sales pitch but for those who are looking for an easy solution can benefit from this.

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))

How to generate classes from wsdl using Maven and wsimport?

Try to wrap wsdlLocation in wsdlUrls

            <wsdlUrls>
                <wsdlLocation>http://url</wsdlLocation>
            </wsdlUrls>

How do I find a list of Homebrew's installable packages?

Please use Homebrew Formulae page to see the list of installable packages. https://formulae.brew.sh/formula/

To install any package => command to use is :

brew install node

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

For me it was "Prefer 32bit": clearing the checkbox allowed CLR to load Crystal Reports 64bit runtime (the only one installed).

Hide axis and gridlines Highcharts

Just add

xAxis: {
   ...  
   lineWidth: 0,
   minorGridLineWidth: 0,
   lineColor: 'transparent',
   ...          
   labels: {
       enabled: false
   },
   minorTickLength: 0,
   tickLength: 0
}

to the xAxis definition.

Since Version 4.1.9 you can simply use the axis attribute visible:

xAxis: {
    visible: false,
}

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

pandas read_csv and filter columns with usecols

The solution lies in understanding these two keyword arguments:

  • names is only necessary when there is no header row in your file and you want to specify other arguments (such as usecols) using column names rather than integer indices.
  • usecols is supposed to provide a filter before reading the whole DataFrame into memory; if used properly, there should never be a need to delete columns after reading.

So because you have a header row, passing header=0 is sufficient and additionally passing names appears to be confusing pd.read_csv.

Removing names from the second call gives the desired output:

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        header=0,
        index_col=["date", "loc"], 
        usecols=["date", "loc", "x"],
        parse_dates=["date"])

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

Python:Efficient way to check if dictionary is empty or not

I just wanted to know if the dictionary i was going to try to pull data from had data in it in the first place, this seems to be simplest way.

d = {}

bool(d)

#should return
False

d = {'hello':'world'}

bool(d)

#should return
True

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I am not sure if this helps but I had the same problem.

You are using springSecurityFilterChain with CSRF protection. That means you have to send a token when you send a form via POST request. Try to add the next input to your form:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

When do we need curly braces around shell variables?

Variables are declared and assigned without $ and without {}. You have to use

var=10

to assign. In order to read from the variable (in other words, 'expand' the variable), you must use $.

$var      # use the variable
${var}    # same as above
${var}bar # expand var, and append "bar" too
$varbar   # same as ${varbar}, i.e expand a variable called varbar, if it exists.

This has confused me sometimes - in other languages we refer to the variable in the same way, regardless of whether it's on the left or right of an assignment. But shell-scripting is different, $var=10 doesn't do what you might think it does!

What's the best UI for entering date of birth?

I would suggest using a drop down menu for each field, making sure to label each as day, month and year. A date picker might also help, but if the user doesn't have JavaScript enabled, it won't work.

How can you have SharePoint Link Lists default to opening in a new window?

It is not possible with the default Link List web part, but there are resources describing how to extend Sharepoint server-side to add this functionality.

Share Point Links Open in New Window
Changing Link Lists in Sharepoint 2007

Passing an array using an HTML form hidden element

You can do it like this:

<input type="hidden" name="result" value="<?php foreach($postvalue as $value) echo $postvalue.","; ?>">

Fatal error: Call to undefined function sqlsrv_connect()

i have same this because in httpd.conf in apache PHPIniDir D:/wamp/bin/php/php5.5.12 that was incorrect

How to concatenate characters in java?

You can use the String constructor.

System.out.println(new String(new char[]{a,b,c}));

Find and replace in file and overwrite file doesn't work, it empties the file

The problem with the command

sed 'code' file > file

is that file is truncated by the shell before sed actually gets to process it. As a result, you get an empty file.

The sed way to do this is to use -i to edit in place, as other answers suggested. However, this is not always what you want. -i will create a temporary file that will then be used to replace the original file. This is problematic if your original file was a link (the link will be replaced by a regular file). If you need to preserve links, you can use a temporary variable to store the output of sed before writing it back to the file, like this:

tmp=$(sed 'code' file); echo -n "$tmp" > file

Better yet, use printf instead of echo since echo is likely to process \\ as \ in some shells (e.g. dash):

tmp=$(sed 'code' file); printf "%s" "$tmp" > file

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

HTML5 form validation pattern alphanumeric with spaces?

How about adding a space in the pattern attribute like pattern="[a-zA-Z0-9 ]+". If you want to support any kind of space try pattern="[a-zA-Z0-9\s]+"

How to check whether a str(variable) is empty or not?

Just say if s or if not s. As in

s = ''
if not s:
    print 'not', s

So in your specific example, if I understand it correctly...

>>> import random
>>> l = ['', 'foo', '', 'bar']
>>> def default_str(l):
...     s = random.choice(l)
...     if not s:
...         print 'default'
...     else:
...         print s
... 
>>> default_str(l)
default
>>> default_str(l)
default
>>> default_str(l)
bar
>>> default_str(l)
default

Regex how to match an optional character

You can make the single letter optional by adding a ? after it as:

([A-Z]{1}?)

The quantifier {1} is redundant so you can drop it.

Is there a way to SELECT and UPDATE rows at the same time?

I have faced the same issue; I have to update the credit amount, and have to get modified time, along with credit details from DB. It is basically

SYNCHRONOUSLY/ATOMICALLY perform (UPDATE then GET) in MYSQL

I have tried many options and found one that solved my issue.

1) OPTION_1 SELECT FOR UPDATE

This is maintaining the lock till update (SYNC from GET to UPDATE), but i need lock after update till the GET.

2) OPTION_2 Stored procedure

Stored procedure will not execute synchronously like redis lua, So there also we need sync code to perform that.

3) OPTION_3 Transaction

I have used JPA entityManager like below, thought that before commit no one can update, and before commit i will get the updated object along with modified time (from DB). But i didn't get the latest object. Only commit i got the latest.

    try {
        entityManager.getTransaction().begin();
        //entityManager.persist(object);
        int upsert = entityManager.createNativeQuery(
        "update com.bill.Credit c set c.balance = c.balance - ?1
          where c.accountId = ?2 and c.balance >= ?1").executeUpdate(); 
             //c.balance >= ? for limit check
        Credit newCredit = entityManager.find(Credit.class, "id");
        entityManager.refresh(newCredit); //SHOULD GET LATEST BUT NOT
        entityManager.getTransaction().commit();
    } finally {     
        entityManager.unwrap(Session.class).close();
    } 

4) OPTION_4 LOCK solved the issue, so before update i acquired the lock; then after GET i have released the lock.

private Object getLock(final EntityManager entityManager, final String Id){

    entityManager.getTransaction().begin();
    Object obj_acquire = entityManager.createNativeQuery("SELECT GET_LOCK('" + Id + "', 10)").getSingleResult();
    entityManager.getTransaction().commit();
    return obj_acquire;
}


private Object releaseLock(final EntityManager entityManager, final String Id){

    entityManager.getTransaction().begin();
    Object obj_release = entityManager.createNativeQuery("SELECT RELEASE_LOCK('" + Id + "')").getSingleResult();
    entityManager.getTransaction().commit();
    return obj_release;
}

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

using extern template (C++11)

If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.

Example on ToggleButton

I think what are attempting is semantically same as a radio button when 1 is when one of the options is selected and 0 is the other option.

I suggest using the radio button provided by Android by default.

Here is how to use it- http://www.mkyong.com/android/android-radio-buttons-example/

and the android documentation is here-

http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Thanks.

change cursor to finger pointer

Add an href attribute to make it a valid link & return false; in the event handler to prevent it from causing a navigation;

<a href="#" class="menu_links" onclick="displayData(11,1,0,'A'); return false;" onmouseover=""> A </a>

(Or make displayData() return false and ..="return displayData(..)

Display PDF within web browser

We render the PDF file pages as PNG files on the server using JPedal (a java library). That, combined with some javascript, gives us high control over visualization and navigation.

Can’t delete docker image with dependent child images

Image Layer: Repositories are often referred to as images or container images, but actually they are made up of one or more layers. Image layers in a repository are connected together in a parent-child relationship. Each image layer represents changes between itself and the parent layer.

The docker building pattern uses inheritance. It means the version i depends on version i-1. So, we must delete the version i+1 to be able to delete version i. This is a simple dependency.

If you wanna delete all images except the last one (the most updated) and the first (base) then we can export the last (the most updated one) using docker save command as below.

docker save -o <output_file> <your_image-id> | gzip <output_file>.tgz

Then, now, delete all the images using image-id as below.

docker rm -f <image-id i> | docker rm -f <image i-1> | docker rm -f <image-id i-2> ... <docker rm -f <image-id i-k> # where i-k = 1

Now, load your saved tgz image as below.

gzip -c <output_file.tgz> | docker load

see the image-id of your loaded image using docker ps -q. It doesn't have tag and name. You can simply update tag and name as done below.

docker tag <image_id> group_name/name:tag

Combine :after with :hover

 #alertlist li:hover:after,#alertlist li.selected:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}?

jsFiddle Link

How to apply filters to *ngFor?

This is my code:

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

@Pipe({
    name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
    transform(items: any[], field : string, value): any[] {
      if (!items) return [];
      if (!value || value.length === 0) return items;
      return items.filter(it =>
      it[field] === value);
    }
}

Sample:

LIST = [{id:1,name:'abc'},{id:2,name:'cba'}];
FilterValue = 1;

<span *ngFor="let listItem of LIST | filter : 'id' : FilterValue">
                              {{listItem .name}}
                          </span>

How do I create a simple Qt console application in C++?

You could fire an event into the quit() slot of your application even without connect(). This way, the event-loop does at least one turn and should process the events within your main()-logic:

#include <QCoreApplication>
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication app( argc, argv );

    // do your thing, once

    QTimer::singleShot( 0, &app, &QCoreApplication::quit );
    return app.exec();
}

Don't forget to place CONFIG += console in your .pro-file, or set consoleApplication: true in your .qbs Project.CppApplication.

Get clicked item and its position in RecyclerView

Here is an Example to set a Click Listener.

Adapter extends  RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {  ...  }

 public static class MessageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView     tv_msg;
        public TextView     tv_date;
        public TextView     tv_sendTime;
        public ImageView    sharedFile;
        public ProgressBar sendingProgressBar;

        public MessageViewHolder(View v) {
            super(v);
            tv_msg =  (TextView) v.findViewById(R.id.tv_msg);
            tv_date = (TextView)  v.findViewById(R.id.tv_date);
            tv_sendTime = (TextView)  v.findViewById(R.id.tv_sendTime);
            sendingProgressBar = (ProgressBar) v.findViewById(R.id.sendingProgressBar);
            sharedFile = (ImageView) v.findViewById(R.id.sharedFile);

            sharedFile.setOnClickListener(this);

        }

        @Override
        public void onClick(View view) {
        int position  =   getAdapterPosition();


            switch (view.getId()){
                case R.id.sharedFile:


                    Log.w("", "Selected"+position);


                    break;
            }
        }

    }

remove double quotes from Json return data using Jquery

You can simple try String(); to remove the quotes.

Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp

Thank me later.

PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.

Why is there no tuple comprehension in Python?

I believe it's simply for the sake of clarity, we do not want to clutter the language with too many different symbols. Also a tuple comprehension is never necessary, a list can just be used instead with negligible speed differences, unlike a dict comprehension as opposed to a list comprehension.

RegEx for Javascript to allow only alphanumeric

Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$:

^\w+$

Explanation:

  • ^ start of string
  • \w any word character (A-Z, a-z, 0-9, _).
  • $ end of string

Use /[^\w]|_/g if you don't want to match the underscore.

excel - if cell is not blank, then do IF statement

Your formula is wrong. You probably meant something like:

=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Another equivalent:

=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Or even shorter:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))

OR EVEN SHORTER:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

I got the same error, I'm using laravel 5.4 with webpack, here package.json before:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    ...
    ...
  },
  "dependencies": {
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I had to move jquery and datatables.net npm packages under one of these "dependencies": {} or "devDependencies": {} in package.json and the error disappeared, after:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I hope that helps!

What's the difference between %s and %d in Python string formatting?

They are format specifiers. They are used when you want to include the value of your Python expressions into strings, with a specific format enforced.

See Dive into Python for a relatively detailed introduction.

TCP: can two different sockets share a port?

No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.

JSON serialization/deserialization in ASP.Net Core

You can use Newtonsoft.Json, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding which is a dependency of Microsoft.AspNet.Mvc. So, you don't need to add a dependency in your project.json.

#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);

Note, using a WebAPI controller you don't need to deal with JSON.

UPDATE ASP.Net Core 3.0

Json.NET has been removed from the ASP.NET Core 3.0 shared framework.

You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader and Utf8JsonWriter. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.

To get started, use the JsonSerializer class in the System.Text.Json.Serialization namespace. See the documentation for information and samples.

To use Json.NET in an ASP.NET Core 3.0 project:

    services.AddMvc()
        .AddNewtonsoftJson();

Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

How to loop through array in jQuery?

Use the each() function of jQuery.

Here is an example:

$.each(currnt_image_list.split(','), function(index, value) { 
  alert(index + ': ' + value); 
});

How can I take a screenshot with Selenium WebDriver?

Java (Robot Framework)

I used this method for taking a screenshot.

void takeScreenShotMethod(){
    try{
        Thread.sleep(10000)
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "jpg", new File("./target/surefire-reports/screenshot.jpg"));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

You may use this method wherever required.

What are the differences between .gitignore and .gitkeep?

.gitkeep is just a placeholder. A dummy file, so Git will not forget about the directory, since Git tracks only files.


If you want an empty directory and make sure it stays 'clean' for Git, create a .gitignore containing the following lines within:

# .gitignore sample
###################

# Ignore all files in this dir...
*

# ... except for this one.
!.gitignore

If you desire to have only one type of files being visible to Git, here is an example how to filter everything out, except .gitignore and all .txt files:

# .gitignore to keep just .txt files
###################################

# Filter everything...
*

# ... except the .gitignore...
!.gitignore

# ... and all text files.
!*.txt

('#' indicates comments.)

<code> vs <pre> vs <samp> for inline and block code snippets

This works for me to display code in frontend:

<style>
.content{
    height:50vh;
    width: 100%;
    background: transparent;
    border: none;
    border-radius: 0;
    resize: none;
    outline: none;
}
.content:focus{
    border: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
}
</style>

<textarea class="content">
<div>my div</div><p>my paragraph</p>
</textarea>

View Live Demo: https://jsfiddle.net/bytxj50e/

Recursively list all files in a directory including files in symlink directories

The -L option to ls will accomplish what you want. It dereferences symbolic links.

So your command would be:

ls -LR

You can also accomplish this with

find -follow

The -follow option directs find to follow symbolic links to directories.

On Mac OS X use

find -L

as -follow has been deprecated.

How to get values and keys from HashMap?

You have to follow the following sequence of opeartions:

  • Convert Map to MapSet with map.entrySet();
  • Get the iterator with Mapset.iterator();
  • Get Map.Entry with iterator.next();
  • use Entry.getKey() and Entry.getValue()
# define Map
for (Map.Entry entry: map.entrySet)
    System.out.println(entry.getKey() + entry.getValue);

Make a UIButton programmatically in Swift

Swift 5.0

        let button = self.makeButton(title: "Login", titleColor: .blue, font: UIFont.init(name: "Arial", size: 18.0), background: .white, cornerRadius: 3.0, borderWidth: 2, borderColor: .black)
        view.addSubview(button)
        // Adding Constraints
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true
        button.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
        button.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
        button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -400).isActive = true
        button.addTarget(self, action: #selector(pressed(_ :)), for: .touchUpInside)

       // Define commmon method
        func makeButton(title: String? = nil,
                           titleColor: UIColor = .black,
                           font: UIFont? = nil,
                           background: UIColor = .clear,
                           cornerRadius: CGFloat = 0,
                           borderWidth: CGFloat = 0,
                           borderColor: UIColor = .clear) -> UIButton {
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(title, for: .normal)
        button.backgroundColor = background
        button.setTitleColor(titleColor, for: .normal)
        button.titleLabel?.font = font
        button.layer.cornerRadius = 6.0
        button.layer.borderWidth = 2
        button.layer.borderColor = UIColor.red.cgColor
        return button
      }
        // Button Action
         @objc func pressed(_ sender: UIButton) {
                print("Pressed")
          }

enter image description here

Java Minimum and Maximum values in Array

Yes you need to use a System.out.println. But you are getting the minimum and maximum everytime they input a value and don't keep track of the number of elements if they break early.

Try:

for (int i = 0 ; i < array.length; i++ ) {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
           break;

       array[i] = next;
 }
 int length = i;
 // get biggest number
 int large = getMaxValue(array, length);
 // get smallest number
 int small = getMinValue(array, length);

 // actually print
 System.out.println( "Max: " + large + " Min: " + small );

Then you will have to pass length into the methods to determine min and max and to print. If you don't do this, the rest of the fields will be 0 and can mess up the proper min and max values.

Java Try and Catch IOException Problem

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }

   if(lines > 0) {
     // Do rest of program.
   }
}

Warning: comparison with string literals results in unspecified behaviour

I ran across this issue today working with a clients program. The program works FINE in VS6.0 using the following: (I've changed it slightly)

//
// This is the one include file that every user-written Nextest programs needs.
// Patcom-generated files will also look for this file.
//
#include "stdio.h"
#define IS_NONE( a_key )   ( ( a_key == "none" || a_key == "N/A" ) ? TRUE : FALSE )

//
// Note in my environment we have output() which is printf which adds /n at the end
//
main {
    char *psNameNone = "none";
    char *psNameNA   = "N/A";
    char *psNameCAT  = "CAT";

    if (IS_NONE(psNameNone) ) {
        output("psNameNone Matches NONE");
        output("%s psNameNoneAddr 0x%x  \"none\" addr 0x%X",
            psNameNone,psNameNone,
            "none");
    } else {
        output("psNameNone Does Not Match None");
        output("%s psNameNoneAddr 0x%x  \"none\" addr 0x%X",
            psNameNone,psNameNone,
            "none");
    }

    if (IS_NONE(psNameNA) ) {
        output("psNameNA Matches N/A");
        output("%s psNameNA 0x%x  \"N/A\" addr 0x%X",
        psNameNA,psNameNA,
        "N/A");
    } else {
        output("psNameNone Does Not Match N/A");
        output("%s psNameNA 0x%x  \"N/A\" addr 0x%X",
        psNameNA,psNameNA,
        "N/A");
    }
    if (IS_NONE(psNameCAT)) {
        output("psNameNA Matches CAT");
        output("%s psNameNA 0x%x  \"CAT\" addr 0x%X",
        psNameNone,psNameNone,
        "CAT");
    } else {
        output("psNameNA does not match CAT");
        output("%s psNameNA 0x%x  \"CAT\" addr 0x%X",
        psNameNone,psNameNone,
        "CAT");
    }
}

If built in VS6.0 with Program Database with Edit and Continue. The compares APPEAR to work. With this setting STRING pooling is enabled, and the compiler optimizes all STRING pointers to POINT TO THE SAME ADDRESSS, so this can work. Any strings created on the fly after compile time will have DIFFERENT addresses so will fail the compare. Where Compiler settings are Changing the setting to Program Database only will build the program so that it will fail.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

How to set HTML Auto Indent format on Sublime Text 3?

This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.

My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.

Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

Executing another application from Java

I know this is an older thread, but I figure it might be worthwhile for me to put in my implementation since I found this thread trying to do the same thing as OP, except with Root level access, but didn't really find a solution I was looking for. The below method creates a static Root level shell that is used for just executing commands without regard to error checking or even if the command executed successfully.

I use it an Android flashlight app I've created that allows setting the LED to different level of brightness. By removing all the error checking and other fluff I can get the LED to switch to a specified brightness level in as little as 3ms, which opens the door to LightTones (RingTones with light). More details on the app itself can be found here: http://forum.xda-developers.com/showthread.php?t=2659842

Below is the class in its entirety.

public class Shell {
    private static Shell rootShell = null;
    private final Process proc;
    private final OutputStreamWriter writer;

    private Shell(String cmd) throws IOException {
        this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
    }

    public void cmd(String command)  {
        try {
            writer.write(command+'\n');
            writer.flush();
        } catch (IOException e) {   }
    }

    public void close() {
        try {
            if (writer != null) {  writer.close();
                if(proc != null) {  proc.destroy();    }
            }
        } catch (IOException ignore) {}
    }

    public static void exec(String command) {   Shell.get().cmd(command);   }

    public static Shell get() {
        if (Shell.rootShell == null) {
            while (Shell.rootShell == null) {
                try {   Shell.rootShell = new Shell("su"); //Open with Root Privileges 
                } catch (IOException e) {   }
            }
        } 
        return Shell.rootShell;
    }
}

Then anywhere in my app to run a command, for instance changing the LED brightness, I just call:

Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);

What should my Objective-C singleton look like?

Just wanted to leave this here so I don't lose it. The advantage to this one is that it's usable in InterfaceBuilder, which is a HUGE advantage. This is taken from another question that I asked:

static Server *instance;

+ (Server *)instance { return instance; }

+ (id)hiddenAlloc
{
    return [super alloc];
}

+ (id)alloc
{
    return [[self instance] retain];
}


+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        instance = [[Server hiddenAlloc] init];
    }
}

- (id) init
{
    if (instance)
        return self;
    self = [super init];
    if (self != nil) {
        // whatever
    }
    return self;
}

How to find cube root using Python?

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

def is_perfect_cube(x):
    x = abs(x)
    return int(round(x ** (1. / 3))) ** 3 == x

print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
                                   # handles this correctly

This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

I was parsing JSON from a REST API call and got this error. It turns out the API had become "fussier" (eg about order of parameters etc) and so was returning malformed results. Check that you are getting what you expect :)

Should I make HTML Anchors with 'name' or 'id'?

The second sample assigns a unique ID to the element in question. This element can then be manipulated or accessed using DHTML.

The first one, on the other hand, sets a named location within the document, akin to a bookmark. Attached to an "anchor", it makes perfect sense.

How can I include css files using node, express, and ejs?

Use this in your server.js file

app.use(express.static(__dirname + '/public'));

and add css like

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

dont need / before css like

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

Spark read file from S3 using sc.textFile ("s3n://...)

Despite that this question has already an accepted answer, I think that the exact details of why this is happening are still missing. So I think there might be a place for one more answer.

If you add the required hadoop-aws dependency, your code should work.

Starting Hadoop 2.6.0, s3 FS connector has been moved to a separate library called hadoop-aws. There is also a Jira for that: Move s3-related FS connector code to hadoop-aws.

This means that any version of spark, that has been built against Hadoop 2.6.0 or newer will have to use another external dependency to be able to connect to the S3 File System.
Here is an sbt example that I have tried and is working as expected using Apache Spark 1.6.2 built against Hadoop 2.6.0:

libraryDependencies += "org.apache.hadoop" % "hadoop-aws" % "2.6.0"

In my case, I encountered some dependencies issues, so I resolved by adding exclusion:

libraryDependencies += "org.apache.hadoop" % "hadoop-aws" % "2.6.0" exclude("tomcat", "jasper-compiler") excludeAll ExclusionRule(organization = "javax.servlet")

On other related note, I have yet to try it, but that it is recommended to use "s3a" and not "s3n" filesystem starting Hadoop 2.6.0.

The third generation, s3a: filesystem. Designed to be a switch in replacement for s3n:, this filesystem binding supports larger files and promises higher performance.

Android View shadow

I'm using Android Studio 0.8.6 and I couldn't find:

android:background="@drawable/abc_menu_dropdown_panel_holo_light"

so I found this instead:

android:background="@android:drawable/dialog_holo_light_frame"

and it looks like this:

enter image description here

jQuery ui dialog change title after load-callback

I tried to implement the result of Nick which is:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:

    $("#modal_popup").html(data);
    $("#modal_popup").dialog('option', 'title', 'My New Title');
    $("#modal_popup").dialog({ width: 950, height: 550);

I fixed this by adding the title to the javascript function arguments of each dialog on the page:

function show_popup1() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}

function show_popup2() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

How to add option to select list in jQuery

$.each(data,function(index,itemData){
    $('#dropListBuilding').append($("<option></option>")
        .attr("value",key)
        .text(value)); 
});

Vue.js getting an element within a component

Vue 2.x

For Official information:

https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced

A simple Example:

On any Element you have to add an attribute ref with a unique value

<input ref="foo" type="text" >

To target that elemet use this.$refs.foo

this.$refs.foo.focus(); // it will focus the input having ref="foo"

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How do malloc() and free() work?

As aluser says in this forum thread:

Your process has a region of memory, from address x to address y, called the heap. All your malloc'd data lives in this area. malloc() keeps some data structure, let's say a list, of all the free chunks of space in the heap. When you call malloc, it looks through the list for a chunk that's big enough for you, returns a pointer to it, and records the fact that it's not free any more as well as how big it is. When you call free() with the same pointer, free() looks up how big that chunk is and adds it back into the list of free chunks(). If you call malloc() and it can't find any large enough chunk in the heap, it uses the brk() syscall to grow the heap, i.e. increase address y and cause all the addresses between the old y and the new y to be valid memory. brk() must be a syscall; there is no way to do the same thing entirely from userspace.

malloc() is system/compiler dependent so it's hard to give a specific answer. Basically however it does keep track of what memory it's allocated and depending on how it does so your calls to free could fail or succeed.

malloc() and free() don't work the same way on every O/S.

Gradle to execute Java class (without modifying build.gradle)

Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build without errors.

Both gradle build and gradle -PmainClass=foo runApp work with this:

task runApp(type:JavaExec) {
    classpath = sourceSets.main.runtimeClasspath

    main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}

where you set your default main class.

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

how to convert string into time format and add two hours

Basic program of adding two times:
You can modify hour:min:sec as per your need using if else.
This program shows you how you can add values from two objects and return in another object.

class demo
{private int hour,min,sec;
    void input(int hour,int min,int sec)
    {this.hour=hour;
    this.min=min;
    this.sec=sec;

    }
    demo add(demo d2)//demo  because we are returning object
    {   demo obj=new demo();
    obj.hour=hour+d2.hour;
    obj.min=min+d2.min;
    obj.sec=sec+d2.sec;
    return obj;//Returning object and later on it gets allocated to demo d3                    
    }
    void display()
    {
        System.out.println(hour+":"+min+":"+sec);
    }
    public static  void main(String args[])
    {
        demo d1=new demo();
        demo d2=new demo();
        d1.input(2, 5, 10);
        d2.input(3, 3, 3);
        demo d3=d1.add(d2);//Note another object is created
        d3.display();


    }

}

Modified Time Addition Program

class demo {private int hour,min,sec; void input(int hour,int min,int sec) {this.hour=(hour>12&&hour<24)?(hour-12):hour; this.min=(min>60)?0:min; this.sec=(sec>60)?0:sec; } demo add(demo d2) { demo obj=new demo(); obj.hour=hour+d2.hour; obj.min=min+d2.min; obj.sec=sec+d2.sec; if(obj.sec>60) {obj.sec-=60; obj.min++; } if(obj.min>60) { obj.min-=60; obj.hour++; } return obj; } void display() { System.out.println(hour+":"+min+":"+sec); } public static void main(String args[]) { demo d1=new demo(); demo d2=new demo(); d1.input(12, 55, 55); d2.input(12, 7, 6); demo d3=d1.add(d2); d3.display(); } }

Cannot start session without errors in phpMyAdmin

Problem I found in Windows server 2016 was that the permissions were wrong on the temp directory used by PHP. I added IUSR.

Using Panel or PlaceHolder

PlaceHolder control

Use the PlaceHolder control as a container to store server controls that are dynamically added to the Web page. The PlaceHolder control does not produce any visible output and is used only as a container for other controls on the Web page. You can use the Control.Controls collection to add, insert, or remove a control in the PlaceHolder control.

Panel control

The Panel control is a container for other controls. It is especially useful when you want to generate controls programmatically, hide/show a group of controls, or localize a group of controls.

The Direction property is useful for localizing a Panel control's content to display text for languages that are written from right to left, such as Arabic or Hebrew.

The Panel control provides several properties that allow you to customize the behavior and display of its contents. Use the BackImageUrl property to display a custom image for the Panel control. Use the ScrollBars property to specify scroll bars for the control.

Small differences when rendering HTML: a PlaceHolder control will render nothing, but Panel control will render as a <div>.

More information at ASP.NET Forums

Blade if(isset) is not working Laravel

I solved this using the optional() helper. Using the example here it would be:

{{ optional($usersType) }}

A more complicated example would be if, like me, say you are trying to access a property of a null object (ie. $users->type) in a view that is using old() helper.

value="{{ old('type', optional($users)->type }}"

Important to note that the brackets go around the object variable and not the whole thing if trying to access a property of the object.

https://laravel.com/docs/5.8/helpers#method-optional

Can a normal Class implement multiple interfaces?

Yes, it is possible. This is the catch: java does not support multiple inheritance, i.e. class cannot extend more than one class. However class can implement multiple interfaces.

git visual diff between branches

UPDATE

Mac: I now use SourceTree. Thoroughly recommended. I especially like the way you can stage / unstage hunks.

Linux: I've had success with:

  • smartgit
  • GitKraken
  • meld

E.g. to install smartgit on Ubuntu:


This does the job:

git-diffall with a GUI diff tool like meld. See point 5 here:

http://rubyglazed.com/post/15772234418/git-ify-your-command-line

There's a nice post about git and meld here: http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy

convert '1' to '0001' in JavaScript

This is a clever little trick (that I think I've seen on SO before):

var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str

JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):

That is, with the above:

  • 1 -> "0001"
  • 12345 -> "12345"

Supporting negative numbers is left as an exercise ;-)

Happy coding.

Detect the Enter key in a text input field

Try this to detect the Enter key pressed in a textbox.

$(document).on("keypress", "input", function(e){
    if(e.which == 13){
        alert("Enter key pressed");
    }
});

DEMO

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

You can set the default value of your Id in your db to newsequentialid() or newid(). Then the identity configuration of EF should work.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Get DateTime.Now with milliseconds precision

If you still want a date instead of a string like the other answers, just add this extension method.

public static DateTime ToMillisecondPrecision(this DateTime d) {
    return new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute,
                        d.Second, d.Millisecond, d.Kind);
}

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

How do I remove a single file from the staging area (undo git add)?

If you make changes to many tracked files but only want to stage a few of them, doing a

git add .

isn't always favorable (or recommended)- as it stages all the tracked files (some cases where you want to keep changes only to yourself and don't want to stage them to the remote repository).

nor is it ideal doing a bunch of

git add path/to/file1 path/to/file2

if you have a lot of nested directories (which is the case in most projects) - gets annoying

That's when Git GUI is helpful (probably only time I use it). Just open Git GUI, it shows staged and unstaged file sections. Select the files from the staged section that you want to unstage and press

Ctrl+U (for windows)

to unstage them.

Checkout another branch when there are uncommitted changes on the current branch

Preliminary notes

This answer is an attempt to explain why Git behaves the way it does. It is not a recommendation to engage in any particular workflows. (My own preference is to just commit anyway, avoiding git stash and not trying to be too tricky, but others like other methods.)

The observation here is that, after you start working in branch1 (forgetting or not realizing that it would be good to switch to a different branch branch2 first), you run:

git checkout branch2

Sometimes Git says "OK, you're on branch2 now!" Sometimes, Git says "I can't do that, I'd lose some of your changes."

If Git won't let you do it, you have to commit your changes, to save them somewhere permanent. You may want to use git stash to save them; this is one of the things it's designed for. Note that git stash save or git stash push actually means "Commit all the changes, but on no branch at all, then remove them from where I am now." That makes it possible to switch: you now have no in-progress changes. You can then git stash apply them after switching.

Sidebar: git stash save is the old syntax; git stash push was introduced in Git version 2.13, to fix up some problems with the arguments to git stash and allow for new options. Both do the same thing, when used in the basic ways.

You can stop reading here, if you like!

If Git won't let you switch, you already have a remedy: use git stash or git commit; or, if your changes are trivial to re-create, use git checkout -f to force it. This answer is all about when Git will let you git checkout branch2 even though you started making some changes. Why does it work sometimes, and not other times?

The rule here is simple in one way, and complicated/hard-to-explain in another:

You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes.

That is—and please note that this is still simplified; there are some extra-difficult corner cases with staged git adds, git rms and such—suppose you are on branch1. A git checkout branch2 would have to do this:

  • For every file that is in branch1 and not in branch2,1 remove that file.
  • For every file that is in branch2 and not in branch1, create that file (with appropriate contents).
  • For every file that is in both branches, if the version in branch2 is different, update the working tree version.

Each of these steps could clobber something in your work-tree:

  • Removing a file is "safe" if the version in the work-tree is the same as the committed version in branch1; it's "unsafe" if you've made changes.
  • Creating a file the way it appears in branch2 is "safe" if it does not exist now.2 It's "unsafe" if it does exist now but has the "wrong" contents.
  • And of course, replacing the work-tree version of a file with a different version is "safe" if the work-tree version is already committed to branch1.

Creating a new branch (git checkout -b newbranch) is always considered "safe": no files will be added, removed, or altered in the work-tree as part of this process, and the index/staging-area is also untouched. (Caveat: it's safe when creating a new branch without changing the new branch's starting-point; but if you add another argument, e.g., git checkout -b newbranch different-start-point, this might have to change things, to move to different-start-point. Git will then apply the checkout safety rules as usual.)


1This requires that we define what it means for a file to be in a branch, which in turn requires defining the word branch properly. (See also What exactly do we mean by "branch"?) Here, what I really mean is the commit to which the branch-name resolves: a file whose path is P is in branch1 if git rev-parse branch1:P produces a hash. That file is not in branch1 if you get an error message instead. The existence of path P in your index or work-tree is not relevant when answering this particular question. Thus, the secret here is to examine the result of git rev-parse on each branch-name:path. This either fails because the file is "in" at most one branch, or gives us two hash IDs. If the two hash IDs are the same, the file is the same in both branches. No changing is required. If the hash IDs differ, the file is different in the two branches, and must be changed to switch branches.

The key notion here is that files in commits are frozen forever. Files you will edit are obviously not frozen. We are, at least initially, looking only at the mismatches between two frozen commits. Unfortunately, we—or Git—also have to deal with files that aren't in the commit you're going to switch away from and are in the commit you're going to switch to. This leads to the remaining complications, since files can also exist in the index and/or in the work-tree, without having to exist these two particular frozen commits we're working with.

2It might be considered "sort-of-safe" if it already exists with the "right contents", so that Git does not have to create it after all. I recall at least some versions of Git allowing this, but testing just now shows it to be considered "unsafe" in Git 1.8.5.4. The same argument would apply to a modified file that happens to be modified to match the to-be-switch-to branch. Again, 1.8.5.4 just says "would be overwritten", though. See the end of the technical notes as well: my memory may be faulty as I don't think the read-tree rules have changed since I first started using Git at version 1.5.something.


Does it matter whether the changes are staged or unstaged?

Yes, in some ways. In particular, you can stage a change, then "de-modify" the work tree file. Here's a file in two branches, that's different in branch1 and branch2:

$ git show branch1:inboth
this file is in both branches
$ git show branch2:inboth
this file is in both branches
but it has more stuff in branch2 now
$ git checkout branch1
Switched to branch 'branch1'
$ echo 'but it has more stuff in branch2 now' >> inboth

At this point, the working tree file inboth matches the one in branch2, even though we're on branch1. This change is not staged for commit, which is what git status --short shows here:

$ git status --short
 M inboth

The space-then-M means "modified but not staged" (or more precisely, working-tree copy differs from staged/index copy).

$ git checkout branch2
error: Your local changes ...

OK, now let's stage the working-tree copy, which we already know also matches the copy in branch2.

$ git add inboth
$ git status --short
M  inboth
$ git checkout branch2
Switched to branch 'branch2'

Here the staged-and-working copies both matched what was in branch2, so the checkout was allowed.

Let's try another step:

$ git checkout branch1
Switched to branch 'branch1'
$ cat inboth
this file is in both branches

The change I made is lost from the staging area now (because checkout writes through the staging area). This is a bit of a corner case. The change is not gone, but the fact that I had staged it, is gone.

Let's stage a third variant of the file, different from either branch-copy, then set the working copy to match the current branch version:

$ echo 'staged version different from all' > inboth
$ git add inboth
$ git show branch1:inboth > inboth
$ git status --short
MM inboth

The two Ms here mean: staged file differs from HEAD file, and, working-tree file differs from staged file. The working-tree version does match the branch1 (aka HEAD) version:

$ git diff HEAD
$

But git checkout won't allow the checkout:

$ git checkout branch2
error: Your local changes ...

Let's set the branch2 version as the working version:

$ git show branch2:inboth > inboth
$ git status --short
MM inboth
$ git diff HEAD
diff --git a/inboth b/inboth
index ecb07f7..aee20fb 100644
--- a/inboth
+++ b/inboth
@@ -1 +1,2 @@
 this file is in both branches
+but it has more stuff in branch2 now
$ git diff branch2 -- inboth
$ git checkout branch2
error: Your local changes ...

Even though the current working copy matches the one in branch2, the staged file does not, so a git checkout would lose that copy, and the git checkout is rejected.

Technical notes—only for the insanely curious :-)

The underlying implementation mechanism for all of this is Git's index. The index, also called the "staging area", is where you build the next commit: it starts out matching the current commit, i.e., whatever you have checked-out now, and then each time you git add a file, you replace the index version with whatever you have in your work-tree.

Remember, the work-tree is where you work on your files. Here, they have their normal form, rather than some special only-useful-to-Git form like they do in commits and in the index. So you extract a file from a commit, through the index, and then on into the work-tree. After changing it, you git add it to the index. So there are in fact three places for each file: the current commit, the index, and the work-tree.

When you run git checkout branch2, what Git does underneath the covers is to compare the tip commit of branch2 to whatever is in both the current commit and the index now. Any file that matches what's there now, Git can leave alone. It's all untouched. Any file that's the same in both commits, Git can also leave alone—and these are the ones that let you switch branches.

Much of Git, including commit-switching, is relatively fast because of this index. What's actually in the index is not each file itself, but rather each file's hash. The copy of the file itself is stored as what Git calls a blob object, in the repository. This is similar to how the files are stored in commits as well: commits don't actually contain the files, they just lead Git to the hash ID of each file. So Git can compare hash IDs—currently 160-bit-long strings—to decide if commits X and Y have the same file or not. It can then compare those hash IDs to the hash ID in the index, too.

This is what leads to all the oddball corner cases above. We have commits X and Y that both have file path/to/name.txt, and we have an index entry for path/to/name.txt. Maybe all three hashes match. Maybe two of them match and one doesn't. Maybe all three are different. And, we might also have another/file.txt that's only in X or only in Y and is or is not in the index now. Each of these various cases requires its own separate consideration: does Git need to copy the file out from commit to index, or remove it from index, to switch from X to Y? If so, it also has to copy the file to the work-tree, or remove it from the work-tree. And if that's the case, the index and work-tree versions had better match at least one of the committed versions; otherwise Git will be clobbering some data.

(The complete rules for all of this are described in, not the git checkout documentation as you might expect, but rather the git read-tree documentation, under the section titled "Two Tree Merge".)

How to add title to seaborn boxplot

sns.boxplot() function returns Axes(matplotlib.axes.Axes) object. please refer the documentation you can add title using 'set' method as below:

sns.boxplot('Day', 'Count', data=gg).set(title='lalala')

you can also add other parameters like xlabel, ylabel to the set method.

sns.boxplot('Day', 'Count', data=gg).set(title='lalala', xlabel='its x_label', ylabel='its y_label')

There are some other methods as mentioned in the matplotlib.axes.Axes documentaion to add tile, legend and labels.

I cannot start SQL Server browser

go to Services, find SQL Server Browser, right click --> Properties --> General tab --> Startup Type --> select automatic . Then go back to configuration management, start it.

jQuery.animate() with css class only, without explicit styles

The jQueryUI provides a extension to animate function that allows you to animate css class.

edit: Example here

There are also methods to add/remove/toggle class which you might also be interested in.

Add/remove HTML inside div using JavaScript

make a class for that button lets say :

`<input type="button" value="+" class="b1" onclick="addRow()">`

your js should look like this :

$(document).ready(function(){
  $('.b1').click(function(){
      $('div').append('<input type="text"..etc ');
  });
});

How do I cast a JSON Object to a TypeScript class?

I had the same issue and I have found a library that does the job : https://github.com/pleerock/class-transformer.

It works like this :

let jsonObject = response.json() as Object;
let fooInstance = plainToClass(Models.Foo, jsonObject);
return fooInstance;

It supports nested childs but you have to decorate your class's member.

How to make a char string from a C macro's value?

@Jonathan Leffler: Thank you. Your solution works.

A complete working example:

/** compile-time dispatch 

   $ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
*/
#include <stdio.h>

#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)

#ifndef TEST_FUN
#  define TEST_FUN some_func
#endif

#define TEST_FUN_NAME STR(TEST_FUN)

void some_func(void)
{
  printf("some_func() called\n");
}

void another_func(void)
{
  printf("do something else\n");
}

int main(void)
{
  TEST_FUN();
  printf("TEST_FUN_NAME=%s\n", TEST_FUN_NAME);
  return 0;
}

Example:

$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
do something else
TEST_FUN_NAME=another_func

UTF-8 problems while reading CSV file with fgetcsv

Try this:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>

Error CS1705: "which has a higher version than referenced assembly"

My problem was that I had 2 projects referencing 2 different copies of the same dll which had different versions. I fixed it by removing them both and making sure they were referencing the same dll file.

Clearing a text field on button click

A simple JavaScript function will do the job.

function ClearFields() {

     document.getElementById("textfield1").value = "";
     document.getElementById("textfield2").value = "";
}

And just have your button call it:

<button type="button" onclick="ClearFields();">Clear</button>

Why do table names in SQL Server start with "dbo"?

Microsoft introduced schema in version 2008. For those who didn’t know about schema, and those who didn’t care, objects were put into a default schema dbo.

dbo stands for DataBase Owner, but that’s not really important.

Think of a schema as you would a folder for files:

  • You don’t need to refer to the schema if the object is in the same or default schema
  • You can reference an object in a different schema by using the schema as a prefix, the way you can reference a file in a different folder.
  • You can’t have two objects with the same name in a single schema, but you can in different schema
  • Using schema can help you to organise a larger number of objects
  • Schema can also be assigned to particular users and roles, so you can control access to who can do what.

You can always access any object from any schema.

Because dbo is the default, you normally don’t need to specify it within a single database:

SELECT * FROM customers;
SELECT * FROM dbo.customers;

mean the same thing.

I am inclined to disagree with the notion of always using the dbo. prefix, since the more you clutter your code with unnecessary detail, the harder it is to read and manage.

For the most part, you can ignore the schema. However, the schema will make itself apparent in the following situations:

  1. If you view the tables in either the object navigator or in an external application, such as Microsoft Excel or Access, you will see the dbo. prefix. You can still ignore it.

  2. If you reference a table in another database, you will need its full name in the form database.schema.table:

    SELECT * FROM bookshop.dbo.customers;
    
  3. For historical reasons, if you write a user defined scalar function, you will need to call it with the schema prefix:

    CREATE FUNCTION tax(@amount DECIMAL(6,2) RETURNS DECIMAL(6,2) AS
    BEGIN
        RETURN @amount * 0.1;
    END;
    GO
    SELECT total, dbo.tax(total) FROM pricelist;
    

    This does not apply to other objects, such as table functions, procedures and views.

You can use schema to overcome naming conflicts. For example, if every user has a personal schema, they can create additional objects without having to fight with other users over the name.

php - How do I fix this illegal offset type error

Use trim($source) before $s[$source].

SQL Error: ORA-00942 table or view does not exist

I am using Oracle Database and i had same problem. Eventually i found ORACLE DB is converting all the metadata (table/sp/view/trigger) in upper case.

And i was trying how i wrote table name (myTempTable) in sql whereas it expect how it store table name in databsae (MYTEMPTABLE). Also same applicable on column name.

It is quite common problem with developer whoever used sql and now jumped into ORACLE DB.

"405 method not allowed" in IIS7.5 for "PUT" method

I had this problem with WebDAV when hosting a MVC4 WebApi Project. I got around it by adding this line to the web.config:

<handlers>
  <remove name="WebDAV" />
  <add name="WebDAV" path="*" verb="*" modules="WebDAVModule"
      resourceType="Unspecified" requireAccess="None" />
</handlers>

As explained here: http://evolutionarydeveloper.blogspot.co.uk/2012/07/method-not-allowed-405-on-iis7-website.html

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

How do I run a single test using Jest?

Use:

npm run test -- test-name

This will only work if your test specification name is unique.

The code above would reference a file with this name: test-name.component.spec.ts

Invalid date in safari

use the format 'mm/dd/yyyy'. For example :- new Date('02/28/2015'). It works well in all browsers.

How can I have a newline in a string in sh?

I'm no bash expert, but this one worked for me:

STR1="Hello"
STR2="World"
NEWSTR=$(cat << EOF
$STR1

$STR2
EOF
)
echo "$NEWSTR"

I found this easier to formatting the texts.

Media Player called in state 0, error (-38,0)

This is my code,tested and working fine:

package com.example.com.mak.mediaplayer;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final MediaPlayer mpp = MediaPlayer.create(this, R.raw.red); //mp3 file in res/raw folder

    Button btnplay = (Button) findViewById(R.id.btnplay); //Play
    btnplay.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View vone) {
        mpp.start();
      }
    });

    Button btnpause = (Button) findViewById(R.id.btnpause); //Pause
    btnpause.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View vtwo) {
        if (mpp.isPlaying()) {
          mpp.pause();
          mpp.seekTo(0);
        }
      }
    });
  }
}

How do you post to the wall on a facebook page (not profile)

Harish has the answer here - except you need to request manage_pages permission when authenticating and then using the page-id instead of me when posting....

$result = $facebook->api('page-id/feed/','post',$attachment);

Your branch is ahead of 'origin/master' by 3 commits

This happened to me once after I merged a pull request on Bitbucket.

I just had to do:

git fetch

My problem was solved. I hope this helps!!!

Get host domain from URL?

You can use Request object or Uri object to get host of url.

Using Request.Url

string host = Request.Url.Host;

Using Uri

Uri myUri = new Uri("http://www.contoso.com:8080/");   
string host = myUri.Host;  // host is "www.contoso.com"

Git pull till a particular commit

You can also pull the latest commit and just undo until the commit you desire:

git pull origin master
git reset --hard HEAD~1

Replace master with your desired branch.

Use git log to see to which commit you would like to revert:

git log

Personally, this has worked for me better.

Basically, what this does is pulls the latest commit, and you manually revert commits one by one. Use git log in order to see commit history.

Good points: Works as advertised. You don't have to use commit hash or pull unneeded branches.

Bad points: You need to revert commits on by one.

WARNING: Commit/stash all your local changes, because with --hard you are going to lose them. Use at your own risk!

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

I did exactly as @JeffOgata said but I got the error:

Windows NT user or group 'IIS APPPOOL\ASP.NET v4.0' not found. Check the name again. (Microsoft SQL Server, Error: 15401)

I looked at my error message again and it said Login failed for user 'IIS APPPOOL\DefaultAppPool'.

After adding a user named IIS APPPOOL\DefaultAppPool everything worked.

Multi-line strings in PHP

Another solution is to use output buffering, you can collect everything that is being outputted/echoed and store it in a variable.

<?php
ob_start(); 

?>line1
line2
line3<?php 

$xml = ob_get_clean();

Please note that output buffering might not be the best solution in terms of performance and code cleanliness for this exact case but worth leaving it here for reference.

What is the difference between dict.items() and dict.iteritems() in Python2?

In Py2.x

The commands dict.items(), dict.keys() and dict.values() return a copy of the dictionary's list of (k, v) pair, keys and values. This could take a lot of memory if the copied list is very large.

The commands dict.iteritems(), dict.iterkeys() and dict.itervalues() return an iterator over the dictionary’s (k, v) pair, keys and values.

The commands dict.viewitems(), dict.viewkeys() and dict.viewvalues() return the view objects, which can reflect the dictionary's changes. (I.e. if you del an item or add a (k,v) pair in the dictionary, the view object can automatically change at the same time.)

$ python2.7

>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>> 
>>> 
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>> 
>>> 
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>

While in Py3.x

In Py3.x, things are more clean, since there are only dict.items(), dict.keys() and dict.values() available, which return the view objects just as dict.viewitems() in Py2.x did.

But

Just as @lvc noted, view object isn't the same as iterator, so if you want to return an iterator in Py3.x, you could use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

Parallel foreach with asynchronous lambda

You can use the ParallelForEachAsync extension method from AsyncEnumerator NuGet Package:

using Dasync.Collections;

var bag = new ConcurrentBag<object>();
await myCollection.ParallelForEachAsync(async item =>
{
  // some pre stuff
  var response = await GetData(item);
  bag.Add(response);
  // some post stuff
}, maxDegreeOfParallelism: 10);
var count = bag.Count;

Using jQuery, Restricting File Size Before Uploading

I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:

LimitRequestBody 2097152

This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).

Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:

Requested content-length of 4000107 is larger than the configured limit of 2097152

And it will also display this message back in the web browser:

<h1>Request Entity Too Large</h1>

So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.

By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...

Redirect 413 413.html

...and provide a more graceful error result back.

Remove a child with a specific attribute, in SimpleXML for PHP

With FluidXML you can use XPath to select the elements to remove.

$doc = fluidify($doc);

$doc->remove('//*[@id="A12"]');

https://github.com/servo-php/fluidxml


The XPath //*[@id="A12"] means:

  • in any point of the document (//)
  • every node (*)
  • with the attribute id equal to A12 ([@id="A12"]).

Stack smashing detected

Please look at the following situation:

ab@cd-x:$ cat test_overflow.c 
#include <stdio.h>
#include <string.h>

int check_password(char *password){
    int flag = 0;
    char buffer[20];
    strcpy(buffer, password);

    if(strcmp(buffer, "mypass") == 0){
        flag = 1;
    }
    if(strcmp(buffer, "yourpass") == 0){
        flag = 1;
    }
    return flag;
}

int main(int argc, char *argv[]){
    if(argc >= 2){
        if(check_password(argv[1])){
            printf("%s", "Access granted\n");
        }else{
            printf("%s", "Access denied\n");
        }
    }else{
        printf("%s", "Please enter password!\n");
    }
}
ab@cd-x:$ gcc -g -fno-stack-protector test_overflow.c 
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out wepassssssssssssssssss
Access granted

ab@cd-x:$ gcc -g -fstack-protector test_overflow.c 
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepassssssssssssssssss
*** stack smashing detected ***: ./a.out terminated
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x48)[0xce0ed8]
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x0)[0xce0e90]
./a.out[0x8048524]
./a.out[0x8048545]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0xc16b56]
./a.out[0x8048411]
======= Memory map: ========
007d9000-007f5000 r-xp 00000000 08:06 5776       /lib/libgcc_s.so.1
007f5000-007f6000 r--p 0001b000 08:06 5776       /lib/libgcc_s.so.1
007f6000-007f7000 rw-p 0001c000 08:06 5776       /lib/libgcc_s.so.1
0090a000-0090b000 r-xp 00000000 00:00 0          [vdso]
00c00000-00d3e000 r-xp 00000000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d3e000-00d3f000 ---p 0013e000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d3f000-00d41000 r--p 0013e000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d41000-00d42000 rw-p 00140000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d42000-00d45000 rw-p 00000000 00:00 0 
00e0c000-00e27000 r-xp 00000000 08:06 4213       /lib/ld-2.10.1.so
00e27000-00e28000 r--p 0001a000 08:06 4213       /lib/ld-2.10.1.so
00e28000-00e29000 rw-p 0001b000 08:06 4213       /lib/ld-2.10.1.so
08048000-08049000 r-xp 00000000 08:05 1056811    /dos/hacking/test/a.out
08049000-0804a000 r--p 00000000 08:05 1056811    /dos/hacking/test/a.out
0804a000-0804b000 rw-p 00001000 08:05 1056811    /dos/hacking/test/a.out
08675000-08696000 rw-p 00000000 00:00 0          [heap]
b76fe000-b76ff000 rw-p 00000000 00:00 0 
b7717000-b7719000 rw-p 00000000 00:00 0 
bfc1c000-bfc31000 rw-p 00000000 00:00 0          [stack]
Aborted
ab@cd-x:$ 

When I disabled the stack smashing protector no errors were detected, which should have happened when I used "./a.out wepassssssssssssssssss"

So to answer your question above, the message "** stack smashing detected : xxx" was displayed because your stack smashing protector was active and found that there is stack overflow in your program.

Just find out where that occurs, and fix it.

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

Use:

  public void onClick(View v) {

    switch(v.getId()){

      case R.id.Button_MyCards: /** Start a new Activity MyCards.java */
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
        break;

      case R.id.Button_Exit: /** AlerDialog when click on Exit */
        MyAlertDialog();
        break;
    }
}

Note that this will not work in Android library projects (due to http://tools.android.com/tips/non-constant-fields) where you will need to use something like:

int id = view.getId();
if (id == R.id.Button_MyCards) {
    action1();
} else if (id == R.id.Button_Exit) {
    action2();
}

How do I measure separate CPU core usage for a process?

I thought perf stat is what you need.

It shows a specific usage of a process when you specify a --cpu=list option. Here is an example of monitoring cpu usage of building a project using perf stat --cpu=0-7 --no-aggr -- make all -j command. The output is:

CPU0         119254.719293 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU1         119254.724776 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU2         119254.724179 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU3         119254.720833 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU4         119254.714109 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU5         119254.727721 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU6         119254.723447 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU7         119254.722418 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU0                 8,108 context-switches          #    0.068 K/sec                    (100.00%)
CPU1                26,494 context-switches                                              (100.00%)
CPU2                10,193 context-switches                                              (100.00%)
CPU3                12,298 context-switches                                              (100.00%)
CPU4                16,179 context-switches                                              (100.00%)
CPU5                57,389 context-switches                                              (100.00%)
CPU6                 8,485 context-switches                                              (100.00%)
CPU7                10,845 context-switches                                              (100.00%)
CPU0                   167 cpu-migrations            #    0.001 K/sec                    (100.00%)
CPU1                    80 cpu-migrations                                                (100.00%)
CPU2                   165 cpu-migrations                                                (100.00%)
CPU3                   139 cpu-migrations                                                (100.00%)
CPU4                   136 cpu-migrations                                                (100.00%)
CPU5                   175 cpu-migrations                                                (100.00%)
CPU6                   256 cpu-migrations                                                (100.00%)
CPU7                   195 cpu-migrations                                                (100.00%)

The left column is the specific CPU index and the right most column is the usage of the CPU. If you don't specify the --no-aggr option, the result will aggregated together. The --pid=pid option will help if you want to monitor a running process.

Try -a --per-core or -a perf-socket too, which will present more classified information.

More about usage of perf stat can be seen in this tutorial: perf cpu statistic, also perf help stat will help on the meaning of the options.

How to convert C# nullable int to int

You can use the Value property for assignment.

v2 = v1.Value;

Node.js setting up environment specific configs to be used with everyauth

set environment variable in deployment server(ex: like NODE_ENV=production). You can access your environmental variable through process.env.NODE_ENV. Find the following config file for the global settings

const env = process.env.NODE_ENV || "development"

const configs = {
    base: {
        env,
        host: '0.0.0.0',
        port: 3000,
        dbPort: 3306,
        secret: "secretKey for sessions",
        dialect: 'mysql',
        issuer : 'Mysoft corp',
        subject : '[email protected]',
    },
    development: {
        port: 3000,
        dbUser: 'root',
        dbPassword: 'root',

    },
    smoke: {
        port: 3000,
        dbUser: 'root',
    },
    integration: {
        port: 3000,
        dbUser: 'root',
    },
    production: {
        port: 3000,
        dbUser: 'root',
    }
};

const config = Object.assign(configs.base, configs[env]);

module.exports= config;

base contains common config for all environments.

then import in other modules like

const config =  require('path/to/config.js')
console.log(config.port)

Happy Coding...

Android - Best and safe way to stop thread

The Thread.stop() method that could be used to stop a thread has been deprecated; for more info see; Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

Your best bet is to have a variable which the thread itself consults, and voluntarily exits if the variable equals a certain value. You then manipulate the variable inside your code when you want the thread to exit. Alternately of course, you can use an AsyncTask instead.

What does if [ $? -eq 0 ] mean for shell scripts?

It's checking the return value ($?) of grep. In this case it's comparing it to 0 (success).

Usually when you see something like this (checking the return value of grep) it's checking to see whether the particular string was detected. Although the redirect to /dev/null isn't necessary, the same thing can be accomplished using -q.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

Make sure you installed the nuget package Microsoft.AspNet.Identity.Owin. Then add System.Net.Http namespace.

how can I set visible back to true in jquery

The problem is that since you are using ASP.NET controls with a runat attribute, the ID of the control is not actually "test1". It's "test1" with a long string attached to it.

Install dependencies globally and locally using package.json

All modules from package.json are installed to ./node_modules/

I couldn't find this explicitly stated but this is the package.json reference for NPM.

function is not defined error in Python

In python functions aren't accessible magically from everywhere (like they are in say, php). They have to be declared first. So this will work:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1, 2)

But this won't:

pyth_test(1, 2)

def pyth_test (x1, x2):
    print x1 + x2

Android: How to bind spinner to custom object list?

You can look at this answer. You can also go with a custom adapter, but the solution below is fine for simple cases.

Here's a re-post:

So if you came here because you want to have both labels and values in the Spinner - here's how I did it:

  1. Just create your Spinner the usual way
  2. Define 2 equal size arrays in your array.xml file -- one array for labels, one array for values
  3. Set your Spinner with android:entries="@array/labels"
  4. When you need a value, do something like this (no, you don't have to chain it):

      String selectedVal = getResources().getStringArray(R.array.values)[spinner.getSelectedItemPosition()];
    

How do I turn a String into a InputStreamReader in java?

I also found the apache commons IOUtils class , so :

InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

Flash CS4 refuses to let go

What if you compile it using another machine? A fresh installed one would be lovely. I hope your machine is not jealous.

How can I control the speed that bootstrap carousel slides in items?

To complement the previous answers, after you edit your CSS file, you just need to edit CAROUSEL.TRANSITION_DURATION (in bootstrap.js) or c.TRANSITION_DURATION (if you use bootstrap.min.js) and to change the value inside it (600 for default). The final value must be the same that you put in your CSS file (for example, 10s in CSS = 10000 in .js)

Carousel.VERSION  = '3.3.2'
Carousel.TRANSITION_DURATION = xxxxx /* Your number here*/
Carousel.DEFAULTS = {
interval: 5000 /* you could change this value too, but to add data-interval="xxxx" to your html it's fine too*/
pause: 'hover',
wrap: true,
keyboard: true
}

How to create file execute mode permissions in Git on Windows?

If the files already have the +x flag set, git update-index --chmod=+x does nothing and git thinks there's nothing to commit, even though the flag isn't being saved into the repo.

You must first remove the flag, run the git command, then put the flag back:

chmod -x <file>
git update-index --chmod=+x <file>
chmod +x <file>

then git sees a change and will allow you to commit the change.

Static image src in Vue.js template

This is how i solve it.:

      items: [
        { title: 'Dashboard', icon: require('@/assets/icons/sidebar/dashboard.svg') },
        { title: 'Projects',  icon: require('@/assets/icons/sidebar/projects.svg') },
        { title: 'Clients', icon: require('@/assets/icons/sidebar/clients.svg') },
      ],

And on the template part:

<img :src="item.icon" />

See it in action here

How to set environment variables in Jenkins?

You can use Environment Injector Plugin to set environment variables in Jenkins at job and node levels. Below I will show how to set them at job level.

  1. From the Jenkins web interface, go to Manage Jenkins > Manage Plugins and install the plugin.

Environment Injector Plugin

  1. Go to your job Configure screen
  2. Find Add build step in Build section and select Inject environment variables
  3. Set the desired environment variable as VARIABLE_NAME=VALUE pattern. In my case, I changed value of USERPROFILE variable

enter image description here

If you need to define a new environment variable depending on some conditions (e.g. job parameters), then you can refer to this answer.

Detecting negative numbers

You could use a ternary operator like this one, to make it a one liner.

echo ($profitloss < 0) ? 'false' : 'true';

Save results to csv file with Python

You can save it as follow if you have Pandas Dataframe

   df.to_csv(r'/dir/filename.csv')

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

The whole cell doesn't need to be remade. You could use the indentationLevel and indentationWidth property of tableViewCells to shift the content of your cell. Then you add your custom imageView to the left side of the cell.

Format date as dd/MM/yyyy using pipes

I am using this Temporary Solution:

import {Pipe, PipeTransform} from "angular2/core";
import {DateFormatter} from 'angular2/src/facade/intl';

@Pipe({
    name: 'dateFormat'
})
export class DateFormat implements PipeTransform {
    transform(value: any, args: string[]): any {
        if (value) {
            var date = value instanceof Date ? value : new Date(value);
            return DateFormatter.format(date, 'pt', 'dd/MM/yyyy');
        }
    }
}

What is the best way to delete a value from an array in Perl?

if you change

my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;

to

my @del_indexes = reverse(grep { $arr[$_] eq 'foo' } 0..$#arr);

This avoids the array renumbering issue by removing elements from the back of the array first. Putting a splice() in a foreach loop cleans up @arr. Relatively simple and readable...

foreach $item (@del_indexes) {
   splice (@arr,$item,1);
}

transparent navigation bar ios

Utility method which you call by passing navigationController and color which you like to set on navigation bar. For transparent you can use clearColor of UIColor class.

For objective c -

+ (void)setNavigationBarColor:(UINavigationController *)navigationController 
                               color:(UIColor*) color {
   [navigationController setNavigationBarHidden:false animated:false];
   [navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
   [navigationController.navigationBar setShadowImage:[UIImage new]];
   [navigationController.navigationBar setTranslucent:true];
   [navigationController.view setBackgroundColor:color];
   [navigationController.navigationBar setBackgroundColor:color];
}

For Swift 3.0 -

class func setNavigationBarColor(navigationController : UINavigationController?, 
                                 color : UIColor) {
    navigationController?.setNavigationBarHidden(false, animated: false)
    navigationController?.navigationBar .setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
    navigationController?.navigationBar.shadowImage = UIImage()
    navigationController?.navigationBar.translucent = true
    navigationController?.view.backgroundColor = color
    navigationController?.navigationBar.backgroundColor =  color
}

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

How do I create a local database inside of Microsoft SQL Server 2014?

Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link

Youtube video about entire process.
Writeup with pictures about installing SQL Server

How to select a local server:

When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:

1) Make sure you have Server Type: Database

2) Make sure you have Authentication: Windows Authentication (no username & password)

3) For the server name field look to the right and select the drop down arrow, click 'browse for more'

4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14

How do I create a local database inside of Microsoft SQL Server 2014?

1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)

2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!

What's the difference between 'int?' and 'int' in C#?

int? is shorthand for Nullable<int>.

This may be the post you were looking for.

How to store Query Result in variable using mysql

use this

 SELECT weight INTO @x FROM p_status where tcount=['value'] LIMIT 1;

tested and workes fine...

ng-repeat finish event

I had to render formulas using MathJax after ng-repeat ends, none of the above answers solved my problem, so I made like below. It's not a nice solution, but worked for me...

<div ng-repeat="formula in controller.formulas">
    <div>{{formula.string}}</div>
    {{$last ? controller.render_formulas() : ""}}
</div>

Show div on scrollDown after 800px

SCROLLBARS & $(window).scrollTop()

What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.

If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then $(window).scrollTop() will not work.

It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.

If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here

Live long and program, CollyG.

The application has stopped unexpectedly: How to Debug?

If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.

The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.

Define constant variables in C++ header

I like the namespace better for this kind of purpose.

Option 1 :

#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H

//  File Name : LibConstants.hpp    Purpose : Global Constants for Lib Utils
namespace LibConstants
{
  const int CurlTimeOut = 0xFF;     // Just some example
  ...
}
#endif

// source.cpp
#include <LibConstants.hpp>
int value = LibConstants::CurlTimeOut;

Option 2 :

#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H
//  File Name : LibConstants.hpp    Purpose : Global Constants for Lib Utils
namespace CurlConstants
{
  const int CurlTimeOut = 0xFF;     // Just some example
  ...
}

namespace MySQLConstants
{
  const int DBPoolSize = 0xFF;      // Just some example
  ...
}
#endif



// source.cpp
#include <LibConstants.hpp>
int value = CurlConstants::CurlTimeOut;
int val2  = MySQLConstants::DBPoolSize;

And I would never use a Class to hold this type of HardCoded Const variables.

How do I get the height of a div's full content with jQuery?

scrollHeight is a property of a DOM object, not a function:

Height of the scroll view of an element; it includes the element padding but not its margin.

Given this:

<div id="x" style="height: 100px; overflow: hidden;">
    <div style="height: 200px;">
        pancakes
    </div>
</div>

This yields 200:

$('#x')[0].scrollHeight

For example: http://jsfiddle.net/ambiguous/u69kQ/2/ (run with the JavaScript console open).

How to check if C string is empty

With strtok(), it can be done in just one line: "if (strtok(s," \t")==NULL)". For example:

#include <stdio.h>
#include <string.h>

int is_whitespace(char *s) {
    if (strtok(s," \t")==NULL) {
        return 1;
    } else {
        return 0;
    }
}

void demo(void) {
    char s1[128];
    char s2[128];
    strcpy(s1,"   abc  \t ");
    strcpy(s2,"    \t   ");
    printf("s1 = \"%s\"\n", s1);
    printf("s2 = \"%s\"\n", s2);
    printf("is_whitespace(s1)=%d\n",is_whitespace(s1));
    printf("is_whitespace(s2)=%d\n",is_whitespace(s2));
}

int main() {
    char url[63] = {'\0'};
    do {
        printf("Enter a URL: ");
        scanf("%s", url);
        printf("url='%s'\n", url);
    } while (is_whitespace(url));
    return 0;
}

Returning an empty array

Definitely the second one. In the first one, you use a constant empty List<?> and then convert it to a File[], which requires to create an empty File[0] array. And that is what you do in the second one in one single step.

Find index of last occurrence of a substring in a string

You can use rfind() or rindex()
Python2 links: rfind() rindex()

>>> s = 'Hello StackOverflow Hi everybody'

>>> print( s.rfind('H') )
20

>>> print( s.rindex('H') )
20

>>> print( s.rfind('other') )
-1

>>> print( s.rindex('other') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code...


Example: Search of last newline character

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('\n')
22

>>> txt.rindex('\n')
22

TypeScript Objects as Dictionary types as in C#

You can use templated interfaces like this:

interface Map<T> {
    [K: string]: T;
}

let dict: Map<number> = {};
dict["one"] = 1;

Pure CSS animation visibility with delay

Unfortunately you can't animate the display property. For a full list of what you can animate, try this CSS animation list by w3 Schools.

If you want to retain it's visual position on the page, you should try animating either it's height (which will still affect the position of other elements), or opacity (how transparent it is). You could even try animating the z-index, which is the position on the z axis (depth), by putting an element over the top of it, and then rearranging what's on top. However, I'd suggest using opacity, as it retains the vertical space where the element is.

I've updated the fiddle to show an example.

Good luck!

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

Scenario #1: You accidentially re-deployed from the command line while tomcat was already running.

Short Answer: Stop Tomcat, delete target folder, mvn package, then re-deploy


Scenario #2: request.getRequestDispatcher("MIS_SPELLED_FILE_NAME.jsp")

Short Answer: Check file name spelling, make sure case is correct.


Scenario #3: Class Not Found Exceptions (Answer put here because: Question# 17982240 ) (java.lang.ClassNotFoundException for servlet in tomcat with eclipse ) (was marked as duplicate and directed me here )

Short Answer #3.1: web.xml has wrong package path in servlet-class tag.

Short Answer #3.2: java file has wrong import statement.


Below is further details for Scenario #1:


1: Stop Tomcat

  • Option 1: Via CTRL+C in terminal.
  • Option 2: (terminal closed while tomcat still running)
  • ------------ 2.1: press:Windows+R --> type:"services.msc"
  • ------------ 2.2: Find "Apache Tomcat #.# Tomcat#" in Name column of list.
  • ------------ 2.3: Right Click --> "stop"

2: Delete the "target" folder. (mvn clean will not help you here)

3: mvn package

4: YOUR_DEPLOYMENT_COMMAND_HERE

(Mine: java -jar target/dependency/webapp-runner.jar --port 5190 target/*.war )

Full Back Story:


Accidentially opened a new git-bash window and tried to deploy a .war file for my heroku project via:

java -jar target/dependency/webapp-runner.jar --port 5190 target/*.war

After a failure to deploy, I realized I had two git-bash windows open, and had not used CTLR+C to stop the previous deployment.

I was met with:

HTTP Status 404 – Not Found Type Status Report

Message /if-student-test.jsp

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/8.5.31

Below is further details for Scenario #3:


SCENARIO 3.1: The servlet-class package path is wrong in your web.xml file.

It should MATCH the package statement at top of your java servlet class.

File: my_stuff/MyClass.java:

   package my_stuff;

File: PRJ_ROOT/src/main/webapp/WEB-INF/web.xml

   <servlet-class>
   my_stuff.MyClass
   </servlet-class>

SCENARIO 3.2:

You put the wrong "package" statement at top of your myClass.java file.

For example:

File is in: "/my_stuff" folder

You mistakenly write:

package com.my_stuff

This is tricky because:

1: The maven build (mvn package) will not report any errors here.

2: servlet-class line in web.xml can have CORRECT package path. E.g:

<servlet-class>
my_stuff.MyClass
</servlet-class>

Stack Used: Notepad++ + GitBash + Maven + Heroku Web App Runner + Tomcat9 + Windows10:

Object passed as parameter to another class, by value or reference?

"Objects" are NEVER passed in C# -- "objects" are not values in the language. The only types in the language are primitive types, struct types, etc. and reference types. No "object types".

The types Object, MyClass, etc. are reference types. Their values are "references" -- pointers to objects. Objects can only be manipulated through references -- when you do new on them, you get a reference, the . operator operates on a reference; etc. There is no way to get a variable whose value "is" an object, because there are no object types.

All types, including reference types, can be passed by value or by reference. A parameter is passed by reference if it has a keyword like ref or out. The SetObject method's obj parameter (which is of a reference type) does not have such a keyword, so it is passed by value -- the reference is passed by value.

Detect encoding and make everything UTF-8

It's simple: when you get something that's not UTF-8, you must encode that into UTF-8.

So, when you're fetching a certain feed that's ISO 8859-1 parse it through utf8_encode.

However, if you're fetching an UTF-8 feed, you don't need to do anything.

Flask SQLAlchemy query, specify column names

You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.

Center button under form in bootstrap

I do it like this <center></center>

<div class="form-actions">
            <center>
                    <button type="submit" class="submit btn btn-primary ">
                        Sign In <i class="icon-angle-right"></i>
                    </button>
            </center>
</div>

Datatable to html Table

I have seen some solutions here worth noting, as Omer Eldan posted. but here follows. ASP C#

using System.Data;
using System.Web.UI.HtmlControls;

public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
    Table tbl = new Table();
    TableRow tr = null;
    TableCell cell = null;

    int rows = dt.Rows.Count;
    int cols = dt.Columns.Count;

    if (includeHeaders)
    {
        TableHeaderRow htr = new TableHeaderRow();
        TableHeaderCell hcell = null;
        for (int i = 0; i < cols; i++)
        {
            hcell = new TableHeaderCell();
            hcell.Text = dt.Columns[i].ColumnName.ToString();
            htr.Cells.Add(hcell);
        }
        tbl.Rows.Add(htr);
    }

    for (int j = 0; j < rows; j++)
    {
        tr = new TableRow();
        for (int k = 0; k < cols; k++)
        {
            cell = new TableCell();
            cell.Text = dt.Rows[j][k].ToString();
            tr.Cells.Add(cell);
        }
        tbl.Rows.Add(tr);
    }
    return tbl;
}

why this solution? Because you can easily just add this to a panel ie:

panel.Controls.Add(DataTableToHTMLTable(dtExample,true));

Second question , why do you have one column datatables and not just array's? Are you sure that these DataTables are uniform, because if the data is jagged then it's no use. If You really have to join these DataTables, there is many examples of Linq operations, or just use (beware though of same name columns as this will conflict in both linq operations and this solution if not handled):

public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
    int dt2ColsCount = dt2.Columns.Count;
    int dt1lRowsCount = dt1.Rows.Count;

    DataColumn column;
    for (int i = 0; i < dt2ColsCount; i++)
    {
        column = new DataColumn();
        string colName = dt2.Columns[i].ColumnName;
        System.Type colType = dt2.Columns[i].DataType;
        column.ColumnName = colName;
        column.DataType = colType;
        dt1.Columns.Add(column);

        for (int j = 0; j < dt1lRowsCount; j++)
        {
            dt1.Rows[j][colName] = dt2.Rows[j][colName];
        }
    }
    return dt1;
}

and your solution would look something like:

panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));

interpret the rest, and have fun.

How to copy directories in OS X 10.7.3?

tl;dr

cp -R "/src/project 1/App" "/src/project 2"

Explanation:

Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

Oracle Differences between NVL and Coalesce

NVL: Replace the null with value.

COALESCE: Return the first non-null expression from expression list.

Table: PRICE_LIST

+----------------+-----------+
| Purchase_Price | Min_Price |
+----------------+-----------+
| 10             | null      |
| 20             |           |
| 50             | 30        |
| 100            | 80        |
| null           | null      |
+----------------+-----------+   

Below is the example of

[1] Set sales price with adding 10% profit to all products.
[2] If there is no purchase list price, then the sale price is the minimum price. For clearance sale.
[3] If there is no minimum price also, then set the sale price as default price "50".

SELECT
     Purchase_Price,
     Min_Price,
     NVL(Purchase_Price + (Purchase_Price * 0.10), Min_Price)    AS NVL_Sales_Price,
COALESCE(Purchase_Price + (Purchase_Price * 0.10), Min_Price,50) AS Coalesce_Sales_Price
FROM 
Price_List

Explain with real life practical example.

+----------------+-----------+-----------------+----------------------+
| Purchase_Price | Min_Price | NVL_Sales_Price | Coalesce_Sales_Price |
+----------------+-----------+-----------------+----------------------+
| 10             | null      | 11              |                   11 |
| null           | 20        | 20              |                   20 |
| 50             | 30        | 55              |                   55 |
| 100            | 80        | 110             |                  110 |
| null           | null      | null            |                   50 |
+----------------+-----------+-----------------+----------------------+

You can see that with NVL we can achieve rules [1],[2]
But with COALSECE we can achieve all three rules.

Adding a Method to an Existing Object Instance

I think that the above answers missed the key point.

Let's have a class with a method:

class A(object):
    def m(self):
        pass

Now, let's play with it in ipython:

In [2]: A.m
Out[2]: <unbound method A.m>

Ok, so m() somehow becomes an unbound method of A. But is it really like that?

In [5]: A.__dict__['m']
Out[5]: <function m at 0xa66b8b4>

It turns out that m() is just a function, reference to which is added to A class dictionary - there's no magic. Then why A.m gives us an unbound method? It's because the dot is not translated to a simple dictionary lookup. It's de facto a call of A.__class__.__getattribute__(A, 'm'):

In [11]: class MetaA(type):
   ....:     def __getattribute__(self, attr_name):
   ....:         print str(self), '-', attr_name

In [12]: class A(object):
   ....:     __metaclass__ = MetaA

In [23]: A.m
<class '__main__.A'> - m
<class '__main__.A'> - m

Now, I'm not sure out of the top of my head why the last line is printed twice, but still it's clear what's going on there.

Now, what the default __getattribute__ does is that it checks if the attribute is a so-called descriptor or not, i.e. if it implements a special __get__ method. If it implements that method, then what is returned is the result of calling that __get__ method. Going back to the first version of our A class, this is what we have:

In [28]: A.__dict__['m'].__get__(None, A)
Out[28]: <unbound method A.m>

And because Python functions implement the descriptor protocol, if they are called on behalf of an object, they bind themselves to that object in their __get__ method.

Ok, so how to add a method to an existing object? Assuming you don't mind patching class, it's as simple as:

B.m = m

Then B.m "becomes" an unbound method, thanks to the descriptor magic.

And if you want to add a method just to a single object, then you have to emulate the machinery yourself, by using types.MethodType:

b.m = types.MethodType(m, b)

By the way:

In [2]: A.m
Out[2]: <unbound method A.m>

In [59]: type(A.m)
Out[59]: <type 'instancemethod'>

In [60]: type(b.m)
Out[60]: <type 'instancemethod'>

In [61]: types.MethodType
Out[61]: <type 'instancemethod'>

How to start and stop/pause setInterval?

You can't stop a timer function mid-execution. You can only catch it after it completes and prevent it from triggering again.

React - Preventing Form Submission

preventDefault is what you're looking for. To just block the button from submitting

<Button onClick={this.onClickButton} ...

code

onClickButton (event) {
  event.preventDefault();
}

If you have a form which you want to handle in a custom way you can capture a higher level event onSubmit which will also stop that button from submitting.

<form onSubmit={this.onSubmit}>

and above in code

onSubmit (event) {
  event.preventDefault();

  // custom form handling here
}

current/duration time of html5 video?

I am assuming you want to display this as part of the player.

This site breaks down how to get both the current and total time regardless of how you want to display it though using jQuery:

http://dev.opera.com/articles/view/custom-html5-video-player-with-css3-and-jquery/

This will also cover how to set it to a specific div. As philip has already mentioned, .currentTime will give you where you are in the video.

Python concatenate text files

If the files are not gigantic:

with open('newfile.txt','wb') as newf:
    for filename in list_of_files:
        with open(filename,'rb') as hf:
            newf.write(hf.read())
            # newf.write('\n\n\n')   if you want to introduce
            # some blank lines between the contents of the copied files

If the files are too big to be entirely read and held in RAM, the algorithm must be a little different to read each file to be copied in a loop by chunks of fixed length, using read(10000) for example.

How to pass dictionary items as function arguments in python?

*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.

data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}


def my_function(**data):
    schoolname  = data['school']
    cityname = data['city']
    standard = data['class']
    studentname = data['name']

You can call the function like this:

my_function(**data)

How do you change the datatype of a column in SQL Server?

As long as you're increasing the size of your varchar you're OK. As per the Alter Table reference:

Reducing the precision or scale of a column may cause data truncation.

Function inside a function.?

It is possible to define a function from inside another function. the inner function does not exist until the outer function gets executed.

echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';
$x=x(2);
echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';

Output

y is not defined

y is defined

Simple thing you can not call function y before executed x

Android failed to load JS bundle

Apparently adb reverse was introduced in Android 5.0
Getting "error: closed" twice on "adb reverse"

I guess we have to go ahead with kzzzf's answer

How can I delete a query string parameter in JavaScript?

I don't see major issues with a regex solution. But, don't forget to preserve the fragment identifier (text after the #).

Here's my solution:

function RemoveParameterFromUrl(url, parameter) {
  return url
    .replace(new RegExp('[?&]' + parameter + '=[^&#]*(#.*)?$'), '$1')
    .replace(new RegExp('([?&])' + parameter + '=[^&]*&'), '$1');
}

And to bobince's point, yes - you'd need to escape . characters in parameter names.

Floating point exception

http://en.wikipedia.org/wiki/Division_by_zero

http://en.wikipedia.org/wiki/Unix_signal#SIGFPE

This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0 IS division by zero and as such, will trigger a SIGFPE being thrown.

What is the right way to debug in iPython notebook?

A native debugger is being made available as an extension to JupyterLab. Released a few weeks ago, this can be installed by getting the relevant extension, as well as xeus-python kernel (which notably comes without the magics well-known to ipykernel users):

jupyter labextension install @jupyterlab/debugger
conda install xeus-python -c conda-forge

This enables a visual debugging experience well-known from other IDEs.

enter image description here

Source: A visual debugger for Jupyter

How to read data from a zip file without having to unzip the entire file

DotNetZip is your friend here.

As easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  ZipEntry e = zip["MyReport.doc"];
  e.Extract(OutputStream);
}

(you can also extract to a file or other destinations).

Reading the zip file's table of contents is as easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  foreach (ZipEntry e in zip)
  {
    if (header)
    {
      System.Console.WriteLine("Zipfile: {0}", zip.Name);
      if ((zip.Comment != null) && (zip.Comment != "")) 
        System.Console.WriteLine("Comment: {0}", zip.Comment);
      System.Console.WriteLine("\n{1,-22} {2,8}  {3,5}   {4,8}  {5,3} {0}",
                               "Filename", "Modified", "Size", "Ratio", "Packed", "pw?");
      System.Console.WriteLine(new System.String('-', 72));
      header = false;
    }
    System.Console.WriteLine("{1,-22} {2,8} {3,5:F0}%   {4,8}  {5,3} {0}",
                             e.FileName,
                             e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                             e.UncompressedSize,
                             e.CompressionRatio,
                             e.CompressedSize,
                             (e.UsesEncryption) ? "Y" : "N");

  }
}

Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still available at Codeplex. It looks like the code has migrated to Github:


Cannot execute script: Insufficient memory to continue the execution of the program

My database was larger than 500mb, I then used the following

C:\Windows>sqlcmd -S SERVERNAME -U USERNAME -P PASSWORD -d DATABASE -i C:\FILE.sql

It loaded everything including SP's

*NB: Run the cmd as Administrator

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

What is the list of valid @SuppressWarnings warning names in Java?

All values are permitted (unrecognized ones are ignored). The list of recognized ones is compiler specific.

In The Java Tutorials unchecked and deprecation are listed as the two warnings required by The Java Language Specification, therefore, they should be valid with all compilers:

Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked.

The specific sections inside The Java Language Specification where they are defined is not consistent across versions. In the Java SE 8 Specification unchecked and deprecation are listed as compiler warnings in sections 9.6.4.5. @SuppressWarnings and 9.6.4.6 @Deprecated, respectively.

For Sun's compiler, running javac -X gives a list of all values recognized by that version. For 1.5.0_17, the list appears to be:

  • all
  • deprecation
  • unchecked
  • fallthrough
  • path
  • serial
  • finally