Programs & Examples On #Eclassnotfound

How can I find the number of arguments of a Python function?

inspect.getargspec() to meet your needs

from inspect import getargspec

def func(a, b):
    pass
print len(getargspec(func).args)

Convert the first element of an array to a string in PHP

For completeness and simplicity sake, the following should be fine:

$str = var_export($array, true);

It does the job quite well in my case, but others seem to have issues with whitespace. In that case, the answer from ucefkh provides a workaround from a comment in the PHP manual.

How to append binary data to a buffer in node.js

Updated Answer for Node.js ~>0.8

Node is able to concatenate buffers on its own now.

var newBuffer = Buffer.concat([buffer1, buffer2]);

Old Answer for Node.js ~0.6

I use a module to add a .concat function, among others:

https://github.com/coolaj86/node-bufferjs

I know it isn't a "pure" solution, but it works very well for my purposes.

IIS Request Timeout on long ASP.NET operation

If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.

For example:

// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;

This value can also be configured in your web.config file in the httpRuntime configuration element:

<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300" 
  ... other configuration attributes ...
/>

enter image description here

Please note according to the MSDN documentation:

"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."

If you've already done this but are finding that your session is expiring then increase the ASP.NET HttpSessionState.Timeout value:

For example:

// Increase session timeout to thirty minutes
Session.Timeout = 30;

This value can also be configured in your web.config file in the sessionState configuration element:

<configuration>
  <system.web>
    <sessionState 
      mode="InProc"
      cookieless="true"
      timeout="30" />
  </system.web>
</configuration>

If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.

The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.

Iterating through a string word by word

This is one way to do it:

string = "this is a string"
ssplit = string.split()
for word in ssplit:
    print (word)

Output:

this
is
a
string

Ruby: Merging variables in to a string

The standard ERB templating system may work for your scenario.

def merge_into_string(animal, second_animal, action)
  template = 'The <%=animal%> <%=action%> the <%=second_animal%>'
  ERB.new(template).result(binding)
end

merge_into_string('tiger', 'deer', 'eats')
=> "The tiger eats the deer"

merge_into_string('bird', 'worm', 'finds')
=> "The bird finds the worm"

how to count the total number of lines in a text file using python

this one also gives the no.of lines in a file.

a=open('filename.txt','r')
l=a.read()
count=l.splitlines()
print(len(count))

How to use "svn export" command to get a single file from the repository?

Use SVN repository URL to export file to Local path.

     svn export [-r rev] [--ignore-externals] URL Export_PATH
     svn export http://<path>/test.txt C:\Temp-Folder

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

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

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

How to round up integer division and have int result in Java?

Another one-liner that is not too complicated:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

Could use long instead of int; just change the parameter types and return type.

Implementing IDisposable correctly

Idisposable is implement whenever you want a deterministic (confirmed) garbage collection.

class Users : IDisposable
    {
        ~Users()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
            // This method will remove current object from garbage collector's queue 
            // and stop calling finilize method twice 
        }    

        public void Dispose(bool disposer)
        {
            if (disposer)
            {
                // dispose the managed objects
            }
            // dispose the unmanaged objects
        }
    }

When creating and using the Users class use "using" block to avoid explicitly calling dispose method:

using (Users _user = new Users())
            {
                // do user related work
            }

end of the using block created Users object will be disposed by implicit invoke of dispose method.

How to split a list by comma not space

Create a bash function

split_on_commas() {
  local IFS=,
  local WORD_LIST=($1)
  for word in "${WORD_LIST[@]}"; do
    echo "$word"
  done
}

split_on_commas "this,is a,list" | while read item; do
  # Custom logic goes here
  echo Item: ${item}
done

... this generates the following output:

Item: this
Item: is a
Item: list

(Note, this answer has been updated according to some feedback)

how to set radio button checked in edit mode in MVC razor view

You have written like

@Html.RadioButtonFor(model => model.gender, "Male", new { @checked = true }) and
@Html.RadioButtonFor(model => model.gender, "Female", new { @checked = true })

Here you have taken gender as a Enum type and you have written the value for the radio button as a string type- change "Male" to 0 and "Female" to 1.

hibernate - get id after save object

The session.save(object) returns the id of the object, or you could alternatively call the id getter method after performing a save.

Save() return value:

Serializable save(Object object) throws HibernateException

Returns:

the generated identifier

Getter method example:

UserDetails entity:

@Entity
public class UserDetails {
    @Id
    @GeneratedValue
    private int id;
    private String name;

    // Constructor, Setters & Getters
}

Logic to test the id's :

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
UserDetails user1 = new UserDetails("user1");
UserDetails user2 = new UserDetails("user2");

//int userId = (Integer) session.save(user1); // if you want to save the id to some variable

System.out.println("before save : user id's = "+user1.getId() + " , " + user2.getId());

session.save(user1);
session.save(user2);

System.out.println("after save : user id's = "+user1.getId() + " , " + user2.getId());

session.getTransaction().commit();

Output of this code:

before save : user id's = 0 , 0

after save : user id's = 1 , 2

As per this output, you can see that the id's were not set before we save the UserDetails entity, once you save the entities then Hibernate set's the id's for your objects - user1 and user2

CSS Background image not loading

I found the problem was you can't use short URL for image "img/image.jpg"

you should use the full URL "http://www.website.com/img/image.jpg", yet I don't know why !!

How can I listen for a click-and-hold in jQuery?

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})

Compare two objects in Java with possible null values

For those on android, who can't use API 19's Objects.equals(str1, str2), there is this:

android.text.TextUtils.equals(str1, str2);

It is null safe. It rarely has to use the more expensive string.equals() method because identical strings on android almost always compare true with the "==" operand thanks to Android's String Pooling, and length checks are a fast way to filter out most mismatches.

Source Code:

/**
 * Returns true if a and b are equal, including if they are both null.
 * <p><i>Note: In platform versions 1.1 and earlier, this method only worked  well if
 * both the arguments were instances of String.</i></p>
 * @param a first CharSequence to check
 * @param b second CharSequence to check
 * @return true if a and b are equal
 */
public static boolean equals(CharSequence a, CharSequence b) {
    if (a == b) return true;
    int length;
    if (a != null && b != null && (length = a.length()) == b.length()) {
        if (a instanceof String && b instanceof String) {
            return a.equals(b);
        } else {
            for (int i = 0; i < length; i++) {
                if (a.charAt(i) != b.charAt(i)) return false;
            }
            return true;
        }
    }
    return false;
}

How to push to History in React Router v4?

React Router v4 is fundamentally different from v3 (and earlier) and you cannot do browserHistory.push() like you used to.

This discussion seems related if you want more info:

  • Creating a new browserHistory won't work because <BrowserRouter> creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the <BrowserRouter>.
  • browserHistory is not exposed by react-router in v4, only in v2.

Instead you have a few options to do this:

  • Use the withRouter high-order component

    Instead you should use the withRouter high order component, and wrap that to the component that will push to history. For example:

    import React from "react";
    import { withRouter } from "react-router-dom";
    
    class MyComponent extends React.Component {
      ...
      myFunction() {
        this.props.history.push("/some/Path");
      }
      ...
    }
    export default withRouter(MyComponent);
    

    Check out the official documentation for more info:

    You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.


  • Use the context API

    Using the context might be one of the easiest solutions, but being an experimental API it is unstable and unsupported. Use it only when everything else fails. Here's an example:

    import React from "react";
    import PropTypes from "prop-types";
    
    class MyComponent extends React.Component {
      static contextTypes = {
        router: PropTypes.object
      }
      constructor(props, context) {
         super(props, context);
      }
      ...
      myFunction() {
        this.context.router.history.push("/some/Path");
      }
      ...
    }
    

    Have a look at the official documentation on context:

    If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.

    If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

There could be various reason for getting the SSH error:

sign_and_send_pubkey: signing failed: agent refused operation

Some of them could be related to the issues highlighted by the other answers (see this thread answers), some of them could be hidden and thus would require a closer investigation.

In my case I've got the following error message:

sign_and_send_pubkey: signing failed: agent refused operation

[email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

The only way to find the real problem was to invoke the -v verbose option which resulted in printing a lot of debugging info:

debug1: Connecting to website.domain.com [xxx.xxx.xxx.xxx] port 22.
debug1: Connection established.
debug1: identity file /home/user/.ssh/id_rsa.website.domain.com type 0
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_rsa.website.domain.com-cert type -1

Please note that the line saying key_load_public: No such file or directory is referring the next line and not the previous line.

So what SSH really says is that it could not find the public key file named id_rsa.website.domain.com-cert and that seemed to be the problem in my case since my public key file did not contain the -cert suffix.

Long story short: the fix in my case was just to make sure that the public key file was named as expected. I could never suspected that without debugging the connection.

The bottom line is USE THE SSH VERBOSE MODE (-v option) to figure out what is wrong, there could be various reasons, none that could be found on this/another thread.

Generate ER Diagram from existing MySQL database, created for CakePHP

If you don't want to install MySQL workbench, and are looking for an online tool, this might help: http://ondras.zarovi.cz/sql/demo/

I use it quite often to create simple DB schemas for various apps I build.

REST HTTP status codes for failed validation or invalid duplicate

I recommend status code 422, "Unprocessable Entity".

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Setting a system environment variable from a Windows batch file?

If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.

Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):

SET XYZ=test
SETX XYZ test

Space between two rows in a table?

Ok, you can do

tr.classname td {background-color:red; border-bottom: 5em solid white}

Make sure the background color is set on the td rather than the row. This should work across most browsers... (Chrome, ie & ff tested)

How to create helper file full of functions in react native?

To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.

Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.

Example:

/* Utils.js */
/* This file contains functions you can use anywhere in your application */

function formatName(label) {
   // your logic
}

function formatDate(date) {
   // your logic
}

// Now you have to export each function you want
export {
   formatName,
   formatDate,
};

Let's create another file which has functions to help you with tables:

/* Table.js */
/* Table file contains functions to help you when working with tables */

function getColumnsFromData(data) {
   // your logic
}

function formatCell(data) {
   // your logic
}

// Export each function
export {
   getColumnsFromData,
   formatCell,
};

Now the trick is to have a index.js inside the helpers folder:

/* Index.js */
/* Inside this file you will import your other helper files */

// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';

// Export again
export {
   Utils,
   Table,
};

Now you can import then separately to use each function:

import { Table, Utils } from 'helpers';

const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);

const myName = Utils.formatName(someNameVariable);

Hope it can help to organise your files in a better way.

Select from multiple tables without a join?

In this case we are assuming that we have two tables: SMPPMsgLogand SMSService with common column serviceid:

SELECT sp.SMS,ss.CMD 
FROM vas.SMPPMsgLog AS sp,vas.SMSService AS ss 
WHERE sp.serviceid=5431 
AND ss.ServiceID = 5431 
AND Receiver ="232700000" 
AND date(TimeStamp) <='2013-08-07' 
AND date(TimeStamp) >='2013-08-06' \G;

How to set height property for SPAN

Give it a display:inline-block in CSS - that should let it do what you want.
In terms of compatibility: IE6/7 will work with this, as quirks mode suggests:

IE 6/7 accepts the value only on elements with a natural display: inline.

socket.error: [Errno 48] Address already in use

I have a raspberry pi, and I am using python web server (using Flask). I have tried everything above, the only solution is to close the terminal(shell) and open it again. Or restart the raspberry pi, because nothing stops that webserver...

POST Content-Length exceeds the limit

you just setting at php.ini

then set :

upload_max_filesize = 1000M;
post_max_size = 1000M;

then restart your xampp.. Check the image

What is the best way to get the count/length/size of an iterator?

Using Guava library:

int size = Iterators.size(iterator);

Internally it just iterates over all elements so its just for convenience.

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

How can I add a Google search box to my website?

Sorry for replying on an older question, but I would like to clarify the last question.

You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:

https://www.google.com/search?g=[value from input-field]

But when you search with google, you notice the following URL:

https://www.google.nl/search?q=google+search+bar

Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Update

Official standard dialogs are coming to JavaFX in release 8u40, as part of the implemenation of RT-12643. These should be available in final release form around March of 2015 and in source code form in the JavaFX development repository now.

In the meantime, you can use the ControlsFX solution below...


ControlsFX is the defacto standard 3rd party library for common dialog support in JavaFX (error, warning, confirmation, etc).

There are numerous other 3rd party libraries available which provide common dialog support as pointed out in some other answers and you can create your own dialogs easily enough using the sample code in Sergey's answer.

However, I believe that ControlsFX easily provide the best quality standard JavaFX dialogs available at the moment. Here are some samples from the ControlsFX documentation.

standard dialog

command links

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

How to get the background color of an HTML element?

Simple solution

myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;

Now the background color is stored in the new variable.

https://jsfiddle.net/7q1dpeo9/1/

Composer Update Laravel

When you run composer update, composer generates a file called composer.lock which lists all your packages and the currently installed versions. This allows you to later run composer install, which will install the packages listed in that file, recreating the environment that you were last using.

It appears from your log that some of the versions of packages that are listed in your composer.lock file are no longer available. Thus, when you run composer install, it complains and fails. This is usually no big deal - just run composer update and it will attempt to build a set of packages that work together and write a new composer.lock file.

However, you're running into a different problem. It appears that, in your composer.json file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate command. This can be avoided by running the following: composer update --no-scripts

This will run the composer update but will skip over the scripts added to the file. You should be able to successfully run the update this way.

However, this does not solve the problem long-term. There are two problems:

  1. A migration is for database changes, not random stuff like compiling assets. Go through the migrations and remove that code from there.

  2. Assets should not be compiled each time you run composer update. Remove that step from the composer.json file.

From what I've read, best practice seems to be compiling assets on an as-needed basis during development (ie. when you're making changes to your LESS files - ideally using a tool like gulp.js) and before deployment.

Accessing session from TWIG template

I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals() method. Rather than using $_SESSION, it's also better to use Symfony's Session class since it handles automatically starting/stopping the session.

I've got the following extension in /src/AppBundle/Twig/AppExtension.php:

<?php    
namespace AppBundle\Twig;

use Symfony\Component\HttpFoundation\Session\Session;

class AppExtension extends \Twig_Extension {

    public function getGlobals() {
        $session = new Session();
        return array(
            'session' => $session->all(),
        );
    }

    public function getName() {
        return 'app_extension';
    }
}

Then add this in /app/config/services.yml:

services:
    app.twig_extension:
        class: AppBundle\Twig\AppExtension
        public: false
        tags:
            - { name: twig.extension }

Then the session can be accessed from any view using:

{{ session.my_variable }}

header location not working in my php code

Create config.php and put the code it will work

MAX(DATE) - SQL ORACLE

Try:

SELECT MEMBSHIP_ID
  FROM user_payment
 WHERE user_id=1 
ORDER BY paym_date = (select MAX(paym_date) from user_payment and user_id=1);

Or:

SELECT MEMBSHIP_ID
FROM (
  SELECT MEMBSHIP_ID, row_number() over (order by paym_date desc) rn
      FROM user_payment
     WHERE user_id=1 )
WHERE rn = 1

Get PHP class property by string

It is simple, $obj->{$obj->Name} the curly brackets will wrap the property much like a variable variable.

This was a top search. But did not resolve my question, which was using $this. In the case of my circumstance using the curly bracket also helped...

example with Code Igniter get instance

in an sourced library class called something with a parent class instance

$this->someClass='something';
$this->someID=34;

the library class needing to source from another class also with the parents instance

echo $this->CI->{$this->someClass}->{$this->someID};

Show percent % instead of counts in charts of categorical variables

Here is a workaround for faceted data. (The accepted answer by @Andrew does not work in this case.) The idea is to calculate the percentage value using dplyr and then to use geom_col to create the plot.

library(ggplot2)
library(scales)
library(magrittr)
library(dplyr)

binwidth <- 30

mtcars.stats <- mtcars %>%
  group_by(cyl) %>%
  mutate(bin = cut(hp, breaks=seq(0,400, binwidth), 
               labels= seq(0+binwidth,400, binwidth)-(binwidth/2)),
         n = n()) %>%
  group_by(cyl, bin) %>%
  summarise(p = n()/n[1]) %>%
  ungroup() %>%
  mutate(bin = as.numeric(as.character(bin)))

ggplot(mtcars.stats, aes(x = bin, y= p)) +  
  geom_col() + 
  scale_y_continuous(labels = percent) +
  facet_grid(cyl~.)

This is the plot:

enter image description here

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

Comparing floating point number to zero

Like @Exceptyon pointed out, this function is 'relative' to the values you're comparing. The Epsilon * abs(x) measure will scale based on the value of x, so that you'll get a comparison result as accurately as epsilon, irrespective of the range of values in x or y.

If you're comparing zero(y) to another really small value(x), say 1e-8, abs(x-y) = 1e-8 will still be much larger than epsilon *abs(x) = 1e-13. So unless you're dealing with extremely small number that can't be represented in a double type, this function should do the job and will match zero only against +0 and -0.

The function seems perfectly valid for zero comparison. If you're planning to use it, I suggest you use it everywhere there're floats involved, and not have special cases for things like zero, just so that there's uniformity in the code.

ps: This is a neat function. Thanks for pointing to it.

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

_x000D_
_x000D_
var regex =/^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,64}$/;

 
function test() {

 if(regex.test(document.getElementById("txtPassword").value)===false)
 {
 alert("Min 6,Max 64,At Least One Uppercase Character,One Lowercase Character,One Numeric Value And One Special Character(!@#$%^&*) Required ");
 }
 else
 {
 alert("Success");
 }
}
_x000D_
<input type="text" id="txtPassword" />
<button id="testBtn" onclick=test()>CheckPassword</button>
_x000D_
_x000D_
_x000D_

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!Column.Value = "Approved", "Green", "No Color")

Setting DEBUG = False causes 500 Error

I know this is late but I ended up here with a search for my error 500 with DEBUG=False, in my case it did turn out to be the ALLOWED_HOSTS but I was using os.environ.get('variable') to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False:

# settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}

Converting DateTime format using razor

Below code will help you

@Html.Label(@item.Date.Value.ToString("dd - M - yy"))

How to display an activity indicator with text on iOS 8 with Swift?

This code work in SWIFT 2.0.

Must Declare a variable for initialize UIActivityIndicatorView

let actInd: UIActivityIndicatorView = UIActivityIndicatorView() 

After initialize put this code in your controller.

actInd.center = ImageView.center
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
view.addSubview(actInd)
actInd.startAnimating()

after your download process complete then hide a animation.

self.actInd.stopAnimating()

How do I calculate a trendline for a graph?

OK, here's my best pseudo math:

The equation for your line is:

Y = a + bX

Where:

b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)

a = sum(y)/n - b(sum(x)/n)

Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)

... and now with added Sigma

b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n)

a = (Σy)/n - b((Σx)/n)

Where Σ(xy) is the sum of all x*y etc. and n is the number of points

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

How do I add a .click() event to an image?

First of all, this line

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()

You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click() there.

If you read the JavaScript you've got there, document.getElementById('foo') it's looking for an HTML element with an ID of foo. You don't have one. Give your image that ID:

<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />

Alternatively, you could throw the JS in a function and put an onclick in your HTML:

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />

I suggest you do some reading up on JavaScript and HTML though.


The others are right about needing to move the <img> above the JS click binding too.

Simplest way to detect a pinch

Hammer.js all the way! It handles "transforms" (pinches). http://eightmedia.github.com/hammer.js/

But if you wish to implement it youself, i think that Jeffrey's answer is pretty solid.

What to do with "Unexpected indent" in python?

In Python, the spacing is very important, this gives the structure of your code blocks. This error happens when you mess up your code structure, for example like this :

def test_function() :
   if 5 > 3 :
   print "hello"

You may also have a mix of tabs and spaces in your file.

I suggest you use a python syntax aware editor like PyScripter, or Netbeans

Authenticated HTTP proxy with Java

(EDIT: As pointed out by the OP, the using a java.net.Authenticator is required too. I'm updating my answer accordingly for the sake of correctness.)

(EDIT#2: As pointed out in another answer, in JDK 8 it's required to remove basic auth scheme from jdk.http.auth.tunneling.disabledSchemes property)

For authentication, use java.net.Authenticator to set proxy's configuration and set the system properties http.proxyUser and http.proxyPassword.

final String authUser = "user";
final String authPassword = "password";
Authenticator.setDefault(
  new Authenticator() {
    @Override
    public PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(authUser, authPassword.toCharArray());
    }
  }
);

System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);

System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

Converting Dictionary to List?

Your problem is that you have key and value in quotes making them strings, i.e. you're setting aKey to contain the string "key" and not the value of the variable key. Also, you're not clearing out the temp list, so you're adding to it each time, instead of just having two items in it.

To fix your code, try something like:

for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

You don't need to copy the loop variables key and value into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value]) if we wanted to be as brief as possible.

Or just use dict.items() as has been suggested.

Get skin path in Magento?

First of all it is not recommended to have php files with functions in design folder. You should create a new module or extend (copy from core to local a helper and add function onto that class) and do not change files from app/code/core.

To answer to your question you can use:

require(Mage::getBaseDir('design').'/frontend/default/mytheme/myfunc.php');

Best practice (as a start) will be to create in /app/code/local/Mage/Core/Helper/Extra.php a php file:

<?php
class Mage_Core_Helper_Extra extends Mage_Core_Helper_Abstract
{

    public function getSomething()
    {
        return 'Someting';
    }

}

And to use it in phtml files use:

$this->helper('core/extra')->getSomething();

Or in all the places:

Mage::helper('core/extra')->getSomething();

Gridview get Checkbox.Checked value

Blockquote

    foreach (GridViewRow row in tempGrid.Rows)
    {
        dt.Rows.Add();
        for (int i = 0; i < row.Controls.Count; i++)
        {
            Control control = row.Controls[i];
            if (control.Controls.Count==1)
            {
                CheckBox chk = row.Cells[i].Controls[0] as CheckBox;
                if (chk != null && chk.Checked)
                {
                    dt.Rows[dt.Rows.Count - 1][i] = "True";
                }
                else
                dt.Rows[dt.Rows.Count - 1][i] = "False";
            }
            else
                dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text.Replace("&nbsp;", "");
        }
    }

Make xargs handle filenames that contain spaces

It depends on (a) how attached you are to the number 7 as opposed to, say, Lemons, and (b) whether any of your file names contain newlines (and whether you're willing to rename them if they do).

There are many ways to deal with it, but some of them are:

mplayer Lemon*.mp3

find . -name 'Lemon*.mp3' -exec mplayer {} ';'

i=0
for mp3 in *.mp3
do
    i=$((i+1))
    [ $i = 7 ] && mplayer "$mp3"
done

for mp3 in *.mp3
do
    case "$mp3" in
    (Lemon*) mplayer "$mp3";;
    esac
done

i=0
find . -name *.mp3 |
while read mp3
do
    i=$((i+1))
    [ $i = 7 ] && mplayer "$mp3"
done

The read loop doesn't work if file names contain newlines; the others work correctly even with newlines in the names (let alone spaces). For my money, if you have file names containing a newline, you should rename the file without the newline. Using the double quotes around the file name is key to the loops working correctly.

If you have GNU find and GNU xargs (or FreeBSD (*BSD?), or Mac OS X), you can also use the -print0 and -0 options, as in:

find . -name 'Lemon*.mp3' -print0 | xargs -0 mplayer

This works regardless of the contents of the name (the only two characters that cannot appear in a file name are slash and NUL, and the slash causes no problems in a file path, so using NUL as the name delimiter covers everything). However, if you need to filter out the first 6 entries, you need a program that handles 'lines' ended by NUL instead of newline...and I'm not sure there are any.

The first is by far the simplest for the specific case on hand; however, it may not generalize to cover your other scenarios that you've not yet listed.

Comparing strings by their alphabetical order

String a = "..."; 
String b = "...";  

int compare = a.compareTo(b);  

if (compare < 0) {  
    //a is smaller
}
else if (compare > 0) {
    //a is larger 
}
else {  
    //a is equal to b
} 

Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

SQL left join vs multiple tables on FROM line?

I hear a lot of people complain the first one is too difficult to understand and that it is unclear. I don't see a problem with it, but after having that discussion, I use the second one even on INNER JOINS for clarity.

MISCONF Redis is configured to save RDB snapshots

If you're running MacOS and have recently upgraded to Catalina, you may need to run brew services restart redis as suggested in this issue.

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You could cast it to <any> or extend the jquery typing to add your own method.

 (<any>$("div.printArea")).printArea();

//Or add your own custom methods (Assuming this is added by yourself as a part of custom plugin)

interface JQuery {
    printArea():void;
}

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

A button to start php script, how?

Having 2 files like you suggested would be the easiest solution.

For instance:

2 files solution:

index.html

(.. your html ..)
<form action="script.php" method="get">
  <input type="submit" value="Run me now!">
</form>
(...)

script.php

<?php
  echo "Hello world!"; // Your code here
?>

Single file solution:

index.php

<?php
  if (!empty($_GET['act'])) {
    echo "Hello world!"; //Your code here
  } else {
?>
(.. your html ..)
<form action="index.php" method="get">
  <input type="hidden" name="act" value="run">
  <input type="submit" value="Run me now!">
</form>
<?php
  }
?>

How to create a file in Ruby

OK, now I feel stupid. The first two definitely do not work but the second two do. Not sure how I convinced my self that I had tried them. Sorry for wasting everyone's time.

In case this helps anyone else, this can occur when you are trying to make a new file in a directory that does not exist.

How to set tint for an image view programmatically in android?

In case you want to set selector to your tint:

ImageViewCompat.setImageTintList(iv, getResources().getColorStateList(R.color.app_icon_click_color));

How do I show my global Git configuration?

Git 2.6 (Sept/Oct 2015) will add the option --name-only to simplify the output of a git config -l:

See commit a92330d, commit f225987, commit 9f1429d (20 Aug 2015) by Jeff King (peff).
See commit ebca2d4 (20 Aug 2015), and commit 905f203, commit 578625f (10 Aug 2015) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit fc9dfda, 31 Aug 2015)

config: add '--name-only' option to list only variable names

'git config' can only show values or name-value pairs, so if a shell script needs the names of set config variables it has to run 'git config --list' or '--get-regexp' and parse the output to separate config variable names from their values.
However, such a parsing can't cope with multi-line values.

Though 'git config' can produce null-terminated output for newline-safe parsing, that's of no use in such a case, because shells can't cope with null characters.

Even our own bash completion script suffers from these issues.

Help the completion script, and shell scripts in general, by introducing the '--name-only' option to modify the output of '--list' and '--get-regexp' to list only the names of config variables, so they don't have to perform error-prone post processing to separate variable names from their values anymore.

Draw on HTML5 Canvas using a mouse

Let me know if you have trouble implementing this. It uses processing.js and has features for changing colors and making the draw point larger and smaller.

<html>
<head>
<!--script librarires-->
<script type="text/javascript" src="processing.js"></script>
<script type="text/javascript" src="init.js"></script>

<!--styles -->
<style type="text/css" src="stylesheet.css">
</style> 
</head>
<body>
<!--toolbox -->
<div id="draggable toolbox"></div>
<script type="application/processing">
// new script
int prevx, prevy;
int newx, newy;
boolean cliked;
color c1 = #000000;
int largeur=2;
int ps = 20;
int px = 50;
int py = 50;

void setup() {
size(500,500);
frameRate(25);
background(50);

 prevx = mouseX;
 prevy = mouseY;
 cliked = false;
 }

void draw() {
 //couleur
 noStroke(0);
 fill(#FFFFFF);//blanc
rect(px, py, ps, ps);
 fill(#000000);
 rect(px, py+(ps), ps, ps);
 fill(#FF0000);
 rect(px, py+(ps*2), ps, ps);
 fill(#00FF00);
 rect(px, py+(ps*3), ps, ps);
 fill(#FFFF00);
 rect(px, py+(ps*4), ps, ps);
 fill(#0000FF);
 rect(px, py+(ps*5), ps, ps);
 //largeur
 fill(#FFFFFF);
 rect(px, py+(ps*7), ps, ps);
  fill(#FFFFFF);
 rect(px, py+(ps*8), ps, ps);
 stroke(#000000);
 line(px+2, py+(ps*7)+(ps/2), px+(ps-2), py+(ps*7)+(ps/2));
 line(px+(ps/2), py+(ps*7)+1, px+(ps/2), py+(ps*8)-1);
 line(px+2, py+(ps*8)+(ps/2), px+(ps-2), py+(ps*8)+(ps/2));

 if(cliked==false){
  prevx = mouseX;
 prevy = mouseY;  
 }
 if(mousePressed) { 
  cliked = true;
 newx = mouseX;
  newy = mouseY;
  strokeWeight(largeur);
  stroke(c1);
  line(prevx, prevy, newx, newy);
  prevx = newx;
 prevy = newy;
 }else{
  cliked= false;
  }
}
void mouseClicked() {
 if (mouseX>=px && mouseX<=(px+ps)){
  //couleur
  if (mouseY>=py && mouseY<=py+(ps*6)){ 
   c1 = get(mouseX, mouseY);
  }
   //largeur
  if (mouseY>=py+(ps*7) && mouseY<=py+(ps*8)){ 
   largeur += 2;
  }
 if (mouseY>=py+(ps*8) && mouseY<=py+(ps*9)){ 
   if (largeur>2){
    largeur -= 2;
   }
  }
 }
}
</script><canvas></canvas>
</body>
</html>

Flutter.io Android License Status Unknown

For someone who is still facing the issue:
As answered below by Tommie C, Aba and few other people, but may not be clear enough as I found it.
Try installing java 1.8 manually as described here on windows/linux: [https://www3.ntu.edu.sg/home/ehchua/programming/howto/JDK_Howto.html]
and setting $JAVA_HOME variable(jdk path).
On windows set jdk path($JAVA_HOME) : [How to set java_home on Windows 7?.
On linux: [https://askubuntu.com/questions/175514/how-to-set-java-home-for-java].
Then run flutter doctor --android-licenses and accept all the licenses. Hope it helps.

Finding local maxima/minima with Numpy in a 1D numpy array

import numpy as np
x=np.array([6,3,5,2,1,4,9,7,8])
y=np.array([2,1,3,5,3,9,8,10,7])
sortId=np.argsort(x)
x=x[sortId]
y=y[sortId]
minm = np.array([])
maxm = np.array([])
i = 0
while i < length-1:
    if i < length - 1:
        while i < length-1 and y[i+1] >= y[i]:
            i+=1

        if i != 0 and i < length-1:
            maxm = np.append(maxm,i)

        i+=1

    if i < length - 1:
        while i < length-1 and y[i+1] <= y[i]:
            i+=1

        if i < length-1:
            minm = np.append(minm,i)
        i+=1


print minm
print maxm

minm and maxm contain indices of minima and maxima, respectively. For a huge data set, it will give lots of maximas/minimas so in that case smooth the curve first and then apply this algorithm.

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

How to get summary statistics by group

There's many different ways to go about this, but I'm partial to describeBy in the psych package:

describeBy(df$dt, df$group, mat = TRUE) 

Java enum - why use toString instead of name

A practical example when name() and toString() make sense to be different is a pattern where single-valued enum is used to define a singleton. It looks surprisingly at first but makes a lot of sense:

enum SingletonComponent {
    INSTANCE(/*..configuration...*/);

    /* ...behavior... */

    @Override
    String toString() {
      return "SingletonComponent"; // better than default "INSTANCE"
    }
}

In such case:

SingletonComponent myComponent = SingletonComponent.INSTANCE;
assertThat(myComponent.name()).isEqualTo("INSTANCE"); // blah
assertThat(myComponent.toString()).isEqualTo("SingletonComponent"); // better

How to iterate through table in Lua?

If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.

arr = {}
apples = {'a', "red", 5 }
arr.apples = apples
arr[1] = apples

This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):

for k,v in pairs(t) do
 print(k,v)
end

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

Access images inside public folder in laravel

Just use public_path() it will find public folder and address it itself.

<img src=public_path().'/images/imagename.jpg' >

Angular2: custom pipe could not be found

If you are declaring your pipe in another module, make sure to add it to that module Declarations and Exports array, then import that module in whatever module is consuming that pipe.

Clear Cache in Android Application programmatically

I think you're supposed to place clearApplicationData() before the super.OnDestroy().

Your app can't process any methods when it has been shut down.

How do I set/unset a cookie with jQuery?

You can use a plugin available here..

https://plugins.jquery.com/cookie/

and then to write a cookie do $.cookie("test", 1);

to access the set cookie do $.cookie("test");

How to change values in a tuple?

based on Jon's Idea and dear Trufa

def modifyTuple(tup, oldval, newval):
    lst=list(tup)
    for i in range(tup.count(oldval)):
        index = lst.index(oldval)
        lst[index]=newval

    return tuple(lst)

print modTupByIndex((1, 1, 3), 1, "a")

it changes all of your old values occurrences

Best way to alphanumeric check in JavaScript

Check it with a regex.

Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:

if (!input_string.match(/^[0-9a-z]+$/))
  show_error_or_something()

Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.

More information on Javascript regexen here: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Declaring a variable and setting its value from a SELECT query in Oracle

SELECT INTO

DECLARE
   the_variable NUMBER;

BEGIN
   SELECT my_column INTO the_variable FROM my_table;
END;

Make sure that the query only returns a single row:

By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row

If no rows are returned, PL/SQL raises NO_DATA_FOUND. You can guard against this exception by selecting the result of an aggregate function, such as COUNT(*) or AVG(), where practical. These functions are guaranteed to return a single value, even if no rows match the condition.

A SELECT ... BULK COLLECT INTO statement can return multiple rows. You must set up collection variables to hold the results. You can declare associative arrays or nested tables that grow as needed to hold the entire result set.

The implicit cursor SQL and its attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN provide information about the execution of a SELECT INTO statement.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Your import has a subtle error:

import java.awt.List;

It should be:

import java.util.List;

The problem is that both awt and Java's util package provide a class called List. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList extends java.util.List, not java.awt.List so if it wasn't for the generics, it would have still been a problem.

Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.

import org.omg.DynamicAny.NameValuePair;

should be

import org.apache.http.NameValuePair

nameValuePairs now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity, which is List<? extends NameValuePair>, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair did not extend org.apache.http.NameValuePair and the shortened type name NameValuePair evaluated to org.omg... in your file, but org.apache... in their code.

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

As he didn't specify which version of SQL server he uses (date type isn't available in 2005), one could also use

SELECT CONVERT(VARCHAR(10),date_column,112),SUM(num_col) AS summed
FROM table_name
GROUP BY CONVERT(VARCHAR(10),date_column,112)

Angular 4 HttpClient Query Parameters

You can pass it like this

let param: any = {'userId': 2};
this.http.get(`${ApiUrl}`, {params: param})

Multiline TextBox multiple newline

When page IsPostback, the following code work correctly. But when page first loading, there is not multiple newline in the textarea. Bug

textBox1.Text = "Line1\r\n\r\n\r\nLine2";

fill an array in C#

you could write an extension method

public static void Fill<T>(this T[] array, T value)
{
  for(int i = 0; i < array.Length; i++) 
  {
     array[i] = value;
  }
}

Nullable types: better way to check for null or zero in c#

You code sample will fail. If obj is null then the obj.ToString() will result in a null reference exception. I'd short cut the process and check for a null obj at the start of your helper function. As to your actual question, what's the type you're checking for null or zero? On String there's a great IsNullOrEmpty function, seems to me this would be a great use of extension methods to implement an IsNullOrZero method on the int? type.

Edit: Remember, the '?' is just compiler sugar for the INullable type, so you could probably take an INullable as the parm and then jsut compare it to null (parm == null) and if not null compare to zero.

Find length (size) of an array in jquery

obj={};

$.each(obj, function (key, value) {
    console.log(key+ ' : ' + value); //push the object value
});

for (var i in obj) {
    nameList += "" + obj[i] + "";//display the object value
}

$("id/class").html($(nameList).length);//display the length of object.

Resolve Git merge conflicts in favor of their changes during a pull

Please not that sometimes this will not work:

git checkout --ours path/to/file

or

git checkout --theirs path/to/file

I did this instead, assuming HEAD is ours and MERGE_HEAD is theirs

git checkout HEAD -- path/to/file

or:

git checkout MERGE_HEAD -- path/to/file

After we do this and we are good:

git add .

If you want to understand more, see wonderful post of torek here : git checkout --ours does not remove files from unmerged files list

Changes in import statement python3

Added another case to Michal Górny's answer:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

How to save user input into a variable in html and js

Like I use on PHP and JavaScript:

<input type="hidden" id="CatId" value="<?php echo $categoryId; ?>">

Update the JavaScript:

var categoryId = document.getElementById('CatId').value;

ASP.NET set hiddenfield a value in Javascript

I suspect you need to use ClientID rather than the literal ID string in your JavaScript code, since you've marked the field as runat="server".

E.g., if your JavaScript code is in an aspx file (not a separate JavaScript file):

var val = document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value;

If it's in a separate JavaScript file that isn't rendered by the ASP.Net stuff, you'll have to find it another way, such as by class.

Can an AWS Lambda function call another

I was looking at cutting out SNS until I saw this in the Lambda client docs (Java version):

Client for accessing AWS Lambda. All service calls made using this client are blocking, and will not return until the service call completes.

So SNS has an obvious advantage: it's asynchronous. Your lambda won't wait for the subsequent lambda to complete.

Should __init__() call the parent class's __init__()?

IMO, you should call it. If your superclass is object, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__ itself, for example when it has no (additional) internal state to initialize.

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>

Best Practices for Custom Helpers in Laravel 5

instead of including your custom helper class, you can actually add to your config/app.php file under aliases.

should be look like this.

 'aliases' => [ 
    ...
    ...
    'Helper' => App\Http\Services\Helper::class,
 ]

and then to your Controller, include the Helper using the method 'use Helper' so you can simply call some of the method on your Helper class.

eg. Helper::some_function();

or in resources view you can directly call the Helper class already.

eg. {{Helper::foo()}}

But this is still the developer coding style approach to be followed. We may have different way of solving problems, and i just want to share what i have too for beginners.

How to create a database from shell command?

Use

$ mysqladmin -u <db_user_name> -p create <db_name>

You will be prompted for password. Also make sure the mysql user you use has privileges to create database.

How to display tables on mobile using Bootstrap?

All tables within bootstrap stretch according to the container they're in. You can put your tables inside a .span element to control the size. This SO Question may help you out

Why do Twitter Bootstrap tables always have 100% width?

Convert .cer certificate to .jks

keytool comes with the JDK installation (in the bin folder):

keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"

This will create a new keystore and add just your certificate to it.

So, you can't convert a certificate to a keystore: you add a certificate to a keystore.

Git - how delete file from remote repository

  1. If you want to push a deleted file to remote

git add 'deleted file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote and locally

git rm 'file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote only

git rm --cached 'file name'

git commit -m'message'

git push -u origin branch

html select option separator

You could use the em dash "—". It has no visible spaces between each character.
(In some fonts!)

In HTML:

<option value="—————————————" disabled>—————————————</option>

Or in XHTML:

<option value="—————————————" disabled="disabled">—————————————</option>

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

You can use this small library: https://github.com/ledfusion/php-rest-curl

Making a call is as simple as:

// GET
$result = RestCurl::get($URL, array('id' => 12345678));

// POST
$result = RestCurl::post($URL, array('name' => 'John'));

// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));

// DELETE
$result = RestCurl::delete($URL); 

And for the $result variable:

  • $result['status'] is the HTTP response code
  • $result['data'] an array with the JSON response parsed
  • $result['header'] a string with the response headers

Hope it helps

Resize font-size according to div size

Here's a SCSS version of @Patrick's mixin.

$mqIterations: 19;
@mixin fontResize($iterations)
{
  $i: 1;
  @while $i <= $iterations
  {
    @media all and (min-width: 100px * $i) {
      body { font-size:0.2em * $i; }
    }
    $i: $i + 1;
  }
}
@include fontResize($mqIterations);

Remove sensitive files and their commits from Git history

For all practical purposes, the first thing you should be worried about is CHANGING YOUR PASSWORDS! It's not clear from your question whether your git repository is entirely local or whether you have a remote repository elsewhere yet; if it is remote and not secured from others you have a problem. If anyone has cloned that repository before you fix this, they'll have a copy of your passwords on their local machine, and there's no way you can force them to update to your "fixed" version with it gone from history. The only safe thing you can do is change your password to something else everywhere you've used it.


With that out of the way, here's how to fix it. GitHub answered exactly that question as an FAQ:

Note for Windows users: use double quotes (") instead of singles in this command

git filter-branch --index-filter \
'git update-index --remove PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA' <introduction-revision-sha1>..HEAD
git push --force --verbose --dry-run
git push --force

Update 2019:

This is the current code from the FAQ:

  git filter-branch --force --index-filter \
  "git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" \
  --prune-empty --tag-name-filter cat -- --all
  git push --force --verbose --dry-run
  git push --force

Keep in mind that once you've pushed this code to a remote repository like GitHub and others have cloned that remote repository, you're now in a situation where you're rewriting history. When others try pull down your latest changes after this, they'll get a message indicating that the changes can't be applied because it's not a fast-forward.

To fix this, they'll have to either delete their existing repository and re-clone it, or follow the instructions under "RECOVERING FROM UPSTREAM REBASE" in the git-rebase manpage.

Tip: Execute git rebase --interactive


In the future, if you accidentally commit some changes with sensitive information but you notice before pushing to a remote repository, there are some easier fixes. If you last commit is the one to add the sensitive information, you can simply remove the sensitive information, then run:

git commit -a --amend

That will amend the previous commit with any new changes you've made, including entire file removals done with a git rm. If the changes are further back in history but still not pushed to a remote repository, you can do an interactive rebase:

git rebase -i origin/master

That opens an editor with the commits you've made since your last common ancestor with the remote repository. Change "pick" to "edit" on any lines representing a commit with sensitive information, and save and quit. Git will walk through the changes, and leave you at a spot where you can:

$EDITOR file-to-fix
git commit -a --amend
git rebase --continue

For each change with sensitive information. Eventually, you'll end up back on your branch, and you can safely push the new changes.

Laravel Request::all() Should Not Be Called Statically

The facade is another Request class, access it with the full path:

$input = \Request::all();

From laravel 5 you can also access it through the request() function:

$input = request()->all();

Why is my CSS bundling not working with a bin deployed MVC4 app?

The CSS and Script bundling should work regardless if .NET is running 4.0 or 4.5. I am running .NET 4.0 and it works fine for me. However in order to get the minification and bundling behavior to work your web.config must be set to not be running in debug mode.

<compilation debug="false" targetFramework="4.0">

Take this bundle for jQuery UI example in the _Layout.cshtml file.

@Styles.Render("~/Content/themes/base/css")

If I run with debug="true" I get the following HTML.

<link href="/Content/themes/base/jquery.ui.core.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.resizable.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.selectable.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.accordion.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.autocomplete.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.button.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.dialog.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.slider.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.tabs.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.datepicker.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.progressbar.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.theme.css" rel="stylesheet"/>

But if I run with debug="false". I'll get this instead.

<link href="/Content/themes/base/css?v=myqT7npwmF2ABsuSaHqt8SCvK8UFWpRv7T4M8r3kiK01" rel="stylesheet"/>

This is a feature so you can easily debug problems with your Script and CSS files. I'm using the MVC4 RTM.

If you think it might be an MVC dependency problem, I'd recommend going into Nuget and removing all of your MVC related packages, and then search for the Microsoft.AspNet.Mvc package and install it. I'm using the most recent version and it's coming up as v.4.0.20710.0. That should grab all the dependencies you need.

Also if you used to be using MVC3 and are now trying to use MVC4 you'll want to go into your web.config(s) and update their references to point to the 4.0 version of MVC. If you're not sure, you can always create a fresh MVC4 app and copy the web.config from there. Don't forget the web.config in your Views/Areas folders if you do.

UPDATE: I've found that what you need to have is the Nuget package Microsoft.AspNet.Web.Optimization installed in your project. It's included by default in an MVC4 RTM app regardless if you specify the target framework as 4.5 or 4.0. This is the namespace that the bundling classes are included in, and doesn't appear to be dependent on the framework. I've deployed to a server that does not have 4.5 installed and it still works as expected for me. Just make sure the DLL gets deployed with the rest of your app.

Reading data from a website using C#

 WebClient client = new WebClient();
            using (Stream data = client.OpenRead(Text))
            {
                using (StreamReader reader = new StreamReader(data))
                {
                    string content = reader.ReadToEnd();
                    string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
                    MatchCollection matches = Regex.Matches(content,pattern);
                    List<string> urls = new List<string>();
                    foreach (Match match in matches)
                    {
                            urls.Add(match.Value);
                    }

              }

Check with jquery if div has overflowing elements

Partially based on Mohsen's answer (the added first condition covers the case where the child is hidden before the parent):

jQuery.fn.isChildOverflowing = function (child) {
  var p = jQuery(this).get(0);
  var el = jQuery(child).get(0);
  return (el.offsetTop < p.offsetTop || el.offsetLeft < p.offsetLeft) ||
    (el.offsetTop + el.offsetHeight > p.offsetTop + p.offsetHeight || el.offsetLeft + el.offsetWidth > p.offsetLeft + p.offsetWidth);
};

Then just do:

jQuery('#parent').isChildOverflowing('#child');

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

This happened to me on Windows 10 and VS 2013. Apparently there is a maximum port number IIS Express handles. Ports above 62546 don't work for me.

How can I check if the current date/time is past a set date/time?

date_default_timezone_set('Asia/Kolkata');

$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
    echo "active";exit;
}else{
    echo "inactive";exit;
}

How to replace multiple substrings of a string?

You can use the pandas library and the replace function which supports both exact matches as well as regex replacements. For example:

df = pd.DataFrame({'text': ['Billy is going to visit Rome in November', 'I was born in 10/10/2010', 'I will be there at 20:00']})

to_replace=['Billy','Rome','January|February|March|April|May|June|July|August|September|October|November|December', '\d{2}:\d{2}', '\d{2}/\d{2}/\d{4}']
replace_with=['name','city','month','time', 'date']

print(df.text.replace(to_replace, replace_with, regex=True))

And the modified text is:

0    name is going to visit city in month
1                      I was born in date
2                 I will be there at time

You can find an example here. Notice that the replacements on the text are done with the order they appear in the lists

How to implement __iter__(self) for a container object (Python)

If your object contains a set of data you want to bind your object's iter to, you can cheat and do this:

>>> class foo:
    def __init__(self, *params):
           self.data = params
    def __iter__(self):
        if hasattr(self.data[0], "__iter__"):
            return self.data[0].__iter__()
        return self.data.__iter__()
>>> d=foo(6,7,3,8, "ads", 6)
>>> for i in d:
    print i
6
7
3
8
ads
6

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Now there is official FAQ for using Google Play in How do I install Google Play Services?, here the FAQ text:

For intellectual property reasons, Google Play Services are not included by default in Genymotion virtual devices. However, if you really need them, you can use the packages provided by OpenGapps. Simply follow these steps:

  1. Visit opengapps.org
  2. Select x86 as platform
  3. Choose the Android version corresponding to your virtual device
  4. Select nano as variant
  5. Download the zip file
  6. Drag & Drop the zip installer in new Genymotion virtual device (2.7.2 and above only)
  7. Follow the pop-up instructions

Please note Genymobile Inc. and Genymotion assume no liability whatsoever resulting from the download, install and use of Google Play Services within your virtual devices. You are solely responsible for the use and assume all liability related thereto. Moreover, we disclaim any warranties of any kind for a particular purpose regarding the compatibility of the OpenGapps packages with any version of Genymotion.

Get value from SimpleXMLElement Object

foreach($xml->code as $vals )
{ 
    unset($geonames);
    $vals=(array)$vals;
    foreach($vals as $key => $value)
      {
        $value=(array)$value;
        $geonames[$key]=$value[0];
      }
}
print_r($geonames);

How to config Tomcat to serve images from an external folder outside webapps?

You could have a redirect servlet. In you web.xml you'd have:

<servlet>
    <servlet-name>images</servlet-name>
    <servlet-class>com.example.images.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>images</servlet-name>
    <url-pattern>/images/*</url-pattern>
</servlet-mapping>

All your images would be in "/images", which would be intercepted by the servlet. It would then read in the relevant file in whatever folder and serve it right back out. For example, say you have a gif in your images folder, c:\Server_Images\smilie.gif. In the web page would be <img src="http:/example.com/app/images/smilie.gif".... In the servlet, HttpServletRequest.getPathInfo() would yield "/smilie.gif". Which the servlet would find in the folder.

how to install Lex and Yacc in Ubuntu?

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

sudo apt-get install bison flex

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

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

For me following worked:

in directive declare it like this:

.directive('myDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            myFunction: '=',
        },
        templateUrl: 'myDirective.html'
    };
})  

In directive template use it in following way:

<select ng-change="myFunction(selectedAmount)">

And then when you use the directive, pass the function like this:

<data-my-directive
    data-my-function="setSelectedAmount">
</data-my-directive>

You pass the function by its declaration and it is called from directive and parameters are populated.

How do I query for all dates greater than a certain date in SQL Server?

We can use like below as well

SELECT * 
FROM dbo.March2010 A
WHERE CAST(A.Date AS Date) >= '2017-03-22';

SELECT * 
    FROM dbo.March2010 A
    WHERE CAST(A.Date AS Datetime) >= '2017-03-22 06:49:53.840';

Jenkins, specifying JAVA_HOME

I was facing the same issue and for me downgrading the JAVA_HOME from jdk12 was not the plausible option like said in the answer. So I did a trial and error experiment and I got the Jenkins running without even downgrading the version of JAVA_HOME.

Steps:

  • open configuration $ sudo vi /etc/init.d/jenkins
  • Comment following line:
 #JAVA=`type -p java`
  • Introduced the line mentioned below. (Note: Insert the specific path of JDK in your machine.)
 JAVA=`type -p /usr/lib/jdk8/bin/java`
  • Reload systemd manager configuration: $ sudo systemctl daemon-reload
  • Start Jenkins service: $ sudo systemctl start jenkins
    ? jenkins.service - LSB: Start Jenkins at boot time
       Loaded: loaded (/etc/init.d/jenkins; generated)
       Active: active (exited) since Sun 2020-05-31 21:05:30 CEST; 9min ago
         Docs: man:systemd-sysv-generator(8)
      Process: 9055 ExecStart=/etc/init.d/jenkins start (code=exited, status=0/SUCCESS)
    

Change the background color of a pop-up dialog

You can create a custom alertDialog and use a xml layout. in the layout, you can set the background color and textcolor.

Something like this:

Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);

How to use sed/grep to extract text between two words?

This might work for you (GNU sed):

sed '/Here/!d;s//&\n/;s/.*\n//;:a;/String/bb;$!{n;ba};:b;s//\n&/;P;D' file 

This presents each representation of text between two markers (in this instance Here and String) on a newline and preserves newlines within the text.

Git 'fatal: Unable to write new index file'

The error message fatal: Unable to write new index file means that we could not write the new content to the git index file .git\index (See here for more information about git index). After reviewing all the answers to this question, I summarize the following root causes:

  • The size of new content exceeds the disk available capacity. (Solution: Clean the disk spaces)
  • Users do not have access right to this file. (Solution: Grant the permission)
  • Users have permission but .git\index is locked by other users or processes. (Solution: Unlock the file)

The link Find out which process is locking a file or folder in Windows specifies the following approach to find out the process which is locking a specific file:

SysInternals Process Explorer - Go to Find > Find Handle or DLL. In the "Handle or DLL substring:" text box, type the path to the file (e.g. "C:\path\to\file.txt") and click "Search". All processes which have an open handle to that file should be listed.

Use the above approach to find which process locked .git\index and then stop the locking executable. This unlocks .git\index.

For example, Process Explorer Search shows that .git\index is locked by vmware-vmx.exe. Suspending the VMWare Player virtual machine (which accessed the git repo via a shared folder) solved the issue.

What do the python file extensions, .pyc .pyd .pyo stand for?

  • .py - Regular script
  • .py3 - (rarely used) Python3 script. Python3 scripts usually end with ".py" not ".py3", but I have seen that a few times
  • .pyc - compiled script (Bytecode)
  • .pyo - optimized pyc file (As of Python3.5, Python will only use pyc rather than pyo and pyc)
  • .pyw - Python script to run in Windowed mode, without a console; executed with pythonw.exe
  • .pyx - Cython src to be converted to C/C++
  • .pyd - Python script made as a Windows DLL
  • .pxd - Cython script which is equivalent to a C/C++ header
  • .pxi - MyPy stub
  • .pyi - Stub file (PEP 484)
  • .pyz - Python script archive (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .pywz - Python script archive for MS-Windows (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .py[cod] - wildcard notation in ".gitignore" that means the file may be ".pyc", ".pyo", or ".pyd".
  • .pth - a path configuration file; its contents are additional items (one per line) to be added to sys.path. See site module.

A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/

Easiest way to convert a List to a Set in Java

If you use the Guava library:

Set<Foo> set = Sets.newHashSet(list);

or, better:

Set<Foo> set = ImmutableSet.copyOf(list);

What are some good Python ORM solutions?

I used Storm + SQLite for a small project, and was pretty happy with it until I added multiprocessing. Trying to use the database from multiple processes resulted in a "Database is locked" exception. I switched to SQLAlchemy, and the same code worked with no problems.

HTML5 Pre-resize images before uploading

Correction to above:

<img src="" id="image">
<input id="input" type="file" onchange="handleFiles()">
<script>

function handleFiles()
{
    var filesToUpload = document.getElementById('input').files;
    var file = filesToUpload[0];

    // Create an image
    var img = document.createElement("img");
    // Create a file reader
    var reader = new FileReader();
    // Set the image once loaded into file reader
    reader.onload = function(e)
    {
        img.src = e.target.result;

        var canvas = document.createElement("canvas");
        //var canvas = $("<canvas>", {"id":"testing"})[0];
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var MAX_WIDTH = 400;
        var MAX_HEIGHT = 300;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);

        var dataurl = canvas.toDataURL("image/png");
        document.getElementById('image').src = dataurl;     
    }
    // Load files into file reader
    reader.readAsDataURL(file);


    // Post the data
    /*
    var fd = new FormData();
    fd.append("name", "some_filename.jpg");
    fd.append("image", dataurl);
    fd.append("info", "lah_de_dah");
    */
}</script>

How to check undefined in Typescript

Use 'this' keyword to access variable. This worked for me

var  uemail = localStorage.getItem("useremail");

if (typeof this.uemail === "undefined")
{
    alert('undefined');
}
else
{
    alert('defined');
}

What is the difference between require() and library()?

Always use library. Never use require.

In a nutshell, this is because, when using require, your code might yield different, erroneous results, without signalling an error. This is rare but not hypothetical! Consider this code, which yields different results depending on whether {dplyr} can be loaded:

require(dplyr)

x = data.frame(y = seq(100))
y = 1
filter(x, y == 1)

This can lead to subtly wrong results. Using library instead of require throws an error here, signalling clearly that something is wrong. This is good.

It also makes debugging all other failures more difficult: If you require a package at the start of your script and use its exports in line 500, you’ll get an error message “object ‘foo’ not found” in line 500, rather than an error “there is no package called ‘bla’”.

The only acceptable use case of require is when its return value is immediately checked, as some of the other answers show. This is a fairly common pattern but even in these cases it is better (and recommended, see below) to instead separate the existence check and the loading of the package. That is: use requireNamespace instead of require in these cases.

More technically, require actually calls library internally (if the package wasn’t already attached — require thus performs a redundant check, because library also checks whether the package was already loaded). Here’s a simplified implementation of require to illustrate what it does:

require = function (package) {
    already_attached = paste('package:', package) %in% search()
    if (already_attached) return(TRUE)
    maybe_error = try(library(package, character.only = TRUE)) 
    success = ! inherits(maybe_error, 'try-error')
    if (! success) cat("Failed")
    success
}

Experienced R developers agree:

Yihui Xie, author of {knitr}, {bookdown} and many other packages says:

Ladies and gentlemen, I've said this before: require() is the wrong way to load an R package; use library() instead

Hadley Wickham, author of more popular R packages than anybody else, says

Use library(x) in data analysis scripts. […] You never need to use require() (requireNamespace() is almost always better)

Javascript how to split newline

The simplest and safest way to split a string using new lines, regardless of format (CRLF, LFCR or LF), is to remove all carriage return characters and then split on the new line characters. "text".replace(/\r/g, "").split(/\n/);

This ensures that when you have continuous new lines (i.e. \r\n\r\n, \n\r\n\r, or \n\n) the result will always be the same.

In your case the code would look like:

(function ($) {
    $(document).ready(function () {
        $('#data').submit(function (e) {
            var ks = $('#keywords').val().replace(/\r/g, "").split(/\n/);
            e.preventDefault();
            alert(ks[0]);
            $.each(ks, function (k) {
                alert(k);
            });
        });
    });
})(jQuery);

Here are some examples that display the importance of this method:

_x000D_
_x000D_
var examples = ["Foo\r\nBar", "Foo\r\n\r\nBar", "Foo\n\r\n\rBar", "Foo\nBar\nFooBar"];_x000D_
_x000D_
examples.forEach(function(example) {_x000D_
  output(`Example "${example}":`);_x000D_
  output(`Split using "\n": "${example.split("\n")}"`);_x000D_
  output(`Split using /\r?\n/: "${example.split(/\r?\n/)}"`);_x000D_
  output(`Split using /\r\n|\n|\r/: "${example.split(/\r\n|\n|\r/)}"`);_x000D_
  output(`Current method: ${example.replace(/\r/g, "").split("\n")}`);_x000D_
  output("________");_x000D_
});_x000D_
_x000D_
function output(txt) {_x000D_
  console.log(txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r"));_x000D_
}
_x000D_
_x000D_
_x000D_

C# Public Enums in Classes

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

ADB.exe is obsolete and has serious performance problems

Try update your SDK Tools items, and then delete all currently created emulator and recreate again. it works for me

How do I handle the window close event in Tkinter?

If you want to change what the x button does or make it so that you cannot close it at all try this.

yourwindow.protocol("WM_DELETE_WINDOW", whatever)

then defy what "whatever" means

def whatever():
    #Replace this with what you want python to do when the user hits the x button

You can also make it so that when you close that window you can call it back like this

yourwindow.withdraw() 

This hides the window but does not close it

yourwindow.deiconify()

This makes the window visible again

'"SDL.h" no such file or directory found' when compiling

header file lives at

/usr/include/SDL/SDL.h

       __OR__

/usr/include/SDL2/SDL.h  #  for SDL2

in your c++ code pull in this header using

#include <SDL.h>

       __OR__

#include <SDL2/SDL.h>    // for SDL2

you have the correct usage of

sdl-config --cflags --libs

       __OR__

sdl2-config --cflags --libs   #  sdl2

which will give you

-I/usr/include/SDL -D_GNU_SOURCE=1 -D_REENTRANT
-L/usr/lib/x86_64-linux-gnu -lSDL

       __OR__

-I/usr/include/SDL2 -D_REENTRANT
-lSDL2

at times you may also see this usage which works for a standard install

pkg-config --cflags --libs sdl

       __OR__

pkg-config --cflags --libs sdl2   #  sdl2

which supplies you with

-D_GNU_SOURCE=1 -D_REENTRANT -I/usr/include/SDL -lSDL

       __OR__

-D_REENTRANT -I/usr/include/SDL2 -lSDL2   #  SDL2

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

How to align input forms in HTML

You should use a table. As a matter of logical structure the data is tabular: this is why you want it to align, because you want to show that the labels are not related solely to their input boxes but also to each other, in a two-dimensional structure.

[consider what you would do if you had string or numeric values to display instead of input boxes.]

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

Wrap long lines in Python

I'd probably split the long statement up into multiple shorter statements so that the program logic is separated from the definition of the long string:

>>> def fun():
...     format_string = '{0} Here is a really long ' \
...                     'sentence with {1}'
...     print format_string.format(3, 5)

If the string is only just too long and you choose a short variable name then by doing this you might even avoid having to split the string:

>>> def fun():
...     s = '{0} Here is a really long sentence with {1}'
...     print s.format(3, 5)

Programmatically add custom event in the iPhone Calendar

Based on Apple Documentation, this has changed a bit as of iOS 6.0.

1) You should request access to the user's calendar via "requestAccessToEntityType:completion:" and execute the event handling inside of a block.

2) You need to commit your event now or pass the "commit" param to your save/remove call

Everything else stays the same...

Add the EventKit framework and #import <EventKit/EventKit.h> to your code.

In my example, I have a NSString *savedEventId instance property.

To add an event:

    EKEventStore *store = [EKEventStore new];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent *event = [EKEvent eventWithEventStore:store];
        event.title = @"Event Title";
        event.startDate = [NSDate date]; //today
        event.endDate = [event.startDate dateByAddingTimeInterval:60*60];  //set 1 hour meeting
        event.calendar = [store defaultCalendarForNewEvents];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
        self.savedEventId = event.eventIdentifier;  //save the event id if you want to access this later
    }];

Remove the event:

    EKEventStore* store = [EKEventStore new];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent* eventToRemove = [store eventWithIdentifier:self.savedEventId];
        if (eventToRemove) {
            NSError* error = nil;
            [store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error];
        }
    }];

This adds events to your default calendar, if you have multiple calendars then you'll have find out which one that is

Swift version

You need to import the EventKit framework

import EventKit

Add event

let store = EKEventStore()
store.requestAccessToEntityType(.Event) {(granted, error) in
    if !granted { return }
    var event = EKEvent(eventStore: store)
    event.title = "Event Title"
    event.startDate = NSDate() //today
    event.endDate = event.startDate.dateByAddingTimeInterval(60*60) //1 hour long meeting
    event.calendar = store.defaultCalendarForNewEvents
    do {
        try store.saveEvent(event, span: .ThisEvent, commit: true)
        self.savedEventId = event.eventIdentifier //save event id to access this particular event later
    } catch {
        // Display error to user
    }
}

Remove event

let store = EKEventStore()
store.requestAccessToEntityType(EKEntityTypeEvent) {(granted, error) in
    if !granted { return }
    let eventToRemove = store.eventWithIdentifier(self.savedEventId)
    if eventToRemove != nil {
        do {
            try store.removeEvent(eventToRemove, span: .ThisEvent, commit: true)
        } catch {
            // Display error to user
        }
    }
}

How to get query string parameter from MVC Razor markup?

For Asp.net Core 2

ViewContext.ModelState["id"].AttemptedValue

Environment Specific application.properties file in Spring Boot application

Spring Boot already has support for profile based properties.

Simply add an application-[profile].properties file and specify the profiles to use using the spring.profiles.active property.

-Dspring.profiles.active=local

This will load the application.properties and the application-local.properties with the latter overriding properties from the first.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.

How to save and extract session data in codeigniter

In codeigniter we are able to store session values in a database. In the config.php file make the sess_use_database variable true

$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';

and create a ci_session table in the database

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);

For more details and reference, click here

How to correctly close a feature branch in Mercurial?

It is strange, that no one yet has suggested the most robust way of closing a feature branches... You can just combine merge commit with --close-branch flag (i.e. commit modified files and close the branch simultaneously):

hg up feature-x
hg merge default
hg ci -m "Merge feature-x and close branch" --close-branch
hg branch default -f

So, that is all. No one extra head on revgraph. No extra commit.

Can I call a constructor from another constructor (do constructor chaining) in C++?

No, in C++ you cannot call a constructor from a constructor. What you can do, as warren pointed out, is:

  • Overload the constructor, using different signatures
  • Use default values on arguments, to make a "simpler" version available

Note that in the first case, you cannot reduce code duplication by calling one constructor from another. You can of course have a separate, private/protected, method that does all the initialization, and let the constructor mainly deal with argument handling.

__init__() missing 1 required positional argument

If error is like Author=models.ForeignKey(User, related_names='blog_posts') TypeError:init() missing 1 required positional argument:'on_delete'

Then the solution will be like, you have to add one argument Author=models.ForeignKey(User, related_names='blog_posts', on_delete=models.DO_NOTHING)

HTML image not showing in Gmail

HTTP or HTTPS should be full address

background-image: url(http://fulladdress.com/ca/1/product_assets/T/C/X/M/K/NMTCXMK_mu.jpg)

var mailOptions = {
  from: '[email protected]',
  to: emails,
  subject: 'i super another ma node mailer cool test',
  text: 'That was easy!',
  html: '<a href="//google.com"><div style="background-image: url(http://fulladdress.com/ca/1/product_assets/T/C/X/M/K/NMTCXMK_mu.jpg);width:500px;height:500px">ascfas</div></a>'
};

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

How to sum the values of a JavaScript object?

_x000D_
_x000D_
let prices = {_x000D_
  "apple": 100,_x000D_
  "banana": 300,_x000D_
  "orange": 250_x000D_
};_x000D_
_x000D_
let sum = 0;_x000D_
for (let price of Object.values(prices)) {_x000D_
  sum += price;_x000D_
}_x000D_
_x000D_
alert(sum)
_x000D_
_x000D_
_x000D_

nodejs mysql Error: Connection lost The server closed the connection

I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.

Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.

tl;dr; Do not use this method.


A pragmatic solution is to force MySQL to keep the connection alive:

setInterval(function () {
    db.query('SELECT 1');
}, 5000);

I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST does not occur.

Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID() and mysql connection have been reset without you being aware about it?

However, this only ensures that connection time out (wait_timeout and interactive_timeout) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

  1. uninstall the x86 versions of VC 11 vcredist_x64/86.exe for 2012 and 2013
  2. uninstall WAMP Server 2.5
  3. delete (maybe back up first) the WAMP folder
  4. restart windows
  5. reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!

Differences between Lodash and Underscore.js

They are pretty similar, with Lodash is taking over...

They both are a utility library which takes the world of utility in JavaScript...

It seems Lodash is getting updated more regularly now, so more used in the latest projects...

Also Lodash seems is lighter by a couple of KBs...

Both have a good API and documentation, but I think the Lodash one is better...

Here is a screenshot for each of the documentation items for getting the first value of an array...

Underscore.js:

Underscore.js

Lodash:

Lodash

As things may get updated time to time, just check their website also...

Lodash

Underscore.js

Call a stored procedure with another in Oracle

Sure, you just call it from within the SP, there's no special syntax.

Ex:

   PROCEDURE some_sp
   AS
   BEGIN
      some_other_sp('parm1', 10, 20.42);
   END;

If the procedure is in a different schema than the one the executing procedure is in, you need to prefix it with schema name.

   PROCEDURE some_sp
   AS
   BEGIN
      other_schema.some_other_sp('parm1', 10, 20.42);
   END;

How to force Chrome browser to reload .css file while debugging in Visual Studio?

Just had this problem where one person running Chrome (on a Mac) suddenly stopped loading the CSS file. CMD + R did NOT work at all. I don't like the suggestions above that force a permanent reload on the production system.

What worked was changing the name of the CSS file in the HTML file (and renaming the CSS file of course). This forced Chrome to go get the latest CSS file.

Reading/parsing Excel (xls) files with Python

Using pandas:

import pandas as pd

xls = pd.ExcelFile(r"yourfilename.xls") #use r before absolute file path 

sheetX = xls.parse(2) #2 is the sheet number+1 thus if the file has only 1 sheet write 0 in paranthesis

var1 = sheetX['ColumnName']

print(var1[1]) #1 is the row number...

How to set String's font size, style in Java using the Font class?

Font myFont = new Font("Serif", Font.BOLD, 12);, then use a setFont method on your components like

JButton b = new JButton("Hello World");
b.setFont(myFont);

How does PHP 'foreach' actually work?

In example 3 you don't modify the array. In all other examples you modify either the contents or the internal array pointer. This is important when it comes to PHP arrays because of the semantics of the assignment operator.

The assignment operator for the arrays in PHP works more like a lazy clone. Assigning one variable to another that contains an array will clone the array, unlike most languages. However, the actual cloning will not be done unless it is needed. This means that the clone will take place only when either of the variables is modified (copy-on-write).

Here is an example:

$a = array(1,2,3);
$b = $a;  // This is lazy cloning of $a. For the time
          // being $a and $b point to the same internal
          // data structure.

$a[] = 3; // Here $a changes, which triggers the actual
          // cloning. From now on, $a and $b are two
          // different data structures. The same would
          // happen if there were a change in $b.

Coming back to your test cases, you can easily imagine that foreach creates some kind of iterator with a reference to the array. This reference works exactly like the variable $b in my example. However, the iterator along with the reference live only during the loop and then, they are both discarded. Now you can see that, in all cases but 3, the array is modified during the loop, while this extra reference is alive. This triggers a clone, and that explains what's going on here!

Here is an excellent article for another side effect of this copy-on-write behaviour: The PHP Ternary Operator: Fast or not?

Get all Attributes from a HTML element with Javascript/jQuery

Element.prototype.getA = function (a) {
        if (a) {
            return this.getAttribute(a);
        } else {
            var o = {};
            for(let a of this.attributes){
                o[a.name]=a.value;
            }
            return o;
        }
    }

having <div id="mydiv" a='1' b='2'>...</div> can use

mydiv.getA() // {id:"mydiv",a:'1',b:'2'}

Input text dialog Android

Sounds like a good opportunity to use an AlertDialog.

As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.

If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).

Within your class:

private String m_Text = "";

Within the OnClickListener of your button (or in a function called from there):

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");

// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);

// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    @Override
    public void onClick(DialogInterface dialog, int which) {
        m_Text = input.getText().toString();
    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

builder.show();

WPF TemplateBinding vs RelativeSource TemplatedParent

One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).

SelectedValue vs SelectedItem.Value of DropDownList

In droupDown list there are two item add property.

1) Text 2) value

If you want to get text property then u use selecteditem.text

and If you want to select value property then use selectedvalue property

In your case i thing both value and text property are the same so no matter if u use selectedvalue or selecteditem.text

If both are different then they give us different results

ImportError: No module named requests

I have had this issue a couple times in the past few months. I haven't seen a good solution for fedora systems posted, so here's yet another solution. I'm using RHEL7, and I discovered the following:

If you have urllib3 installed via pip, and requests installed via yum you will have issues, even if you have the correct packages installed. The same will apply if you have urllib3 installed via yum, and requests installed via pip. Here's what I did to fix the issue:

sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests

(confirm that all those libraries have been removed)

sudo yum install python-urllib3
sudo yum install python-requests

Just be aware that this will only work for systems that are running Fedora, Redhat, or CentOS.

Sources:
This very question (in the comments to this answer).
This github issue.

File content into unix variable with newlines

Just if someone is interested in another option:

content=( $(cat test.txt) )

a=0
while [ $a -le ${#content[@]} ]
do
        echo ${content[$a]}
        a=$[a+1]
done

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

Bluetooth pairing without user confirmation

BT version 2.0 or less - You should be able to pair/bond using a standard PIN code, entered programmatically e.g. 1234 or 0000. This is not very secure but many BT devices do this.

BT version 2.1 or greater - Mode 4 Secure Simple Pairing "just works" model can be used. It uses elliptical encryption (whatever that is) and is very secure but is open to Man In The Middle attacks. Compared to the old '0000' pin code approach it is light years ahead. This doesn't require any user input.

This is according to the Bluetooth specs but what you can use depends on what verson of the Bluetooth standard your stack supports and what API you have.

How do I instantiate a JAXBElement<String> object?

ObjectFactory fact = new ObjectFactory();   
JAXBElement<String> str = fact.createCompositeTypeStringValue("vik");    
comp.setStringValue(str);
CompositeType retcomp = service.getDataUsingDataContract(comp);
System.out.println(retcomp.getStringValue().getValue());

How to get just the parent directory name of a specific file

In Java 7 you have the new Paths api. The modern and cleanest solution is:

Paths.get("C:/aaa/bbb/ccc/ddd/test.java").getParent().getFileName();

Result would be:

C:/aaa/bbb/ccc/ddd

Writing an input integer into a cell

When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.

  1. The user types something in and clicks OK. This is what you expect to happen and you will receive input back that can be returned directly to a cell or a declared variable.
  2. The user clicks Cancel, presses Esc or clicks × (Close). The return value is a boolean False. This should be accounted for.
  3. The user does not type anything in but clicks OK regardless. The return value is a zero-length string.

If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.

    Dim returnVal As Variant

    returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")

    'if the user clicked Cancel, Close or Esc the False
    'is translated to the variant as a vbNullString
    Select Case True
        Case Len(returnVal) = 0
            'no value but user clicked OK - clear the target cell
            Range("A2").ClearContents
        Case Else
            'returned a value with OK, save it
            Range("A2") = returnVal
    End Select

¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.

Trigger change() event when setting <select>'s value with val() function

I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.

$('#selectField').change(function(){
    if($('#selectField').val() == 'N'){
        $('#secondaryInput').hide();
    } else {
        $('#secondaryInput').show();
}
});

Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".

$('#selectField').val(valueFromDatabase).change();

So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.

Change image size via parent div

Actually using 100% will not make the image bigger if the image is smaller than the div size you specified. You need to set one of the dimensions, height or width in order to have all images fill the space. In my experience it's better to have the height set so each row is the same size, then all items wrap to next line properly. This will produce an output similar to fotolia.com (stock image website)

with css:

parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 42px;
}

without:

<div style="height:42px;width:42px">
    <img style="height:42px" src="http://someimage.jpg">
</div>

Passing parameters on button action:@selector

You can sub-class a UIButton named MyButton, and pass the parameter by MyButton's properties.

Then, get the parameter back from (id)sender.

CREATE DATABASE permission denied in database 'master' (EF code-first)

Permission denied is a security so you need to add a "User" permission..

  1. Right click you database(which is .mdf file) and then properties
  2. Go to security tab
  3. Click Continue button
  4. Click Add button
  5. Click Advance button
  6. Another window will show, then you click the "Find Now" button on the right side.
  7. On the fields below, go to the bottom most and click the "Users". Click OK.
  8. Click the permission "Users" that you have been created, then Check the full control checkbox.

There you go. You have now permission to your database.

Note: The connection-string in the above questions is using SQL-server authentication. So, Before taking the above step, You have to login using windows-authentication first, and then you have to give permission to the user who is using sql-server authentication. Permission like "dbcreator".

if you login with SQL server authentication and trying to give permission to the user you logged in. it shows, permission denied error.

Full Screen DialogFragment in Android

the following solution worked for me other solution gave me some space in the sides i.e not full screen

You need to make changes in onStart and onCreate method

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null)
    {
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);
    }
}


 public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    final Dialog dialog = new Dialog(requireContext());
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
 }


   

Loading context in Spring using web.xml

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info

Why is Ant giving me a Unsupported major.minor version error

You would need to say which version of Ant and which JVM version.

You can run ant -v to see which settings Ant is using as per the doc

Ant 1.8* requires JDK 1.4 or higher.

The 'Unsupported major.minor version 51.0' means somewhere code was compiled for a version of the JDK, and that you are trying to run those classes under an older version of the JDK. (see here)

How do we control web page caching, across all browsers?

As @Kornel stated, what you want is not to deactivate the cache, but to deactivate the history buffer. Different browsers have their own subtle ways to disable the history buffer.

In Chrome (v28.0.1500.95 m) we can do this only by Cache-Control: no-store.

In FireFox (v23.0.1) any one of these will work:

  1. Cache-Control: no-store

  2. Cache-Control: no-cache (https only)

  3. Pragma: no-cache (https only)

  4. Vary: * (https only)

In Opera (v12.15) we only can do this by Cache-Control: must-revalidate (https only).

In Safari (v5.1.7, 7534.57.2) any one of these will work:

  1. Cache-Control: no-store
    <body onunload=""> in html

  2. Cache-Control: no-store (https only)

In IE8 (v8.0.6001.18702IC) any one of these will work:

  1. Cache-Control: must-revalidate, max-age=0

  2. Cache-Control: no-cache

  3. Cache-Control: no-store

  4. Cache-Control: must-revalidate
    Expires: 0

  5. Cache-Control: must-revalidate
    Expires: Sat, 12 Oct 1991 05:00:00 GMT

  6. Pragma: no-cache (https only)

  7. Vary: * (https only)

Combining the above gives us this solution which works for Chrome 28, FireFox 23, IE8, Safari 5.1.7, and Opera 12.15: Cache-Control: no-store, must-revalidate (https only)

Note that https is needed because Opera wouldn't deactivate history buffer for plain http pages. If you really can't get https and you are prepared to ignore Opera, the best you can do is this:

Cache-Control: no-store
<body onunload="">

Below shows the raw logs of my tests:

HTTP:

  1. Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  2. Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  3. Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    Fail: Safari 5.1.7, Opera 12.15
    Success: Chrome 28, FireFox 23, IE8

  4. Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    Fail: Safari 5.1.7, Opera 12.15
    Success: Chrome 28, FireFox 23, IE8

  5. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  6. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  7. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  8. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  9. Cache-Control: no-store
    Fail: Safari 5.1.7, Opera 12.15
    Success: Chrome 28, FireFox 23, IE8

  10. Cache-Control: no-store
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  11. Cache-Control: no-cache
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  12. Vary: *
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

  13. Pragma: no-cache
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

  14. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  15. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  16. Cache-Control: must-revalidate, max-age=0
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  17. Cache-Control: must-revalidate
    Expires: 0
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  18. Cache-Control: must-revalidate
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  19. Cache-Control: private, must-revalidate, proxy-revalidate, s-maxage=0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

HTTPS:

  1. Cache-Control: private, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    <body onunload="">
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

  2. Cache-Control: private, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    <body onunload="">
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

  3. Vary: *
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  4. Pragma: no-cache
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  5. Cache-Control: no-cache
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  6. Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  7. Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  8. Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  9. Cache-Control: must-revalidate
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7
    Success: Opera 12.15

  10. Cache-Control: private, must-revalidate, proxy-revalidate, s-maxage=0
    <body onunload="">
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7
    Success: Opera 12.15

  11. Cache-Control: must-revalidate, max-age=0
    Fail: Chrome 28, FireFox 23, Safari 5.1.7
    Success: IE8, Opera 12.15

  12. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, Safari 5.1.7
    Success: FireFox 23, IE8, Opera 12.15

  13. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, Safari 5.1.7
    Success: FireFox 23, IE8, Opera 12.15

  14. Cache-Control: no-store
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  15. Cache-Control: private, no-cache, no-store, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  16. Cache-Control: private, no-cache, no-store, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  17. Cache-Control: private, no-cache
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  18. Cache-Control: must-revalidate
    Expires: 0
    Fail: Chrome 28, FireFox 23, Safari 5.1.7,
    Success: IE8, Opera 12.15

  19. Cache-Control: must-revalidate
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Fail: Chrome 28, FireFox 23, Safari 5.1.7,
    Success: IE8, Opera 12.15

  20. Cache-Control: private, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7,
    Success: IE8, Opera 12.15

  21. Cache-Control: private, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7,
    Success: IE8, Opera 12.15

  22. Cache-Control: private, must-revalidate
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    Fail: Chrome 28, Safari 5.1.7
    Success: FireFox 23, IE8, Opera 12.15

  23. Cache-Control: no-store, must-revalidate
    Fail: none
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15

How to get datas from List<Object> (Java)?

You should try something like this

List xx= (List) list.get(0)
String id = (String) xx.get(0)

or if you have a House value object the result of the query is of the same type, then

House myhouse = (House) list.get(0);

using javascript to detect whether the url exists before display in iframe

Due to my low reputation I couldn't comment on Derek ????'s answer. I've tried that code as it is and it didn't work well. There are three issues on Derek ????'s code.

  1. The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.

  2. The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:

    • Remove the quotes that surrounds 404, making it an integer;
    • Use the javascript's operator '==' so you will be testing if the two objects are similar.
  3. The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax

The code that really worked for me was:

var request;
if(window.XMLHttpRequest)
    request = new XMLHttpRequest();
else
    request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
    alert("The page you are trying to reach is not available.");
}

How to get param from url in angular 4?

In angular, They separate it into 2 kind of url.

  1. URL pattern /heroes/:limit. Example: /heroes/20

    • You can get raw value by using route.snapshot.paramMap.get.
    • Subscribe from route.paramMap to get params
  2. URL pattern /heroes. Example: /heroes?limit=20

    • You can get raw value by using route.snapshot.queryParamMap

Reference: All you need to know about Angular parameters

Doing a cleanup action just before Node.js exits

async-exit-hook seems to be the most up-to-date solution for handling this problem. It's a forked/re-written version of exit-hook that supports async code before exiting.

Call a Class From another class

Class2 class2 = new Class2();

Instead of calling the main, perhaps you should call individual methods where and when you need them.

Second line in li starts under the bullet after CSS-reset

I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.

ul li{
text-indent: -1em;
}

Permission denied (publickey,keyboard-interactive)

You may want to double check the authorized_keys file permissions:

$ chmod 600 ~/.ssh/authorized_keys

Newer SSH server versions are very picky on this respect.

how to check if a datareader is null or empty

This

Example:

objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";

php static function

In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.

How do I install the OpenSSL libraries on Ubuntu?

How could I have figured that out for myself (other than asking this question here)? Can I somehow tell apt-get to list all packages, and grep for ssl? Or do I need to know the "lib*-dev" naming convention?

If you're linking with -lfoo then the library is likely libfoo.so. The library itself is probably part of the libfoo package, and the headers are in the libfoo-dev package as you've discovered.

Some people use the GUI "synaptic" app (sudo synaptic) to (locate and) install packages, but I prefer to use the command line. One thing that makes it easier to find the right package from the command line is the fact that apt-get supports bash completion.

Try typing sudo apt-get install libssl and then hit tab to see a list of matching package names (which can help when you need to select the correct version of a package that has multiple versions or other variations available).

Bash completion is actually very useful... for example, you can also get a list of commands that apt-get supports by typing sudo apt-get and then hitting tab.

show distinct column values in pyspark dataframe: python

you could do

distinct_column = 'somecol' 

distinct_column_vals = df.select(distinct_column).distinct().collect()
distinct_column_vals = [v[distinct_column] for v in distinct_column_vals]

How to insert a large block of HTML in JavaScript?

If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

identifier "string" undefined?

You want to do #include <string> instead of string.h and then the type string lives in the std namespace, so you will need to use std::string to refer to it.

Structs in Javascript

I always use object literals

{id: 1, speaker:"john", country: "au"}

"git rm --cached x" vs "git reset head --? x"?

There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.

When you do something like git add file you add it to the index. And when you commit it, you add it to the tree as well.

It will probably help you to know the three more common flags in git reset:

git reset [--<mode>] [<commit>]

This form resets the current branch head to <commit> and possibly updates the index (resetting it to the tree of <commit>) and the working tree depending on <mode>, which must be one of the following:
--soft

Does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--mixed

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

Now, when you do something like git reset HEAD, what you are actually doing is git reset HEAD --mixed and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD is the exact opposite of git add.

git rm, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add was used to add a new (previously untracked) file, then git rm --cached is the exact opposite of git add (and is pretty much identical to git reset HEAD).

Git 2.25 introduced a new command for these cases, git restore, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.

ECONNREFUSED error when connecting to mongodb from node.js

sometimes you need to check the rightfulness of the IP, firewall, port forwarding, etc, if your target database is in other machines.

@Media min-width & max-width

The correct value for the content attribute should include initial-scale instead:

_x000D_
_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
                                                   ^^^^^^^^^^^^^^^
_x000D_
_x000D_
_x000D_

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Extract parameter value from url using regular expressions

I know the question is Old and already answered but this can also be a solution

\b[\w-]+$

and I checked these two URLs

http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos

DEMO