Programs & Examples On #Testing

Software testing is any activity aimed at evaluating an attribute or capability of a program or system and determining that it meets its required results.

How-to turn off all SSL checks for postman for a specific site

This is not the exact answer to this question, but those who are not able to find setting popup. Their is two ways to open setting pop up.

  1. Way 1

  2. Way 2

iOS Simulator to test website on Mac

I use this site mostly

Its good one

http://iphone4simulator.com/

Still its better preferred to test on real device..

Hope this info helps you..

What is code coverage and how do YOU measure it?

Code coverage is a measurement of how many lines/blocks/arcs of your code are executed while the automated tests are running.

Code coverage is collected by using a specialized tool to instrument the binaries to add tracing calls and run a full set of automated tests against the instrumented product. A good tool will give you not only the percentage of the code that is executed, but also will allow you to drill into the data and see exactly which lines of code were executed during a particular test.

Our team uses Magellan - an in-house set of code coverage tools. If you are a .NET shop, Visual Studio has integrated tools to collect code coverage. You can also roll some custom tools, like this article describes.

If you are a C++ shop, Intel has some tools that run for Windows and Linux, though I haven't used them. I've also heard there's the gcov tool for GCC, but I don't know anything about it and can't give you a link.

As to how we use it - code coverage is one of our exit criteria for each milestone. We have actually three code coverage metrics - coverage from unit tests (from the development team), scenario tests (from the test team) and combined coverage.

BTW, while code coverage is a good metric of how much testing you are doing, it is not necessarily a good metric of how well you are testing your product. There are other metrics you should use along with code coverage to ensure the quality.

Mockito - NullpointerException when stubbing Method

I had this issue and my problem was that I was calling my method with any() instead of anyInt(). So I had:

doAnswer(...).with(myMockObject).thisFuncTakesAnInt(any())

and I had to change it to:

doAnswer(...).with(myMockObject).thisFuncTakesAnInt(anyInt())

I have no idea why that produced a NullPointerException. Maybe this will help the next poor soul.

Switch tabs using Selenium WebDriver with Java

public class TabBrowserDemo {

public static void main(String[] args) throws InterruptedException {
    System.out.println("Main Started");
    System.setProperty("webdriver.gecko.driver", "driver//geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.get("https://www.irctc.co.in/eticketing/userSignUp.jsf");
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    driver.findElement(By.xpath("//a[text()='Flights']")).click();
    waitForLoad(driver);
    Set<String> ids = driver.getWindowHandles();
    Iterator<String> iterator = ids.iterator();
    String parentID = iterator.next();
    System.out.println("Parent WIn id " + parentID);
    String childID = iterator.next();
    System.out.println("child win id " + childID);

    driver.switchTo().window(childID);
    List<WebElement> hyperlinks = driver.findElements(By.xpath("//a"));

    System.out.println("Total links in tabbed browser " + hyperlinks.size());

    Thread.sleep(3000);
//  driver.close();
    driver.switchTo().window(parentID);
    List<WebElement> hyperlinksOfParent = driver.findElements(By.xpath("//a"));

    System.out.println("Total links " + hyperlinksOfParent.size());

}

public static void waitForLoad(WebDriver driver) {
    ExpectedCondition<Boolean> pageLoadCondition = new
            ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driver) {
                    return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
                }
            };
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(pageLoadCondition);
}

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

How to configure "Shorten command line" method for whole project in IntelliJ

You can set up a default way to shorten the command line and use it as a template for further configurations by changing the default JUnit Run/Debug Configuration template. Then all new Run/Debug configuration you create in project will use the same option.

Here is the related blog post about configurable command line shortener option.

What is the difference between smoke testing and sanity testing?

Smoke testing

Smoke testing came from the hardware environment where testing should be done to check whether the development of a new piece of hardware causes no fire and smoke for the first time.

In the software environment, smoke testing is done to verify whether we can consider for further testing the functionality which is newly built.

Sanity testing

A subset of regression test cases are executed after receiving a functionality or code with small or minor changes in the functionality or code, to check whether it resolved the issues or software bugs and no other software bug is introduced by the new changes.


Difference between smoke testing and sanity testing

Smoke testing

  • Smoke testing is used to test all areas of the application without going into too deep.

  • A smoke test always use an automated test or a written set of tests. It is always scripted.

  • Smoke testing is designed to include every part of the application in a not thorough or detailed way.

  • Smoke testing always ensures whether the most crucial functions of a program are working, but not bothering with finer details.

Sanity testing

  • Sanity testing is a narrow test that focuses on one or a few areas of functionality, but not thoroughly or in-depth.

  • A sanity test is usually unscripted.

  • Sanity testing is used to ensure that after a minor change a small part of the application is still working.

  • Sanity testing is a cursory testing, which is performed to prove that the application is functioning according to the specifications. This level of testing is a subset of regression testing.

Hope these points help you to understand the difference between smoke testing and sanity testing.


References

Load vs. Stress testing

-> Testing the app with maximum number of user and input is defined as load testing. While testing the app with more than maximum number of user and input is defined as stress testing.

->In Load testing we measure the system performance based on a volume of users. While in Stress testing we measure the breakpoint of a system.

->Load Testing is testing the application for a given load requirements which may include any of the following criteria:

 .Total number of users.

 .Response Time

 .Through Put

Some parameters to check State of servers/application.

-> While stress testing is testing the application for unexpected load. It includes

 .Vusers

 .Think-Time

Example:

If an app is build for 500 users, then for load testing we check up to 500 users and for stress testing we check greater than 500.

Testing HTML email rendering

I found emailonacid.com today (beta, currently free†) - have only played with it a little but so far so good. It simulates the following clients:

  • AOL 9
  • Entourage 2004 & 2008
  • Gmail
  • Hotmail
  • Windows Live Mail
  • Windows Mail
  • Mac Mail
  • Outlook 2003 & 2007
  • Thunderbird 2, 3 & Beta
  • Yahoo Classic / Yahoo Mail

The very helpful thing about this service is it tells you what code is not supported in which client.


Edit: Not free anymore, but provides a 7 day free trial.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.

Here is the code:

package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Facebook {
    public static void main(String args[]){
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.facebook.com");
        WebElement email= driver.findElement(By.id("email"));
        Actions builder = new Actions(driver);
        Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "[email protected]");
        seriesOfActions.perform();
        WebElement pass = driver.findElement(By.id("pass"));
        WebElement login =driver.findElement(By.id("u_0_b"));
        Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);
        seriesOfAction.perform();
        driver.
    }    
}

How to emulate GPS location in the Android Emulator?

I was trying to set the geo fix through adb for many points and could not get my app to see any GPS data. But when I tried opening DDMS, selecting my app's process and sending coordinates through the emulator control tab it worked right away.

New to unit testing, how to write great tests?

It's worth noting that retro-fitting unit tests into existing code is far more difficult than driving the creation of that code with tests in the first place. That's one of the big questions in dealing with legacy applications... how to unit test? This has been asked many times before (so you may be closed as a dupe question), and people usually end up here:

Moving existing code to Test Driven Development

I second the accepted answer's book recommendation, but beyond that there's more information linked in the answers there.

Curl command line for consuming webServices?

For a SOAP 1.2 Webservice, I normally use

curl --header "content-type: application/soap+xml" --data @filetopost.xml http://domain/path

Test if string is URL encoded in PHP

I am using the following test to see if strings have been urlencoded:

if(urlencode($str) != str_replace(['%','+'], ['%25','%2B'], $str))

If a string has already been urlencoded, the only characters that will changed by double encoding are % (which starts all encoded character strings) and + (which replaces spaces.) Change them back and you should have the original string.

Let me know if this works for you.

Should black box or white box testing be the emphasis for testers?

Black Box

1 Focuses on the functionality of the system Focuses on the structure (Program) of the system

2 Techniques used are :

· Equivalence partitioning

· Boundary-value analysis

· Error guessing

· Race conditions

· Cause-effect graphing

· Syntax testing

· State transition testing

· Graph matrix

Tester can be non technical

Helps to identify the vagueness and contradiction in functional specifications

White Box

Techniques used are:

· Basis Path Testing

· Flow Graph Notation

· Control Structure Testing

  1. Condition Testing

  2. Data Flow testing

· Loop Testing

  1. Simple Loops

  2. Nested Loops

  3. Concatenated Loops

  4. Unstructured Loops

    Tester should be technical

    Helps to identify the logical and coding issues.

How to select option in drop down protractorjs e2e tests

Here's how I did it:

$('select').click();
$('select option=["' + optionInputFromFunction + '"]').click();
// This looks useless but it slows down the click event
// long enough to register a change in Angular.
browser.actions().mouseDown().mouseUp().perform();

Gradle: How to Display Test Results in the Console in Real Time?

'test' task does not work for Android plugin, for Android plugin use the following:

// Test Logging
tasks.withType(Test) {
    testLogging {
        events "started", "passed", "skipped", "failed"
    }
}

See the following: https://stackoverflow.com/a/31665341/3521637

Selenium and xpath: finding a div with a class/id and verifying text inside

To verify this:-

<div class="Caption">
  Model saved
</div>

Write this -

//div[contains(@class, 'Caption') and text()='Model saved']

And to verify this:-

<div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
  Save to server successful
</div>

Write this -

//div[@id='alertLabel' and text()='Save to server successful']

Unit Testing C Code

Minunit is an incredibly simple unit testing framework. I'm using it to unit test c microcontroller code for avr.

Automated testing for REST Api

Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun. http://frisbyjs.com

Example:

var frisby = require('../lib/frisby');

var URL = 'http://localhost:3000/';
var URL_AUTH = 'http://username:password@localhost:3000/';

frisby.globalSetup({ // globalSetup is for ALL requests
  request: {
    headers: { 'X-Auth-Token': 'fa8426a0-8eaf-4d22-8e13-7c1b16a9370c' }
  }
});

frisby.create('GET user johndoe')
  .get(URL + '/users/3.json')
  .expectStatus(200)
  .expectJSONTypes({
    id: Number,
    username: String,
    is_admin: Boolean
  })
  .expectJSON({
    id: 3,
    username: 'johndoe',
    is_admin: false
  })
  // 'afterJSON' automatically parses response body as JSON and passes it as an argument
  .afterJSON(function(user) {
    // You can use any normal jasmine-style assertions here
    expect(1+1).toEqual(2);

    // Use data from previous result in next test
    frisby.create('Update user')
      .put(URL_AUTH + '/users/' + user.id + '.json', {tags: ['jasmine', 'bdd']})
      .expectStatus(200)
    .toss();
  })
.toss();

How to test an SQL Update statement before running it?

What about Transactions? They have the ROLLBACK-Feature.

@see https://dev.mysql.com/doc/refman/5.0/en/commit.html

For example:

START TRANSACTION;
SELECT * FROM nicetable WHERE somthing=1;
UPDATE nicetable SET nicefield='VALUE' WHERE somthing=1;
SELECT * FROM nicetable WHERE somthing=1; #check

COMMIT;
# or if you want to reset changes 
ROLLBACK;

SELECT * FROM nicetable WHERE somthing=1; #should be the old value

Answer on question from @rickozoe below:

In general these lines will not be executed as once. In PHP f.e. you would write something like that (perhaps a little bit cleaner, but wanted to answer quick ;-) ):

$MysqlConnection->query('START TRANSACTION;');
$erg = $MysqlConnection->query('UPDATE MyGuests SET lastname='Doe' WHERE id=2;');
if($erg)
    $MysqlConnection->query('COMMIT;');
else
    $MysqlConnection->query('ROLLBACK;');

Another way would be to use MySQL Variables (see https://dev.mysql.com/doc/refman/5.7/en/user-variables.html and https://stackoverflow.com/a/18499823/1416909 ):

# do some stuff that should be conditionally rollbacked later on

SET @v1 := UPDATE MyGuests SET lastname='Doe' WHERE id=2;
IF(v1 < 1) THEN
    ROLLBACK;
ELSE
    COMMIT;
END IF;

But I would suggest to use the language wrappers available in your favorite programming language.

How to check if a string array contains one string in JavaScript?

There is an indexOf method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.

How do I simulate a low bandwidth, high latency environment?

I've been looking for an easy to use tool for this type of testing for a while now. I just came across this the other day: Network Delay Simulator

If you're running Windows, you should check it out. It was super easy to set up and get going, and seems to work really well. It allows you to define bandwidth, latency, and packet loss in each direction. The other really nice thing is that you can define "Flow Match Conditions" so that it only affects the traffic you want it to. Oh yeah, and it's free.

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

For those who don't care if it's "Google Chrome", I suggest using "Chromium" instead.

See: Download Chromium

  1. Look in http://googlechromereleases.blogspot.com/search/label/Stable%20updates for the last time "44." was mentioned.
  2. Loop up that version history ("44.0.2403.157") in the Position Lookup
  3. In this case it returns a base position of "330231". This is the commit of where the 44 release was branched, back in May 2015.*
  4. Open the continuous builds archive
  5. Click through on your platform (Linux/Mac/Win)
  6. Paste "330231" into the filter field at the top and wait for all the results to XHR in.
  7. Eventually I get a perfect hit: https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Mac/330231/
    1. Sometimes you may have to decrement the commit number until you find one.
  8. Download and run!

What is the difference between mocking and spying when using Mockito?

Spy can be useful when you want to create unit tests for legacy code.

I have created a runable example here https://www.surasint.com/mockito-with-spy/ , I copy some of it here.

If you have something like this code:

public void transfer(  DepositMoneyService depositMoneyService, WithdrawMoneyService withdrawMoneyService, 
             double amount, String fromAccount, String toAccount){
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some, legacy code, dependency is in the code like this:

    public void transfer(String fromAccount, String toAccount, double amount){

        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }
    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }

Then you can use the spy the inject the dependency like this:

DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target).proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target).proxyWithdrawMoneyServiceCreator();

More detail in the link above.

Test process.env with Jest

The way I did it can be found in this Stack Overflow question.

It is important to use resetModules before each test and then dynamically import the module inside the test:

describe('environmental variables', () => {
  const OLD_ENV = process.env;

  beforeEach(() => {
    jest.resetModules() // Most important - it clears the cache
    process.env = { ...OLD_ENV }; // Make a copy
  });

  afterAll(() => {
    process.env = OLD_ENV; // Restore old environment
  });

  test('will receive process.env variables', () => {
    // Set the variables
    process.env.NODE_ENV = 'dev';
    process.env.PROXY_PREFIX = '/new-prefix/';
    process.env.API_URL = 'https://new-api.com/';
    process.env.APP_PORT = '7080';
    process.env.USE_PROXY = 'false';

    const testedModule = require('../../config/env').default

    // ... actual testing
  });
});

If you look for a way to load environment values before running the Jest look for the answer below. You should use setupFiles for that.

How do I get my Maven Integration tests to run

Another way of running integration tests with Maven is to make use of the profile feature:

...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <includes>
                    <include>**/*Test.java</include>
                </includes>
                <excludes>
                    <exclude>**/*IntegrationTest.java</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>integration-tests</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <includes>
                            <include>**/*IntegrationTest.java</include>
                        </includes>
                        <excludes>
                            <exclude>**/*StagingIntegrationTest.java</exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
...

Running 'mvn clean install' will run the default build. As specified above integration tests will be ignored. Running 'mvn clean install -P integration-tests' will include the integration tests (I also ignore my staging integration tests). Furthermore, I have a CI server that runs my integration tests every night and for that I issue the command 'mvn test -P integration-tests'.

Is there a Social Security Number reserved for testing/examples?

There are multiple number groups and some particular numbers that will never be allocated:

Consider using one of these (the obviously invalid 000-00-0000 would be a good one IMO).

(Answer has been updated to provide source information beyond Wikipedia and remove information that is no longer accurate after the SSA made its randomization change in mid 2011.)

How do you run a single test/spec file in RSpec?

from help (spec -h):

-l, --line LINE_NUMBER           Execute example group or example at given line.
                                 (does not work for dynamically generated examples)

Example: spec spec/runner_spec.rb -l 162

Stopping an Android app from console

If you target a non-rooted device and/or have services in you APK that you don't want to stop as well, the other solutions won't work.

To solve this problem, I've resorted to a broadcast message receiver I've added to my activity in order to stop it.

public class TestActivity extends Activity {
    private static final String STOP_COMMAND = "com.example.TestActivity.STOP";

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TestActivity.this.finish();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //other stuff...

        registerReceiver(broadcastReceiver, new IntentFilter(STOP_COMMAND));
    }
}

That way, you can issue this adb command to stop your activity:

adb shell am broadcast -a com.example.TestActivity.STOP

JUnit: how to avoid "no runnable methods" in test utils classes

To prevent JUnit from instantiating your test base class just make it

public abstract class MyTestBaseClass { ... whatever... }

(@Ignore reports it as ignored which I reserve for temporarily ignored tests.)

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class TestMyServlet extends Mockito{

    @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    

        when(request.getParameter("username")).thenReturn("me");
        when(request.getParameter("password")).thenReturn("secret");

        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        when(response.getWriter()).thenReturn(writer);

        new MyServlet().doPost(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(stringWriter.toString().contains("My expected string"));
    }
}

Writing unit tests in Python: How do I start?

There are, in my opinion, three great python testing frameworks that are good to check out.
unittest - module comes standard with all python distributions
nose - can run unittest tests, and has less boilerplate.
pytest - also runs unittest tests, has less boilerplate, better reporting, lots of cool extra features

To get a good comparison of all of these, read through the introductions to each at http://pythontesting.net/start-here.
There's also extended articles on fixtures, and more there.

What are unit tests, integration tests, smoke tests, and regression tests?

A new test category I've just become aware of is the canary test. A canary test is an automated, non-destructive test that is run on a regular basis in a live environment, such that if it ever fails, something really bad has happened.

Examples might be:

  • Has data that should only ever be available in development/testy appeared live?
  • Has a background process failed to run?
  • Can a user logon?

Unit tests vs Functional tests

Unit tests tell a developer that the code is doing things right; functional tests tell a developer that the code is doing the right things.

You can read more at Unit Testing versus Functional Testing


A well explained real-life analogy of unit testing and functional testing can be described as follows,

Many times the development of a system is likened to the building of a house. While this analogy isn't quite correct, we can extend it for the purposes of understanding the difference between unit and functional tests.

Unit testing is analogous to a building inspector visiting a house's construction site. He is focused on the various internal systems of the house, the foundation, framing, electrical, plumbing, and so on. He ensures (tests) that the parts of the house will work correctly and safely, that is, meet the building code.

Functional tests in this scenario are analogous to the homeowner visiting this same construction site. He assumes that the internal systems will behave appropriately, that the building inspector is performing his task. The homeowner is focused on what it will be like to live in this house. He is concerned with how the house looks, are the various rooms a comfortable size, does the house fit the family's needs, are the windows in a good spot to catch the morning sun.

The homeowner is performing functional tests on the house. He has the user's perspective.

The building inspector is performing unit tests on the house. He has the builder's perspective.


As a summary,

Unit Tests are written from a programmers perspective. They are made to ensure that a particular method (or a unit) of a class performs a set of specific tasks.

Functional Tests are written from the user's perspective. They ensure that the system is functioning as users are expecting it to.

jquery (or pure js) simulate enter key pressed for testing

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

How to check whether dynamically attached event listener exists or not?

I did something like that:

const element = document.getElementById('div');

if (element.getAttribute('listener') !== 'true') {
     element.addEventListener('click', function (e) {
         const elementClicked = e.target;
         elementClicked.setAttribute('listener', 'true');
         console.log('event has been attached');
    });
}

Creating a special attribute for an element when the listener is attached and then checking if it exists.

WebDriver: check if an element exists?

Write the following method using Java:

protected boolean isElementPresent(By by){
        try{
            driver.findElement(by);
            return true;
        }
        catch(NoSuchElementException e){
            return false;
        }
    }

Call the above method during assertion.

How can I time a code segment for testing performance with Pythons timeit?

If you are profiling your code and can use IPython, it has the magic function %timeit.

%%timeit operates on cells.

In [2]: %timeit cos(3.14)
10000000 loops, best of 3: 160 ns per loop

In [3]: %%timeit
   ...: cos(3.14)
   ...: x = 2 + 3
   ...: 
10000000 loops, best of 3: 196 ns per loop

Before and After Suite execution hook in jUnit 4.x

Here, we

  • upgraded to JUnit 4.5,
  • wrote annotations to tag each test class or method which needed a working service,
  • wrote handlers for each annotation which contained static methods to implement the setup and teardown of the service,
  • extended the usual Runner to locate the annotations on tests, adding the static handler methods into the test execution chain at the appropriate points.

python: how to send mail with TO, CC and BCC?

You can try MIMEText

msg = MIMEText('text')
msg['to'] = 
msg['cc'] = 

then send msg.as_string()

https://docs.python.org/3.6/library/email.examples.html

Integration Testing POSTing an entire object to Spring MVC controller

I had the same question and it turned out the solution was fairly simple, by using JSON marshaller.
Having your controller just change the signature by changing @ModelAttribute("newObject") to @RequestBody. Like this:

@Controller
@RequestMapping(value = "/somewhere/new")
public class SomewhereController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@RequestBody NewObject newObject) {
        // ...
    }
}

Then in your tests you can simply say:

NewObject newObjectInstance = new NewObject();
// setting fields for the NewObject  

mockMvc.perform(MockMvcRequestBuilders.post(uri)
  .content(asJsonString(newObjectInstance))
  .contentType(MediaType.APPLICATION_JSON)
  .accept(MediaType.APPLICATION_JSON));

Where the asJsonString method is just:

public static String asJsonString(final Object obj) {
    try {
        final ObjectMapper mapper = new ObjectMapper();
        final String jsonContent = mapper.writeValueAsString(obj);
        return jsonContent;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}  

How do I assert my exception message with JUnit Test annotation?

@Test (expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "This is not allowed")
public void testInvalidValidation() throws Exception{
     //test code
}

How do I install jmeter on a Mac?

Download last version (not 2.5.1 or other old ones) from jmeter.apache.org

Unzip file

Ensure you install a version of JAVA which is compatible, Java 6 or 7 for JMeter 2.11

In bin folder click on jmeter.sh not on jar or execute sh ./apache-jmeter-x.x.x/bin/jmeter in the terminal.

x.x.x is the version you use.

Finally, when started you may want to select System Look and feel for Mac OSX better integration. Menu > Options > Look and Feel > System

How do you test running time of VBA code?

If you are trying to return the time like a stopwatch you could use the following API which returns the time in milliseconds since system startup:

Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Sub testTimer()
Dim t As Long
t = GetTickCount

For i = 1 To 1000000
a = a + 1
Next

MsgBox GetTickCount - t, , "Milliseconds"
End Sub

after http://www.pcreview.co.uk/forums/grab-time-milliseconds-included-vba-t994765.html (as timeGetTime in winmm.dll was not working for me and QueryPerformanceCounter was too complicated for the task needed)

How to create unit tests easily in eclipse

To create a test case template:

"New" -> "JUnit Test Case" -> Select "Class under test" -> Select "Available methods". I think the wizard is quite easy for you.

toBe(true) vs toBeTruthy() vs toBeTrue()

What I do when I wonder something like the question asked here is go to the source.

toBe()

expect().toBe() is defined as:

function toBe() {
  return {
    compare: function(actual, expected) {
      return {
        pass: actual === expected
      };
    }
  };
}

It performs its test with === which means that when used as expect(foo).toBe(true), it will pass only if foo actually has the value true. Truthy values won't make the test pass.

toBeTruthy()

expect().toBeTruthy() is defined as:

function toBeTruthy() {
  return {
    compare: function(actual) {
      return {
        pass: !!actual
      };
    }
  };
}

Type coercion

A value is truthy if the coercion of this value to a boolean yields the value true. The operation !! tests for truthiness by coercing the value passed to expect to a boolean. Note that contrarily to what the currently accepted answer implies, == true is not a correct test for truthiness. You'll get funny things like

> "hello" == true
false
> "" == true
false
> [] == true
false
> [1, 2, 3] == true
false

Whereas using !! yields:

> !!"hello"
true
> !!""
false
> !![1, 2, 3]
true
> !![] 
true

(Yes, empty or not, an array is truthy.)

toBeTrue()

expect().toBeTrue() is part of Jasmine-Matchers (which is registered on npm as jasmine-expect after a later project registered jasmine-matchers first).

expect().toBeTrue() is defined as:

function toBeTrue(actual) {
  return actual === true ||
    is(actual, 'Boolean') &&
    actual.valueOf();
}

The difference with expect().toBeTrue() and expect().toBe(true) is that expect().toBeTrue() tests whether it is dealing with a Boolean object. expect(new Boolean(true)).toBe(true) would fail whereas expect(new Boolean(true)).toBeTrue() would pass. This is because of this funny thing:

> new Boolean(true) === true
false
> new Boolean(true) === false
false

At least it is truthy:

> !!new Boolean(true)
true

Which is best suited for use with elem.isDisplayed()?

Ultimately Protractor hands off this request to Selenium. The documentation states that the value produced by .isDisplayed() is a promise that resolves to a boolean. I would take it at face value and use .toBeTrue() or .toBe(true). If I found a case where the implementation returns truthy/falsy values, I would file a bug report.

How can I solve the error LNK2019: unresolved external symbol - function?

One option would be to include function.cpp in your UnitTest1 project, but that may not be the most ideal solution structure. The short answer to your problem is that when building your UnitTest1 project, the compiler and linker have no idea that function.cpp exists, and also have nothing to link that contains a definition of multiple. A way to fix this is making use of linking libraries.

Since your unit tests are in a different project, I'm assuming your intention is to make that project a standalone unit-testing program. With the functions you are testing located in another project, it's possible to build that project to either a dynamically or statically linked library. Static libraries are linked to other programs at build time, and have the extension .lib, and dynamic libraries are linked at runtime, and have the extension .dll. For my answer I'll prefer static libraries.

You can turn your first program into a static library by changing it in the projects properties. There should be an option under the General tab where the project is set to build to an executable (.exe). You can change this to .lib. The .lib file will build to the same place as the .exe.

In your UnitTest1 project, you can go to its properties, and under the Linker tab in the category Additional Library Directories, add the path to which MyProjectTest builds. Then, for Additional Dependencies under the Linker - Input tab, add the name of your static library, most likely MyProjectTest.lib.

That should allow your project to build. Note that by doing this, MyProjectTest will not be a standalone executable program unless you change its build properties as needed, which would be less than ideal.

How to unit test abstract classes: extend with stubs?

If an abstract class is appropriate for your implementation, test (as suggested above) a derived concrete class. Your assumptions are correct.

To avoid future confusion, be aware that this concrete test class is not a mock, but a fake.

In strict terms, a mock is defined by the following characteristics:

  • A mock is used in place of each and every dependency of the subject class being tested.
  • A mock is a pseudo-implementation of an interface (you may recall that as a general rule, dependencies should be declared as interfaces; testability is one primary reason for this)
  • Behaviors of the mock's interface members -- whether methods or properties -- are supplied at test-time (again, by use of a mocking framework). This way, you avoid coupling of the implementation being tested with the implementation of its dependencies (which should all have their own discrete tests).

ReferenceError: describe is not defined NodeJs

You can also do like this:

  var mocha = require('mocha')
  var describe = mocha.describe
  var it = mocha.it
  var assert = require('chai').assert

  describe('#indexOf()', function() {
    it('should return -1 when not present', function() {
      assert.equal([1,2,3].indexOf(4), -1)
    })
  })

Reference: http://mochajs.org/#require

How to identify and switch to the frame in selenium webdriver when frame does not have id

you can use cssSelector,

driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));

How can one check to see if a remote file exists using PHP?

function remote_file_exists($url){
   return(bool)preg_match('~HTTP/1\.\d\s+200\s+OK~', @current(get_headers($url)));
}  
$ff = "http://www.emeditor.com/pub/emed32_11.0.5.exe";
    if(remote_file_exists($ff)){
        echo "file exist!";
    }
    else{
        echo "file not exist!!!";
    }

How do you print in a Go test using the "testing" package?

t.Log() will not show up until after the test is complete, so if you're trying to debug a test that is hanging or performing badly it seems you need to use fmt.

Yes: that was the case up to Go 1.13 (August 2019) included.

And that was followed in golang.org issue 24929

Consider the following (silly) automated tests:

func TestFoo(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(3 * time.Second)
    }
}

func TestBar(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(2 * time.Second)
    }
}

func TestBaz(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(1 * time.Second)
    }
}

If I run go test -v, I get no log output until all of TestFoo is done, then no output until all of TestBar is done, and again no more output until all of TestBaz is done.
This is fine if the tests are working, but if there is some sort of bug, there are a few cases where buffering log output is problematic:

  • When iterating locally, I want to be able to make a change, run my tests, see what's happening in the logs immediately to understand what's going on, hit CTRL+C to shut the test down early if necessary, make another change, re-run the tests, and so on.
    If TestFoo is slow (e.g., it's an integration test), I get no log output until the very end of the test. This significantly slows down iteration.
  • If TestFoo has a bug that causes it to hang and never complete, I'd get no log output whatsoever. In these cases, t.Log and t.Logf are of no use at all.
    This makes debugging very difficult.
  • Moreover, not only do I get no log output, but if the test hangs too long, either the Go test timeout kills the test after 10 minutes, or if I increase that timeout, many CI servers will also kill off tests if there is no log output after a certain amount of time (e.g., 10 minutes in CircleCI).
    So now my tests are killed and I have nothing in the logs to tell me what happened.

But for (possibly) Go 1.14 (Q1 2020): CL 127120

testing: stream log output in verbose mode

The output now is:

=== RUN   TestFoo
=== PAUSE TestFoo
=== RUN   TestBar
=== PAUSE TestBar
=== RUN   TestGaz
=== PAUSE TestGaz
=== CONT  TestFoo
    TestFoo: main_test.go:14: hello from foo
=== CONT  TestGaz
=== CONT  TestBar
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
--- PASS: TestFoo (1.00s)
--- PASS: TestGaz (1.00s)
--- PASS: TestBar (1.00s)
PASS
ok      dummy/streaming-test    1.022s

It is indeed in Go 1.14, as Dave Cheney attests in "go test -v streaming output":

In Go 1.14, go test -v will stream t.Log output as it happens, rather than hoarding it til the end of the test run.

Under Go 1.14 the fmt.Println and t.Log lines are interleaved, rather than waiting for the test to complete, demonstrating that test output is streamed when go test -v is used.

Advantage, according to Dave:

This is a great quality of life improvement for integration style tests that often retry for long periods when the test is failing.
Streaming t.Log output will help Gophers debug those test failures without having to wait until the entire test times out to receive their output.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

Partly it depends on what you are trying to increase the size of... number of pages, number of images, size of a single image. In my experience, the vast bulk (90%+) of any given 'large' PDF file will be the images.

You could try using a pro product like Adobe InDesign to quickly build a large project and export it as a PDF.

Adobe Acrobat Pro has built-in tools to optimize PDF files -- you try using the tools to 'un-optimize' your file. :)

How to test code dependent on environment variables using JUnit?

The library System Lambda has a method withEnvironmentVariables for setting environment variables.

public void EnvironmentVariablesTest {
  @Test
  public void setEnvironmentVariable() {
    String value = withEnvironmentVariable("name", "value")
      .execute(() -> System.getenv("name"));
    assertEquals("value", value);
  }
}

For Java 5 to 7 the library System Rules has a JUnit rule called EnvironmentVariables.

import org.junit.contrib.java.lang.system.EnvironmentVariables;

public class EnvironmentVariablesTest {
  @Rule
  public final EnvironmentVariables environmentVariables
    = new EnvironmentVariables();

  @Test
  public void setEnvironmentVariable() {
    environmentVariables.set("name", "value");
    assertEquals("value", System.getenv("name"));
  }
}

Full disclosure: I'm the author of both libraries.

How to mock private method for testing using PowerMock?

With no argument:

ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");

With String argument:

ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
                .withArguments(anyString()).thenReturn("mocked result");

How do I run all Python unit tests in a directory?

I tried various approaches but all seem flawed or I have to makeup some code, that's annoying. But there's a convinient way under linux, that is simply to find every test through certain pattern and then invoke them one by one.

find . -name 'Test*py' -exec python '{}' \;

and most importantly, it definitely works.

ScalaTest in sbt: is there a way to run a single test without tags?

I don't see a way to run a single untagged test within a test class but I am providing my workflow since it seems to be useful for anyone who runs into this question.

From within a sbt session:

test:testOnly *YourTestClass

(The asterisk is a wildcard, you could specify the full path com.example.specs.YourTestClass.)

All tests within that test class will be executed. Presumably you're most concerned with failing tests, so correct any failing implementations and then run:

test:testQuick

... which will only execute tests that failed. (Repeating the most recently executed test:testOnly command will be the same as test:testQuick in this case, but if you break up your test methods into appropriate test classes you can use a wildcard to make test:testQuick a more efficient way to re-run failing tests.)

Note that the nomenclature for test in ScalaTest is a test class, not a specific test method, so all untagged methods are executed.

If you have too many test methods in a test class break them up into separate classes or tag them appropriately. (This could be a signal that the class under test is in violation of single responsibility principle and could use a refactoring.)

Difference between acceptance test and functional test?

  1. Audience. Functional testing is to assure members of the team producing the software that it does what they expect. Acceptance testing is to assure the consumer that it meets their needs.

  2. Scope. Functional testing only tests the functionality of one component at a time. Acceptance testing covers any aspect of the product that matters to the consumer enough to test before accepting the software (i.e., anything worth the time or money it will take to test it to determine its acceptability).

Software can pass functional testing, integration testing, and system testing; only to fail acceptance tests when the customer discovers that the features just don't meet their needs. This would usually imply that someone screwed up on the spec. Software could also fail some functional tests, but pass acceptance testing because the customer is willing to deal with some functional bugs as long as the software does the core things they need acceptably well (beta software will often be accepted by a subset of users before it is completely functional).

Should I test private methods or only public ones?

It's obviously language dependent. In the past with c++, I've declared the testing class to be a friend class. Unfortunately, this does require your production code to know about the testing class.

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

    JavascriptExecutor js = (JavascriptExecutor) driver;        
    js.executeScript("document.getElementsByClassName('featured-heading')[0].setAttribute('style', 'background-color: green')");

I could add an attribute using the above code in java

estimating of testing effort as a percentage of development time

From my experience, 25% effort is spent on Analysis; 50% for Design, Development and Unit Test; remaining 25% for testing. Most projects will fit within a +/-10% variance of this rule of thumb depending on the nature of the project, knowledge of resources, quality of inputs & outputs, etc. One can add a project management overhead within these percentages or as an overhead on top within a 10-15% range.

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Proper way to assert type of variable in Python

The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

Simulate a button click in Jest

#1 Using Jest

This is how I use the Jest mock callback function to test the click event:

import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';

describe('Test Button component', () => {
  it('Test click event', () => {
    const mockCallBack = jest.fn();

    const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
    button.find('button').simulate('click');
    expect(mockCallBack.mock.calls.length).toEqual(1);
  });
});

I am also using a module called enzyme. Enzyme is a testing utility that makes it easier to assert and select your React Components

#2 Using Sinon

Also, you can use another module called Sinon which is a standalone test spy, stubs and mocks for JavaScript. This is how it looks:

import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';

import Button from './Button';

describe('Test Button component', () => {
  it('simulates click events', () => {
    const mockCallBack = sinon.spy();
    const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));

    button.find('button').simulate('click');
    expect(mockCallBack).toHaveProperty('callCount', 1);
  });
});

#3 Using Your own Spy

Finally, you can make your own naive spy (I don't recommend this approach unless you have a valid reason for that).

function MySpy() {
  this.calls = 0;
}

MySpy.prototype.fn = function () {
  return () => this.calls++;
}

it('Test Button component', () => {
  const mySpy = new MySpy();
  const mockCallBack = mySpy.fn();

  const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));

  button.find('button').simulate('click');
  expect(mySpy.calls).toEqual(1);
});

Trying to mock datetime.date.today(), but not working

Here's another way to mock datetime.date.today() with an added bonus that the rest of datetime functions continue to work, as the mock object is configured to wrap the original datetime module:

from unittest import mock, TestCase

import foo_module

class FooTest(TestCase):

    @mock.patch(f'{foo_module.__name__}.datetime', wraps=datetime)
    def test_something(self, mock_datetime):
        # mock only datetime.date.today()
        mock_datetime.date.today.return_value = datetime.date(2019, 3, 15)
        # other calls to datetime functions will be forwarded to original datetime

Note the wraps=datetime argument to mock.patch() – when the foo_module uses other datetime functions besides date.today() they will be forwarded to the original wrapped datetime module.

Order of execution of tests in TestNG

An answer with an important explanation:

There are two parameters of "TestNG" who are supposed to determine the order of execution the tests:

@Test(dependsOnGroups= "someGroup")

And:

@Test(dependsOnMethods= "someMethod")

In both cases these functions will depend on the method or group,

But the differences:

In this case:

@Test(dependsOnGroups= "someGroup")

The method will be dependent on the whole group, so it is not necessarily that immediately after the execution of the dependent function, this method will also be executed, but it may occur later in the run and even after other tests run.

It is important to note that in case and there is more than one use within the same set of tests in this parameter, this is a safe recipe for problems, because the dependent methods of the entire set of tests will run first and only then the methods that depend on them.

However, in this case:

@Test(dependsOnMethods= "someMethod")

Even if this parameter is used more than once within the same set of tests, the dependent method will still be executed after the dependent method is executed immediately.

Hope it's clearly and help.

Exact time measurement for performance testing

As others have said, Stopwatch is a good class to use here. You can wrap it in a helpful method:

public static TimeSpan Time(Action action)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    action();
    stopwatch.Stop();
    return stopwatch.Elapsed;
}

(Note the use of Stopwatch.StartNew(). I prefer this to creating a Stopwatch and then calling Start() in terms of simplicity.) Obviously this incurs the hit of invoking a delegate, but in the vast majority of cases that won't be relevant. You'd then write:

TimeSpan time = StopwatchUtil.Time(() =>
{
    // Do some work
});

You could even make an ITimer interface for this, with implementations of StopwatchTimer, CpuTimer etc where available.

What's the difference between a mock & stub?

This slide explain the main differences very good.

enter image description here

*From CSE 403 Lecture 16 , University of Washington (slide created by "Marty Stepp")

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Check Following : 1) Package names 2) Import Statements (import every required packages) 3) Proper set of braces ,i.e { } 4) Check Syntax too.. i.e semicolons,commas,etc.

Making the Android emulator run faster

On this year google I/O (2011), Google demonstrated a faster emulator. The problem is not so much on the byte code between ARM and x86 but the software rendering performed by QEMU. They bypass the rendering of QEMU and send the rendering directly to an X server I believe. They showed a car game with really good performace and fps.

I wonder when that will be available for developers...

Best way to compare 2 XML documents in Java

Below code works for me

String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
XMLAssert.assertXMLEqual(actualxml, xmlInDb);

Spring Test & Security: How to mock authentication?

Seaching for answer I couldn't find any to be easy and flexible at the same time, then I found the Spring Security Reference and I realized there are near to perfect solutions. AOP solutions often are the greatest ones for testing, and Spring provides it with @WithMockUser, @WithUserDetails and @WithSecurityContext, in this artifact:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <version>4.2.2.RELEASE</version>
    <scope>test</scope>
</dependency>

In most cases, @WithUserDetails gathers the flexibility and power I need.

How @WithUserDetails works?

Basically you just need to create a custom UserDetailsService with all the possible users profiles you want to test. E.g

@TestConfiguration
public class SpringSecurityWebAuxTestConfig {

    @Bean
    @Primary
    public UserDetailsService userDetailsService() {
        User basicUser = new UserImpl("Basic User", "[email protected]", "password");
        UserActive basicActiveUser = new UserActive(basicUser, Arrays.asList(
                new SimpleGrantedAuthority("ROLE_USER"),
                new SimpleGrantedAuthority("PERM_FOO_READ")
        ));

        User managerUser = new UserImpl("Manager User", "[email protected]", "password");
        UserActive managerActiveUser = new UserActive(managerUser, Arrays.asList(
                new SimpleGrantedAuthority("ROLE_MANAGER"),
                new SimpleGrantedAuthority("PERM_FOO_READ"),
                new SimpleGrantedAuthority("PERM_FOO_WRITE"),
                new SimpleGrantedAuthority("PERM_FOO_MANAGE")
        ));

        return new InMemoryUserDetailsManager(Arrays.asList(
                basicActiveUser, managerActiveUser
        ));
    }
}

Now we have our users ready, so imagine we want to test the access control to this controller function:

@RestController
@RequestMapping("/foo")
public class FooController {

    @Secured("ROLE_MANAGER")
    @GetMapping("/salute")
    public String saluteYourManager(@AuthenticationPrincipal User activeUser)
    {
        return String.format("Hi %s. Foo salutes you!", activeUser.getUsername());
    }
}

Here we have a get mapped function to the route /foo/salute and we are testing a role based security with the @Secured annotation, although you can test @PreAuthorize and @PostAuthorize as well. Let's create two tests, one to check if a valid user can see this salute response and the other to check if it's actually forbidden.

@RunWith(SpringRunner.class)
@SpringBootTest(
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = SpringSecurityWebAuxTestConfig.class
)
@AutoConfigureMockMvc
public class WebApplicationSecurityTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithUserDetails("[email protected]")
    public void givenManagerUser_whenGetFooSalute_thenOk() throws Exception
    {
        mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
                .accept(MediaType.ALL))
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("[email protected]")));
    }

    @Test
    @WithUserDetails("[email protected]")
    public void givenBasicUser_whenGetFooSalute_thenForbidden() throws Exception
    {
        mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
                .accept(MediaType.ALL))
                .andExpect(status().isForbidden());
    }
}

As you see we imported SpringSecurityWebAuxTestConfig to provide our users for testing. Each one used on its corresponding test case just by using a straightforward annotation, reducing code and complexity.

Better use @WithMockUser for simpler Role Based Security

As you see @WithUserDetails has all the flexibility you need for most of your applications. It allows you to use custom users with any GrantedAuthority, like roles or permissions. But if you are just working with roles, testing can be even easier and you could avoid constructing a custom UserDetailsService. In such cases, specify a simple combination of user, password and roles with @WithMockUser.

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(
    factory = WithMockUserSecurityContextFactory.class
)
public @interface WithMockUser {
    String value() default "user";

    String username() default "";

    String[] roles() default {"USER"};

    String password() default "password";
}

The annotation defines default values for a very basic user. As in our case the route we are testing just requires that the authenticated user be a manager, we can quit using SpringSecurityWebAuxTestConfig and do this.

@Test
@WithMockUser(roles = "MANAGER")
public void givenManagerUser_whenGetFooSalute_thenOk() throws Exception
{
    mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
            .accept(MediaType.ALL))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("user")));
}

Notice that now instead of the user [email protected] we are getting the default provided by @WithMockUser: user; yet it won't matter because what we really care about is his role: ROLE_MANAGER.

Conclusions

As you see with annotations like @WithUserDetails and @WithMockUser we can switch between different authenticated users scenarios without building classes alienated from our architecture just for making simple tests. Its also recommended you to see how @WithSecurityContext works for even more flexibility.

How to properly assert that an exception gets raised in pytest?

pytest.raises(Exception) is what you need.

Code

import pytest

def test_passes():
    with pytest.raises(Exception) as e_info:
        x = 1 / 0

def test_passes_without_info():
    with pytest.raises(Exception):
        x = 1 / 0

def test_fails():
    with pytest.raises(Exception) as e_info:
        x = 1 / 1

def test_fails_without_info():
    with pytest.raises(Exception):
        x = 1 / 1

# Don't do this. Assertions are caught as exceptions.
def test_passes_but_should_not():
    try:
        x = 1 / 1
        assert False
    except Exception:
        assert True

# Even if the appropriate exception is caught, it is bad style,
# because the test result is less informative
# than it would be with pytest.raises(e)
# (it just says pass or fail.)

def test_passes_but_bad_style():
    try:
        x = 1 / 0
        assert False
    except ZeroDivisionError:
        assert True

def test_fails_but_bad_style():
    try:
        x = 1 / 1
        assert False
    except ZeroDivisionError:
        assert True

Output

============================================================================================= test session starts ==============================================================================================
platform linux2 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.6.4
collected 7 items 

test.py ..FF..F

=================================================================================================== FAILURES ===================================================================================================
__________________________________________________________________________________________________ test_fails __________________________________________________________________________________________________

    def test_fails():
        with pytest.raises(Exception) as e_info:
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:13: Failed
___________________________________________________________________________________________ test_fails_without_info ____________________________________________________________________________________________

    def test_fails_without_info():
        with pytest.raises(Exception):
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:17: Failed
___________________________________________________________________________________________ test_fails_but_bad_style ___________________________________________________________________________________________

    def test_fails_but_bad_style():
        try:
            x = 1 / 1
>           assert False
E           assert False

test.py:43: AssertionError
====================================================================================== 3 failed, 4 passed in 0.02 seconds ======================================================================================

Note that e_info saves the exception object so you can extract details from it. For example, if you want to check the exception call stack or another nested exception inside.

How to run only one unit test class using Gradle

In my case, my eclipse java compiler warnings were set too high, and eclipse was not recognizing my class as valid for execution. Updating my compiler settings fixed the problem. You can read more about it here: annotation-nonnull-cannot-be-resolved

Select a date from date picker using Selenium webdriver

Here's a tidy solution where you provide the target date as a Calendar object.

// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
    MONTH_TO_CALENDAR_INDEX.put("January",  0);
    MONTH_TO_CALENDAR_INDEX.put("February",1);
    MONTH_TO_CALENDAR_INDEX.put("March",2);
    MONTH_TO_CALENDAR_INDEX.put("April",3);
    MONTH_TO_CALENDAR_INDEX.put("May",4);
    MONTH_TO_CALENDAR_INDEX.put("June",5);
    MONTH_TO_CALENDAR_INDEX.put("July",6);
    MONTH_TO_CALENDAR_INDEX.put("August",7);
    MONTH_TO_CALENDAR_INDEX.put("September",8);
    MONTH_TO_CALENDAR_INDEX.put("October",9);
    MONTH_TO_CALENDAR_INDEX.put("November",10);
    MONTH_TO_CALENDAR_INDEX.put("December",11);
}

        // ====================================================================================================
        // setCalendarPicker
        // ====================================================================================================

        /**
         * Sets the value of specified web element while assuming the element is a JQuery calendar.
         * @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
         * @param byPicker The By phrase that locates the JQuery calendar.
         * @param targetDate The target date that you want set.
         * @throws AssertionError if the method is unable to set the date.
         */

        public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {

            // Open the JQuery calendar.
            WebElement opener = driver.findElement(byOpen);
            opener.click();

            // Locate the JQuery calendar.
            WebElement picker = driver.findElement(byPicker);

            // Calculate the target and current year-and-month as an integer where value = year*12+month.
            // The difference between the two is the number of months we have to move ahead or backward.
            int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
            int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
                    + Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
            // Calculate the number of months we need to move the JQuery calendar.
            int delta = targetYearMonth - currentYearMonth;
            // As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
            if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");

            // Push the JQuery calendar forward or backward as appropriate.
            if (delta > 0) {
                while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
            } else if (delta < 0 ){
                while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
            }

            // Select the day within the month.
            String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
            WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
            for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
                if (dayOfMonth.equals(we.getText())) {
                    we.click();

                    // Send a tab to completely leave this control.  If the next control the user will access is another CalendarPicker,
                    // the picker might not get selected properly if we stay on the current control.
                    opener.sendKeys("\t");

                    return;
                }
            }

            throw new AssertionError(String.format("Unable to select specified day"));
        }

How to write a test which expects an Error to be thrown in Jasmine?

You are using:

expect(fn).toThrow(e)

But if you'll have a look on the function comment (expected is string):

294 /**
295  * Matcher that checks that the expected exception was thrown by the actual.
296  *
297  * @param {String} expected
298  */
299 jasmine.Matchers.prototype.toThrow = function(expected) {

I suppose you should probably write it like this (using lambda - anonymous function):

expect(function() { parser.parse(raw); } ).toThrow("Parsing is not possible");

This is confirmed in the following example:

expect(function () {throw new Error("Parsing is not possible")}).toThrow("Parsing is not possible");

Douglas Crockford strongly recommends this approach, instead of using "throw new Error()" (prototyping way):

throw {
   name: "Error",
   message: "Parsing is not possible"
}

Fix footer to bottom of page

A very simple example that shows how to fix the footer at the bottom in your application's layout.

_x000D_
_x000D_
/* Styles go here */_x000D_
html{ height: 100%;}_x000D_
body{ min-height: 100%; background: #fff;}_x000D_
.page-layout{ border: none; width: 100%; height: 100vh; }_x000D_
.page-layout td{ vertical-align: top; }_x000D_
.page-layout .header{ background: #aaa; }_x000D_
.page-layout .main-content{ height: 100%; background: #f1f1f1; text-align: center; padding-top: 50px; }_x000D_
.page-layout .main-content .container{ text-align: center; padding-top: 50px; }_x000D_
.page-layout .footer{ background: #333; color: #fff; } 
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <link data-require="bootstrap@*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />_x000D_
    <link rel="stylesheet" href="style.css" />_x000D_
    <script src="script.js"></script>_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <table class="page-layout">_x000D_
      <tr>_x000D_
        <td class="header">_x000D_
          <div>_x000D_
            This is the site header._x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="main-content">_x000D_
          <div>_x000D_
            <h1>Fix footer always to the bottom</h1>_x000D_
            <div>_x000D_
              This is how you can simply fix the footer to the bottom._x000D_
            </div>_x000D_
            <div>_x000D_
              The footer will always stick to the bottom until the main-content doesn't grow till footer._x000D_
            </div>_x000D_
            <div>_x000D_
              Even if the content grows, the footer will start to move down naturally as like the normal behavior of page._x000D_
            </div>_x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="footer">_x000D_
          <div>_x000D_
            This is the site footer._x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to create a jQuery function (a new jQuery method or plugin)?

Simplest example to making any function in jQuery is

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something here*/}

How to change the default collation of a table?

It sets the default collation for the table; if you create a new column, that should be collated with latin_general_ci -- I think. Try specifying the collation for the individual column and see if that works. MySQL has some really bizarre behavior in regards to the way it handles this.

Online SQL syntax checker conforming to multiple databases

Only know about this. Not sure how well does it against MySQL http://developer.mimer.se/validator/

How do I compare strings in GoLang?

For the Platform Independent Users or Windows users, what you can do is:

import runtime:

import (
    "runtime"
    "strings"
)

and then trim the string like this:

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}

now you can compare it like that:

if strings.Compare(input, "a") == 0 {
  //....yourCode
}

This is a better approach when you're making use of STDIN on multiple platforms.

Explanation

This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.

Select option padding not working in chrome

That's not work on optionentry because it's a "system" generated drop-down menu but you can set the padding of a select.

Just reset the box-sizing property to content-box in your CSS.

The default value of select is border-box.

select {
 box-sizing: content-box;
 padding: 5px 0;
}

Why is lock(this) {...} bad?

It is bad form to use this in lock statements because it is generally out of your control who else might be locking on that object.

In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For example, any one with a reference to the object can lock on it without the object designer/creator knowing about it. This increases the complexity of multi-threaded solutions and might affect their correctness.

A private field is usually a better option as the compiler will enforce access restrictions to it, and it will encapsulate the locking mechanism. Using this violates encapsulation by exposing part of your locking implementation to the public. It is also not clear that you will be acquiring a lock on this unless it has been documented. Even then, relying on documentation to prevent a problem is sub-optimal.

Finally, there is the common misconception that lock(this) actually modifies the object passed as a parameter, and in some way makes it read-only or inaccessible. This is false. The object passed as a parameter to lock merely serves as a key. If a lock is already being held on that key, the lock cannot be made; otherwise, the lock is allowed.

This is why it's bad to use strings as the keys in lock statements, since they are immutable and are shared/accessible across parts of the application. You should use a private variable instead, an Object instance will do nicely.

Run the following C# code as an example.

public class Person
{
    public int Age { get; set;  }
    public string Name { get; set; }

    public void LockThis()
    {
        lock (this)
        {
            System.Threading.Thread.Sleep(10000);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var nancy = new Person {Name = "Nancy Drew", Age = 15};
        var a = new Thread(nancy.LockThis);
        a.Start();
        var b = new Thread(Timewarp);
        b.Start(nancy);
        Thread.Sleep(10);
        var anotherNancy = new Person { Name = "Nancy Drew", Age = 50 };
        var c = new Thread(NameChange);
        c.Start(anotherNancy);
        a.Join();
        Console.ReadLine();
    }

    static void Timewarp(object subject)
    {
        var person = subject as Person;
        if (person == null) throw new ArgumentNullException("subject");
        // A lock does not make the object read-only.
        lock (person.Name)
        {
            while (person.Age <= 23)
            {
                // There will be a lock on 'person' due to the LockThis method running in another thread
                if (Monitor.TryEnter(person, 10) == false)
                {
                    Console.WriteLine("'this' person is locked!");
                }
                else Monitor.Exit(person);
                person.Age++;
                if(person.Age == 18)
                {
                    // Changing the 'person.Name' value doesn't change the lock...
                    person.Name = "Nancy Smith";
                }
                Console.WriteLine("{0} is {1} years old.", person.Name, person.Age);
            }
        }
    }

    static void NameChange(object subject)
    {
        var person = subject as Person;
        if (person == null) throw new ArgumentNullException("subject");
        // You should avoid locking on strings, since they are immutable.
        if (Monitor.TryEnter(person.Name, 30) == false)
        {
            Console.WriteLine("Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \"Nancy Drew\".");
        }
        else Monitor.Exit(person.Name);

        if (Monitor.TryEnter("Nancy Drew", 30) == false)
        {
            Console.WriteLine("Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!");
        }
        else Monitor.Exit("Nancy Drew");
        if (Monitor.TryEnter(person.Name, 10000))
        {
            string oldName = person.Name;
            person.Name = "Nancy Callahan";
            Console.WriteLine("Name changed from '{0}' to '{1}'.", oldName, person.Name);
        }
        else Monitor.Exit(person.Name);
    }
}

Console output

'this' person is locked!
Nancy Drew is 16 years old.
'this' person is locked!
Nancy Drew is 17 years old.
Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string "Nancy Drew".
'this' person is locked!
Nancy Smith is 18 years old.
'this' person is locked!
Nancy Smith is 19 years old.
'this' person is locked!
Nancy Smith is 20 years old.
Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!
'this' person is locked!
Nancy Smith is 21 years old.
'this' person is locked!
Nancy Smith is 22 years old.
'this' person is locked!
Nancy Smith is 23 years old.
'this' person is locked!
Nancy Smith is 24 years old.
Name changed from 'Nancy Drew' to 'Nancy Callahan'.

How do I find what Java version Tomcat6 is using?

If tomcat did not start up yet , you can use the command \bin\cataline version to check which JVM will the tomcat use when you start tomcat using bin\startup

In fact ,\bin\cataline version just call the main class of org.apache.catalina.util.ServerInfo , which is located inside the \lib\catalina.jar . The org.apache.catalina.util.ServerInfo gets the JVM Version and JVM Vendor by the following commands:

System.out.println("JVM Version: " +System.getProperty("java.runtime.version"));
System.out.println("JVM Vendor: " +System.getProperty("java.vm.vendor")); 

So , if the tomcat is running , you can create a JSP page that call org.apache.catalina.util.ServerInfo or just simply call the above System.getProperty() to get the JVM Version and Vendor . Deploy this JSP to the running tomcat instance and browse to it to see the result.

Alternatively, you should know which port is the running tomcat instance using . So , you can use the OS command to find which process is listening to this port. For example in the window , you can use the command netstat -aon to find out the process ID of a process that is listening to a particular port . Then go to the window task manager to check the full file path of this process ID belongs to. .The java version can then be determined from that file path.

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

The major difference between the two is that $_SERVER['SERVER_NAME'] is a server controlled variable, while $_SERVER['HTTP_HOST'] is a user-controlled value.

The rule of thumb is to never trust values from the user, so $_SERVER['SERVER_NAME'] is the better choice.

As Gumbo pointed out, Apache will construct SERVER_NAME from user-supplied values if you don't set UseCanonicalName On.

Edit: Having said all that, if the site is using a name-based virtual host, the HTTP Host header is the only way to reach sites that aren't the default site.

Display Bootstrap Modal using javascript onClick

I had the same problem, after researching a lot, I finally built a js function to create modals dynamically based on my requirements. Using this function, you can create popups in one line such as:

puyModal({title:'Test Title',heading:'Heading',message:'This is sample message.'})

Or you can use other complex functionality such as iframes, video popups, etc.

Find it on https://github.com/aybhalala/puymodals For demo, go to http://pateladitya.com/puymodals/

Elegant solution for line-breaks (PHP)

I ended up writing a function that has worked for me well so far:

// pretty print data
function out($data, $label = NULL) {

  $CLI = (php_sapi_name() === 'cli') ? 'cli' : '';

  $gettype = gettype($data);

  if (isset($label)) {
    if ($CLI) { $label = $label . ': '; }
    else { $label = '<b>'.$label.'</b>: '; }
  }

  if ($gettype == 'string' || $gettype == 'integer' || $gettype == 'double' || $gettype == 'boolean') {
    if ($CLI) { echo $label . $data . "\n"; }
    else { echo $label . $data . "<br/>"; }
  }
  else {
    if ($CLI) { echo $label . print_r($data,1) . "\n"; } 
    else { echo $label . "<pre>".print_r($data,1)."</pre>"; }
  }
}


// Usage

out('Hello world!');

$var = 'Hello Stackoverflow!';
out($var, 'Label');

How to send a pdf file directly to the printer using JavaScript?

a function to house the print trigger...

function printTrigger(elementId) {
    var getMyFrame = document.getElementById(elementId);
    getMyFrame.focus();
    getMyFrame.contentWindow.print();
}

an button to give the user access...

(an onClick on an a or button or input or whatever you wish)

<input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
an iframe pointing to your PDF...

<iframe id="iFramePdf" src="myPdfUrl.pdf" style="dispaly:none;"></iframe>

More : http://www.fpdf.org/en/script/script36.php

datetimepicker is not a function jquery

Keep in mind, the jQuery UI's datepicker is not initialized with datetimepicker(), there appears to be a plugin/addon here: http://trentrichardson.com/examples/timepicker/.

However, with just jquery-ui it's actually initialized as $("#example").datepicker(). See jQuery's demo site here: http://jqueryui.com/demos/datepicker/

   $(document).ready(function(){
        $("#example1").datepicker();
    });

To use the datetimepicker at the link referenced above, you will want to be certain that your scripts path is correct for the plugin.

error: Libtool library used but 'LIBTOOL' is undefined

For folks who ended up here and are using CYGWIN, install following packages in cygwin and re-run:

  • cygwin32-libtool
  • libtool
  • libtool-debuginfo

Run Command Prompt Commands

you can use simply write the code in a .bat format extension ,the code of the batch file :

c:/ copy /b Image1.jpg + Archive.rar Image2.jpg

use this c# code :

Process.Start("file_name.bat")

Where is Python language used?

Many websites uses Django or Zope/Plone web framework, these are written in Python.

Python is used a lot for writing system administration software, usually when bash scripts (shell script) isn't up to the job, but going C/C++ is an overkill. This is also the spectrum where perl, awk, etc stands. Gentoo's emerge/portage is one example. Mercurial/HG is a distributed version control system (DVCS) written in python.

Many desktop applications are also written in Python. The original Bittorrent was written in python.

Python is also used as the scripting languages for GIMP, Inkscape, Blender, OpenOffice, etc. Python allows advanced users to write plugins and access advanced functionalities that cannot typically be used through a GUI.

Assert that a WebElement is not present using Selenium WebDriver with java

With Selenium Webdriver would be something like this:

assertTrue(!isElementPresent(By.linkText("Empresas en Misión")));

Java Swing revalidate() vs repaint()

You need to call repaint() and revalidate(). The former tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by removeAll()); the latter tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause children of the panel to repaint, but may not cause the panel itself to do so (see this for the list of repaint triggers).

On a more general note: rather than reusing the original panel, I'd recommend building a new panel and swapping them at the parent.

JavaScript: Passing parameters to a callback function

This would also work:

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

// callback executer 
function callbackTester (callback) { 
    callback(); 
} 

// test function
callbackTester (function() {
    tryMe("hello", "goodbye"); 
}); 

Another Scenario :

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

// callback executer 
function callbackTester (callback) { 
//this is the more obivous scenario as we use callback function
//only when we have some missing value
//get this data from ajax or compute
var extraParam = "this data was missing" ;

//call the callback when we have the data
    callback(extraParam); 
} 

// test function
callbackTester (function(k) {
    tryMe("hello", "goodbye", k); 
}); 

How to parse a text file with C#

You could open the file up and use StreamReader.ReadLine to read the file in line-by-line. Then you can use String.Split to break each line into pieces (use a \t delimiter) to extract the second number.

As the number of items is different you would need to search the string for the pattern 'item\*.ddj'.

To delete an item you could (for example) keep all of the file's contents in memory and write out a new file when the user clicks 'Save'.

How can I add additional PHP versions to MAMP

MAMP takes only two highest versions of the PHP in the following folder /Application/MAMP/bin/php

As you can see here highest versions are 7.0.10 and 5.6.25 MAMP php Versions 7.0.10 and 5.6.25

Now 7.0.10 version is removed and as you can see highest two versions are 5.6.25 and 5.5.38 as shown in preferencesphp versions 5.6.25 and 5.5.38

Convert YYYYMMDD to DATE

The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?

To find the values that are causing issues (so you (or whoever designed this table) can fix them):

SELECT GRADUATION_DATE FROM mydb
  WHERE ISDATE(GRADUATION_DATE) = 0;

Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.

ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;

Now you don't have to worry about the formatting - you can always format as YYYYMMDD or YYYY-MM-DD on the client, or using CONVERT in SQL. When you have a valid date as a string literal, you can use:

SELECT CONVERT(CHAR(10), '20120101', 120);

...but this is better done on the client (if at all).

There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.

Setting DIV width and height in JavaScript

The onclick attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.

How to correctly implement custom iterators and const_iterators?

They often forget that iterator must convert to const_iterator but not the other way around. Here is a way to do that:

template<class T, class Tag = void>
class IntrusiveSlistIterator
   : public std::iterator<std::forward_iterator_tag, T>
{
    typedef SlistNode<Tag> Node;
    Node* node_;

public:
    IntrusiveSlistIterator(Node* node);

    T& operator*() const;
    T* operator->() const;

    IntrusiveSlistIterator& operator++();
    IntrusiveSlistIterator operator++(int);

    friend bool operator==(IntrusiveSlistIterator a, IntrusiveSlistIterator b);
    friend bool operator!=(IntrusiveSlistIterator a, IntrusiveSlistIterator b);

    // one way conversion: iterator -> const_iterator
    operator IntrusiveSlistIterator<T const, Tag>() const;
};

In the above notice how IntrusiveSlistIterator<T> converts to IntrusiveSlistIterator<T const>. If T is already const this conversion never gets used.

How can I group data with an Angular filter?

I originally used Plantface's answer, but I didn't like how the syntax looked in my view.

I reworked it to use $q.defer to post-process the data and return a list on unique teams, which is then uses as the filter.

http://plnkr.co/edit/waWv1donzEMdsNMlMHBa?p=preview

View

<ul>
  <li ng-repeat="team in teams">{{team}}
    <ul>
      <li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li> 
    </ul>
  </li>
</ul>

Controller

app.controller('MainCtrl', function($scope, $q) {

  $scope.players = []; // omitted from SO for brevity

  // create a deferred object to be resolved later
  var teamsDeferred = $q.defer();

  // return a promise. The promise says, "I promise that I'll give you your
  // data as soon as I have it (which is when I am resolved)".
  $scope.teams = teamsDeferred.promise;

  // create a list of unique teams. unique() definition omitted from SO for brevity
  var uniqueTeams = unique($scope.players, 'team');

  // resolve the deferred object with the unique teams
  // this will trigger an update on the view
  teamsDeferred.resolve(uniqueTeams);

});

Wireshark vs Firebug vs Fiddler - pros and cons?

If you're developing an application that transfers data using AMF (fairly common in a particular set of GIS web APIs I use regularly), Fiddler does not currently provide an AMF decoder that will allow you to easily view the binary data in an easily-readable format. Charles provides this functionality.

How can I upgrade NumPy?

If you don't encounter any permission errors with

pip install -U numpy

try:

pip install --user -U numpy

Create intermediate folders if one doesn't exist

Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:

File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();

Increment a database field by 1

If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:

INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;

If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.

How to find the length of an array in shell?

In the Fish Shell the length of an array can be found with:

$ set a 1 2 3 4
$ count $a
4

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

C# using streams

There is only one basic type of Stream. However in various circumstances some members will throw an exception when called because in that context the operation was not available.

For example a MemoryStream is simply a way to moves bytes into and out of a chunk of memory. Hence you can call Read and Write on it.

On the other hand a FileStream allows you to read or write (or both) from/to a file. Whether you can actually Read or Write depends on how the file was opened. You can't Write to a file if you only opened it for Read access.

How to get distinct results in hibernate with joins and row-based limiting (paging)?

I will now explain a different solution, where you can use the normal query and pagination method without having the problem of possibly duplicates or suppressed items.

This Solution has the advance that it is:

  • faster than the PK id solution mentioned in this article
  • preserves the Ordering and don’t use the 'in clause' on a possibly large Dataset of PK’s

The complete Article can be found on my blog

Hibernate gives the possibility to define the association fetching method not only at design time but also at runtime by a query execution. So we use this aproach in conjunction with a simple relfection stuff and can also automate the process of changing the query property fetching algorithm only for collection properties.

First we create a method which resolves all collection properties from the Entity Class:

public static List<String> resolveCollectionProperties(Class<?> type) {
  List<String> ret = new ArrayList<String>();
  try {
   BeanInfo beanInfo = Introspector.getBeanInfo(type);
   for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
     if (Collection.class.isAssignableFrom(pd.getPropertyType()))
     ret.add(pd.getName());
   }
  } catch (IntrospectionException e) {
    e.printStackTrace();
  }
  return ret;
}

After doing that you can use this little helper method do advise your criteria object to change the FetchMode to SELECT on that query.

Criteria criteria = …

//    … add your expression here  …

// set fetchmode for every Collection Property to SELECT
for (String property : ReflectUtil.resolveCollectionProperties(YourEntity.class)) {
  criteria.setFetchMode(property, org.hibernate.FetchMode.SELECT);
}
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
criteria.list();

Doing that is different from define the FetchMode of your entities at design time. So you can use the normal join association fetching on paging algorithms in you UI, because this is most of the time not the critical part and it is more important to have your results as quick as possible.

How to get previous page url using jquery

Easy as pie.

$(document).ready(function() {
   var referrer =  document.referrer;
});

Hope it helps. It is not always available though.

How to add a color overlay to a background image?

You can use a pseudo element to create the overlay.

.testclass {
  background-image: url("../img/img.jpg");
  position: relative;
}
.testclass:before {
  content: "";
  position: absolute;
  left: 0; right: 0;
  top: 0; bottom: 0;
  background: rgba(0,0,0,.5);
}

Run bash script from Windows PowerShell

If you add the extension .SH to the environment variable PATHEXT, you will be able to run shell scripts from PowerShell by only using the script name with arguments:

PS> .\script.sh args

If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:

PS> script args

Note: sh.exe or another *nix shell must be associated with the .sh extension.

jQuery event handlers always execute in order they were bound - any way around this?

You can do a custom namespace of events.

$('span').bind('click.doStuff1',function(){doStuff1();});
$('span').bind('click.doStuff2',function(){doStuff2();});

Then, when you need to trigger them you can choose the order.

$('span').trigger('click.doStuff1').trigger('click.doStuff2');

or

$('span').trigger('click.doStuff2').trigger('click.doStuff1');

Also, just triggering click SHOULD trigger both in the order they were bound... so you can still do

$('span').trigger('click'); 

How to change colors of a Drawable in Android?

Int color = Color.GRAY; 
// or int color = Color.argb(123,255,0,5);
// or int color = 0xaaff000;

in XML /res/values/color.xml

<?xml version="1.0" encoding="utf-8">
<resources>
    <color name="colorRed">#ff0000</color>
</resoures> 

Java Code

int color = ContextCompat.getColor(context, R.color.colorRed);

GradientDrawable drawableBg = yourView.getBackground().mutate();
drawableBg.setColor(color);

npm install hangs

The registry(https://registry.npmjs.org/cordova) was blocked by our firewall. Unblocking it fixed the issue.

How to send email via Django?

I had actually done this from Django a while back. Open up a legitimate GMail account & enter the credentials here. Here's my code -

from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

def sendmail(to, subject, text, attach=[], mtype='html'):
    ok = True
    gmail_user = settings.EMAIL_HOST_USER
    gmail_pwd  = settings.EMAIL_HOST_PASSWORD

    msg = MIMEMultipart('alternative')

    msg['From']    = gmail_user
    msg['To']      = to
    msg['Cc']      = '[email protected]'
    msg['Subject'] = subject

    msg.attach(MIMEText(text, mtype))

    for a in attach:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(attach, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(a))
        msg.attach(part)

    try:
        mailServer = smtplib.SMTP("smtp.gmail.com", 687)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        mailServer.sendmail(gmail_user, [to,msg['Cc']], msg.as_string())
        mailServer.close()
    except:
        ok = False
    return ok

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

Just my two cents for future visitors who have this problem.

This is the correct syntax for PHP 5.3, for example if you call static method from the class name:

MyClassName::getConfig($key);

If you previously assign the ClassName to the $cnf variable, you can call the static method from it (we are talking about PHP 5.3):

$cnf = MyClassName;
$cnf::getConfig($key);

However, this sintax doesn't work on PHP 5.2 or lower, and you need to use the following:

$cnf = MyClassName;
call_user_func(array($cnf, "getConfig", $key, ...otherposibleadditionalparameters... ));

Hope this helps people having this error in 5.2 version (don't know if this was openfrog's version).

Pandas get the most frequent values of a column

my best solution to get the first is

 df['my_column'].value_counts().sort_values(ascending=False).argmax()

Get data from php array - AJAX - jQuery

you cannot access array (php array) from js try

<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>

and js

$(document).ready( function() {
$('#prev').click(function() {
  $.ajax({
  type: 'POST',
  url: 'ajax.php',
  data: 'id=testdata',
  cache: false,
  success: function(data) {
    result=data.split('~');
    $('#content1').html(result[0]);
  },
  });
});
});

What's the difference between "super()" and "super(props)" in React when using es6 classes?

There is only one reason when one needs to pass props to super():

When you want to access this.props in constructor.

Passing:

class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

Not passing:

class MyComponent extends React.Component {    
    constructor(props) {
        super()

        console.log(this.props)
        // -> undefined

        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
    }

    render() {
        // No difference outside constructor
        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

Note that passing or not passing props to super has no effect on later uses of this.props outside constructor. That is render, shouldComponentUpdate, or event handlers always have access to it.

This is explicitly said in one Sophie Alpert's answer to a similar question.


The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:

Class components should always call the base constructor with props.

However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.

(Thanks @MattBrowne for the link)

How to convert JSON to XML or XML to JSON?

Here is a simple snippet that converts a XmlNode (recursively) into a hashtable, and groups multiple instances of the same child into an array (as an ArrayList). The Hashtable is usually accepted to convert into JSON by most of the JSON libraries.

protected object convert(XmlNode root){
    Hashtable obj = new Hashtable();
    for(int i=0,n=root.ChildNodes.Count;i<n;i++){
        object result = null;
        XmlNode current = root.ChildNodes.Item(i);

        if(current.NodeType != XmlNodeType.Text)
            result = convert(current);
        else{
            int resultInt;
            double resultFloat;
            bool resultBoolean;
            if(Int32.TryParse(current.Value, out resultInt)) return resultInt;
            if(Double.TryParse(current.Value, out resultFloat)) return resultFloat;
            if(Boolean.TryParse(current.Value, out resultBoolean)) return resultBoolean;
            return current.Value;
        }

        if(obj[current.Name] == null)
            obj[current.Name] = result;
        else if(obj[current.Name].GetType().Equals(typeof(ArrayList)))
            ((ArrayList)obj[current.Name]).Add(result);
        else{
            ArrayList collision = new ArrayList();
            collision.Add(obj[current.Name]);
            collision.Add(result);
            obj[current.Name] = collision;
        }
    }

    return obj;
}

How can I get CMake to find my alternative Boost installation?

I had a similar issue, CMake finding a vendor-installed Boost only, but my cluster had a locally installed version which is what I wanted it to use. Red Hat Linux 6.

Anyway, it looks like all the BOOSTROOT, BOOST_ROOT, and Boost_DIR stuff would get annoyed unless one also sets Boost_NO_BOOST_CMAKE (e.g add to cmd line -DBoost_NO_BOOST_CMAKE=TRUE).

(I will concede the usefulness of CMake for multiplatform, but I can still hate it.)

Accessing attributes from an AngularJS directive

See section Attributes from documentation on directives.

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

How to check if a variable is null or empty string or all whitespace in JavaScript?

function isEmptyOrSpaces(str){
    return str === null || str.match(/^[\s\n\r]*$/) !== null;
}

HTTP vs HTTPS performance

There isn't a single answer for this.

Encryption will always consume more CPU. This can be offloaded to dedicated hardware in many cases, and the cost will vary by algorithm selected. 3des is more expensive than AES, for example. Some algorithms are more expensive for the encrypter than the decryptor. Some have the opposite cost.

More expensive than the bulk crypto is handshake cost. New connections will consume much more CPU. This can be reduced with session resumption, at the cost of keeping old session secrets around until they expire. This means that small requests from a client that doesn't come back for more are the most expensive.

For cross internet traffic you may not notice this cost in your data rate, because the bandwidth available is too low. But you will certainly notice it in CPU usage on a busy server.

Alternative Windows shells, besides CMD.EXE?

At the moment there are three realy powerfull cmd.exe alternatives:

cmder is an enhancement off ConEmu and Clink

All have features like Copy & Paste, Window Resize per Mouse, Splitscreen, Tabs and a lot of other usefull features.

jQuery find() method not working in AngularJS directive

You can easily solve that in 2 steps:

1- Reach the child element using querySelector like that: var target = element[0].querySelector('tbody tr:first-child td')

2- Transform it to an angular.element object again by doing: var targetElement = angular.element(target)

You will then have access to all expected methods on the targetElement variable.

How do I get the total Json record count using JQuery?

If you have something like this:

var json = [ {a:b, c:d}, {e:f, g:h, ...}, {..}, ... ]

then, you can do:

alert(json.length)

jQuery - getting custom attribute from selected option

$("body").on('change', '#location', function(e) {

 var option = $('option:selected', this).attr('myTag');

});

Integer expression expected error in shell script

./bilet.sh: line 6: [: 7]: integer expression expected

Be careful with " "

./bilet.sh: line 9: [: missing `]'

This is because you need to have space between brackets like:

if [ "$age" -le 7 ] -o [ "$age" -ge 65 ]

look: added space, and no " "

Java compile error: "reached end of file while parsing }"

You need to enclose your class in { and }. A few extra pointers: According to the Java coding conventions, you should

  • Put your { on the same line as the method declaration:
  • Name your classes using CamelCase (with initial capital letter)
  • Name your methods using camelCase (with small initial letter)

Here's how I would write it:

public class ModMyMod extends BaseMod {

    public String version() {
         return "1.2_02";
    }

    public void addRecipes(CraftingManager recipes) {
       recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
          "#", Character.valueOf('#'), Block.dirt
       });
    }
}

Trigger a button click with JavaScript on the Enter key in a text box

Then just code it in!

<input type = "text"
       id = "txtSearch" 
       onkeydown = "if (event.keyCode == 13)
                        document.getElementById('btnSearch').click()"    
/>

<input type = "button"
       id = "btnSearch"
       value = "Search"
       onclick = "doSomething();"
/>

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

This post helped me with zip(). I know I'm a few years late, but I still want to contribute. This is in Python 3.

Note: in python 2.x, zip() returns a list of tuples; in Python 3.x, zip() returns an iterator. itertools.izip() in python 2.x == zip() in python 3.x

Since it looks like you're building a list of tuples, the following code is the most pythonic way of trying to accomplish what you are doing.

>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = list(zip(lat, long))
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]

Or, alternatively, you can use list comprehensions (or list comps) should you need more complicated operations. List comprehensions also run about as fast as map(), give or take a few nanoseconds, and are becoming the new norm for what is considered Pythonic versus map().

>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = [(x,y) for x,y in zip(lat, long)]
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]
>>> added_tuples = [x+y for x,y in zip(lat, long)]
>>> added_tuples
[5, 7, 9]

Counting Line Numbers in Eclipse

You could use a batch file with the following script:

@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir "%CD%\src\*.java" /b /s') DO (type "%%G") >> lines.txt
SET count=1
FOR /f "tokens=*" %%G IN ('type lines.txt') DO (set /a lines+=1)
echo Your Project has currently totaled %lines% lines of code. 
del lines.txt
PAUSE

JavaScript hashmap equivalent

JavaScript does not have a built-in map/hashmap. It should be called an associative array.

hash["X"] is equal to hash.X, but it allows "X" as a string variable. In other words, hash[x] is functionally equal to eval("hash."+x.toString()).

It is more similar to object.properties rather than key-value mapping. If you are looking for a better key/value mapping in JavaScript, please use the Map object.

Is it possible to cast a Stream in Java 8?

Late to the party, but I think it is a useful answer.

flatMap would be the shortest way to do it.

Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())

If o is a Client then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>.

How do I reformat HTML code using Sublime Text 2?

I am yet to have the privilege to comment so this is simply additional information related to @peter's answer above answer.

I found HTML did not align as expected if IE conditional comments in the header were not completely in-line e.g. flush to the left:

<!--[if lt IE 7]>
<p class='chromeframe'>Your browser is <em>unsupported</em>. <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p>
<![endif]-->
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--> 

Difference between "read commited" and "repeatable read"

Trying to explain this doubt with simple diagrams.

Read Committed: Here in this isolation level, Transaction T1 will be reading the updated value of the X committed by Transaction T2.

Read Committed

Repeatable Read: In this isolation level, Transaction T1 will not consider the changes committed by the Transaction T2.

enter image description here

How to add "class" to host element?

Günter's answer is great (question is asking for dynamic class attribute) but I thought I would add just for completeness...

If you're looking for a quick and clean way to add one or more static classes to the host element of your component (i.e., for theme-styling purposes) you can just do:

@Component({
   selector: 'my-component',
   template: 'app-element',
   host: {'class': 'someClass1'}
})
export class App implements OnInit {
...
}

And if you use a class on the entry tag, Angular will merge the classes, i.e.,

<my-component class="someClass2">
  I have both someClass1 & someClass2 applied to me
</my-component>

How exactly does binary code get converted into letters?

Do you mean the conversion 011001100110111101101111 ? foo, for example? You just take the binary stream, split it into separate bytes (01100110, 01101111, 01101111) and look up the ASCII character that corresponds to given number. For example, 01100110 is 102 in decimal and the ASCII character with code 102 is f:

$ perl -E 'say 0b01100110'
102
$ perl -E 'say chr(102)'
f

(See what the chr function does.) You can generalize this algorithm and have a different number of bits per character and different encodings, the point remains the same.

Import Script from a Parent Directory

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

Note that both explicit and implicit 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 should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I have try with the SCFRench and with the Ru Hasha on octave.

And finally it works: but I have done some modification

function message = makefuns
    assignin('base','fun1', @fun1);   % Ru Hasha
    assignin('base', 'fun2', @fun2);  % Ru Hasha
    message.fun1=@fun1;               % SCFrench
    message.fun2=@fun2;               % SCFrench
end

function y=fun1(x)
    y=x;
end

function z=fun2
    z=1;
end

Can be called in other 'm' file:

printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());

update:

I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).

Pandas read_csv low_memory and dtype options

df = pd.read_csv('somefile.csv', low_memory=False)

This should solve the issue. I got exactly the same error, when reading 1.8M rows from a CSV.

Where are the recorded macros stored in Notepad++?

Go to %appdata%\Notepad++ folder.

The macro definitions are held in shortcuts.xml inside the <Macros> tag. You can copy the whole file, or copy the tag and paste it into shortcuts.xml at the other location.
In the latter case, be sure to use another editor, since N++ overwrites shortcuts.xml on exit.

How to remove an HTML element using Javascript?

Just do this element.remove();

Try it here LOOK

http://jsfiddle.net/4WGRP/

Catching exceptions from Guzzle

To catch Guzzle errors you can do something like this:

try {
    $response = $client->get('/not_found.xml')->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
    echo 'Uh oh! ' . $e->getMessage();
}

... but, to be able to "log" or "resend" your request try something like this:

// Add custom error handling to any request created by this client
$client->getEventDispatcher()->addListener(
    'request.error', 
    function(Event $event) {

        //write log here ...

        if ($event['response']->getStatusCode() == 401) {

            // create new token and resend your request...
            $newRequest = $event['request']->clone();
            $newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken());
            $newResponse = $newRequest->send();

            // Set the response object of the request without firing more events
            $event['response'] = $newResponse;

            // You can also change the response and fire the normal chain of
            // events by calling $event['request']->setResponse($newResponse);

            // Stop other events from firing when you override 401 responses
            $event->stopPropagation();
        }

});

... or if you want to "stop event propagation" you can overridde event listener (with a higher priority than -255) and simply stop event propagation.

$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() != 200) {
        // Stop other events from firing when you get stytus-code != 200
        $event->stopPropagation();
    }
});

thats a good idea to prevent guzzle errors like:

request.CRITICAL: Uncaught PHP Exception Guzzle\Http\Exception\ClientErrorResponseException: "Client error response

in your application.

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Iframe transparent background

Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.

Your content must have a ListView whose id attribute is 'android.R.id.list'

You should have one listview in your mainlist.xml file with id as @android:id/list

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_height="fill_parent"/>

How to change package name of an Android Application

The fastest way to do that in Android Studio 1.3:

  1. Change the package name in the manifest
  2. Go to Module Settings[F4]-> Flavors, into Application Id write the same name.
  3. Create new package with that name: [right-click-> new-> package]
  4. Select all java files of your project and then proceed [Right-click-> Refactor-> Move-> {Select package}-> Refactor]

P.S. If you will not follow this order you can end up changing all the java files one by one with new imports and a bunch of compile time errors, so the order is very important.

Oracle SQL, concatenate multiple columns + add text

Below query works for me @Oracle 10G ----

select PHONE, CONTACT, (ADDR1 ||  '-' || ADDR2 || '-' || ADDR3) as Address
from CUSTOMER_DETAILS
where Code='341'; 

O/P -

1111 [email protected] 4th street-capetown-sa

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

MySQL - force not to use cache for testing speed of query

You can also run the follow command to reset the query cache.

RESET QUERY CACHE

Command-line Unix ASCII-based charting / plotting tool

feedgnuplot is another front end to gnuplot, which handles piping in data.

    $ seq 5 | awk '{print 2*$1, $1*$1}' |
      feedgnuplot --lines --points --legend 0 "data 0" --title "Test plot" --y2 1
                  --terminal 'dumb 80,40' --exit

                                     Test plot

     10 ++------+--------+-------+-------+-------+--------+-------+------*A 25
        +       +        +       +       +       +        +       +    **#+
        |       :        :       :       :       :        : data 0+**A*** |
        |       :        :       :       :       :        :       :** #   |
      9 ++.......................................................**.##....|
        |       :        :       :       :       :        :    ** :#      |
        |       :        :       :       :       :        :  **   #       |
        |       :        :       :       :       :        :**   ##:      ++ 20
      8 ++................................................A....#..........|
        |       :        :       :       :       :      **:   #   :       |
        |       :        :       :       :       :    **  : ##    :       |
        |       :        :       :       :       :  **    :#      :       |
        |       :        :       :       :       :**      B       :       |
      7 ++......................................**......##................|
        |       :        :       :       :    ** :    ##  :       :      ++ 15
        |       :        :       :       :  **   :   #    :       :       |
        |       :        :       :       :**     : ##     :       :       |
      6 ++..............................*A.......##.......................|
        |       :        :       :    ** :     ##:        :       :       |
        |       :        :       :  **   :    #  :        :       :       |
        |       :        :       :**     :  ##   :        :       :      ++ 10
      5 ++......................**........##..............................|
        |       :        :    ** :      #B       :        :       :       |
        |       :        :  **   :    ## :       :        :       :       |
        |       :        :**     :  ##   :       :        :       :       |
      4 ++...............A.......###......................................|
        |       :      **:     ##:       :       :        :       :       |
        |       :    **  :   ##  :       :       :        :       :      ++ 5
        |       :  **    : ##    :       :       :        :       :       |
        |       :**    ##B#      :       :       :        :       :       |
      3 ++.....**..####...................................................|
        |    **####      :       :       :       :        :       :       |
        |  **## :        :       :       :       :        :       :       |
        B**     +        +       +       +       +        +       +       +
      2 A+------+--------+-------+-------+-------+--------+-------+------++ 0
        1      1.5       2      2.5      3      3.5       4      4.5      5

Getting all names in an enum as a String[]

Create a String[] array for the names and call the static values() method which returns all the enum values, then iterate over the values and populate the names array.

public static String[] names() {
    State[] states = values();
    String[] names = new String[states.length];

    for (int i = 0; i < states.length; i++) {
        names[i] = states[i].name();
    }

    return names;
}

A server with the specified hostname could not be found

I got this message when the device has mobile data turned on and no wifi connection, but the internet is not properly connected.

Try to connect to a wifi network with an internet connection or turning off the mobile data.

PHP foreach loop through multidimensional array

<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));

//Iterate through an array declared above

foreach($php_multi_array as $key => $value)
{
    if (!is_array($value))
    {
        echo $key ." => ". $value ."\r\n" ;
    }
    else
    {
       echo $key ." => array( \r\n";

       foreach ($value as $key2 => $value2)
       {
           echo "\t". $key2 ." => ". $value2 ."\r\n";
       }

       echo ")";
    }
}
?>

OUTPUT:

lang => PHP
type => array( 
    c_type => MULTI
    p_type => ARRAY
)

Reference Source Code

How can I pass a parameter to a setTimeout() callback?

The easiest cross browser solution for supporting parameters in setTimeout:

setTimeout(function() {
    postinsql(topicId);
}, 4000)

If you don't mind not supporting IE 9 and lower:

setTimeout(postinsql, 4000, topicId);

setTimeout desktop browser compatibility

setTimeout mobile browser compatibility

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

Generating a WSDL from an XSD file

I know this question is old, but it deserves an answer. I personally prefer to create a WSDL by hand and test for compliance using SoapUI. But sometimes (specially for complex WSDLs), you have three ways to generate one out of an XSD:

  1. Generating a WSDL from a schema using Eclipse (probably the most user-friendly)
  2. Generating a WSDL via CXF (my favorite)
  3. Generating a WSDL via conventions using Spring WS (my least favorite)

I prefer the CXF approach since I'm a CLI guy. If it has a CLI, you can automate (that's my motto). And I like the Spring WS approach the least since it uses a lot of framework specific conventions.

There are more people who know CXF (I believe) than Spring WS. So anything that can throw a learning curve for a new engineer (without any clear advantage or ROI) is something I frown upon.

It should also go w/o saying that any generated WSDL should be tested for validity and compliance (and tweaked till it complies), and that your application publishes a static wsdl (as opposed to returning an auto-generated one.)

It's been my experience that you start with a WS-I compliant wsdl and then your application auto-generates (and returns to consumers) a non-compliant one.

In other words, beware of auto magic.

Swift programmatically navigate to another view controller/scene

OperationQueue.main.addOperation {
   let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
   let newViewController = storyBoard.instantiateViewController(withIdentifier: "Storyboard ID") as! NewViewController
   self.present(newViewController, animated: true, completion: nil)
}

It worked for me when I put the code inside of the OperationQueue.main.addOperation, that will execute in the main thread for me.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

Sometimes all it takes to get a EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) is a missing return statement.

It certainly was my case.

How to refresh token with Google API client?

This here works very good, maybe it could help anybody:

index.php

session_start();

require_once __DIR__.'/client.php';

if(!isset($obj->error) && isset($_SESSION['access_token']) && $_SESSION['access_token'] && isset($obj->expires_in)) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Google API Token Test</title>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
search('Music Mix 2010');
function search(q) {
    $.ajax({
        type: 'GET',
        url: 'action.php?q='+q,
        success: function(data) {
            if(data == 'refresh') location.reload();
            else $('#response').html(JSON.stringify(JSON.parse(data)));
        }
    });
}
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
<?php
}
else header('Location: '.filter_var('https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/oauth2callback.php', FILTER_SANITIZE_URL));
?>

oauth2callback.php

require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('auth.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setRedirectUri('https://'.filter_var($_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'], FILTER_SANITIZE_URL));
$client->addScope(Google_Service_YouTube::YOUTUBE_FORCE_SSL);

if(isset($_GET['code']) && $_GET['code']) {
    $client->authenticate(filter_var($_GET['code'], FILTER_SANITIZE_STRING));
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $_SESSION['access_token']['refresh_token'];
    setcookie('refresh_token', $_SESSION['refresh_token'], time()+60*60*24*180, '/', filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL), true, true);
    header('Location: '.filter_var('https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']), FILTER_SANITIZE_URL));
    exit();
}
else header('Location: '.filter_var($client->createAuthUrl(), FILTER_SANITIZE_URL));
exit();

?>

client.php

// https://developers.google.com/api-client-library/php/start/installation
require_once __DIR__.'/vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig('auth.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_YouTube::YOUTUBE_FORCE_SSL);

// Delete Cookie Token
#setcookie('refresh_token', @$_SESSION['refresh_token'], time()-1, '/', filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL), true, true);

// Delete Session Token
#unset($_SESSION['refresh_token']);

if(isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
    $client->refreshToken($_SESSION['refresh_token']);
    $_SESSION['access_token'] = $client->getAccessToken();
}
elseif(isset($_COOKIE['refresh_token']) && $_COOKIE['refresh_token']) {
    $client->refreshToken($_COOKIE['refresh_token']);
    $_SESSION['access_token'] = $client->getAccessToken();
}

$url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.urlencode(@$_SESSION['access_token']['access_token']);
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Google API Token Test');
$json = curl_exec($curl_handle);
curl_close($curl_handle);

$obj = json_decode($json);

?>

action.php

session_start();

require_once __DIR__.'/client.php';

if(isset($obj->error)) {
    echo 'refresh';
    exit();
}
elseif(isset($_SESSION['access_token']) && $_SESSION['access_token'] && isset($obj->expires_in) && isset($_GET['q']) && !empty($_GET['q'])) {
    $client->setAccessToken($_SESSION['access_token']);
    $service = new Google_Service_YouTube($client);
    $response = $service->search->listSearch('snippet', array('q' => filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS), 'maxResults' => '1', 'type' => 'video'));
    echo json_encode($response['modelData']);
    exit();
}
?>

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

When would you use the Builder Pattern?

The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within one method call.

One example of using a builder is a building an XML document, I've used this model when building HTML fragments for example I might have a Builder for building a specific type of table and it might have the following methods (parameters are not shown):

BuildOrderHeaderRow()
BuildLineItemSubHeaderRow()
BuildOrderRow()
BuildLineItemSubRow()

This builder would then spit out the HTML for me. This is much easier to read than walking through a large procedural method.

Check out Builder Pattern on Wikipedia.

Get Maven artifact version at runtime

You should not need to access Maven-specific files to get the version information of any given library/class.

You can simply use getClass().getPackage().getImplementationVersion() to get the version information that is stored in a .jar-files MANIFEST.MF. Luckily Maven is smart enough Unfortunately Maven does not write the correct information to the manifest as well by default!

Instead one has to modify the <archive> configuration element of the maven-jar-plugin to set addDefaultImplementationEntries and addDefaultSpecificationEntries to true, like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>                   
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>

Ideally this configuration should be put into the company pom or another base-pom.

Detailed documentation of the <archive> element can be found in the Maven Archive documentation.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

use request.getContextPath() instead of ${pageContext.request.contextPath} in JSP expression language.

<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);

output: willPrintMyProjectcontextPath

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

How to change Windows 10 interface language on Single Language version

Actually, it looks like you may be able to download language packs directly through Windows Update. Open the old Control Panel by pressing WinKey+X and clicking Control Panel. Then go to Clock, Language, and Region > Add a language. Add the desired language. Then under the language it should say "Windows display language: Available". Click "Options" and then "Download and install language pack."

I'm not sure why this functionality appears to be less accessible than it was in Windows 8.

Show a number to two decimal places

Another more exotic way to solve this issue is to use bcadd() with a dummy value for the $right_operand of 0.

$formatted_number = bcadd($number, 0, 2);

Java: int[] array vs int array[]

Both are equivalent. Take a look at the following:

int[] array;

// is equivalent to

int array[];
int var, array[];

// is equivalent to

int var;
int[] array;
int[] array1, array2[];

// is equivalent to

int[] array1;
int[][] array2;
public static int[] getArray()
{
    // ..
}

// is equivalent to

public static int getArray()[]
{
    // ..
}

Unexpected character encountered while parsing value

I experienced the same error in my Xamarin.Android solution.

I verified that my JSON was correct, and noticed that the error only appeared when I ran the app as a Release build.

It turned out that the Linker was removing a library from Newtonsoft.JSON, causing the JSON to be parsed incorrectly.

I fixed the error by adding Newtonsoft.Json to the Ignore assemblies setting in the Android Build Configuration (screen shot below)

JSON Parsing Code

static readonly JsonSerializer _serializer = new JsonSerializer();
static readonly HttpClient _client = new HttpClient();

static async Task<T> GetDataObjectFromAPI<T>(string apiUrl)
{
    using (var stream = await _client.GetStreamAsync(apiUrl).ConfigureAwait(false))
    using (var reader = new StreamReader(stream))
    using (var json = new JsonTextReader(reader))
    {
        if (json == null)
            return default(T);

        return _serializer.Deserialize<T>(json);
    }
}

Visual Studio Mac Screenshot

enter image description here

Visual Studio Screenshot

enter image description here

Default value of function parameter

On thing to remember here is that the default param must be the last param in the function definition.

Following code will not compile:

void fun(int first, int second = 10, int third);

Following code will compile:

void fun(int first, int second, int third = 10);

What port number does SOAP use?

SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.

Increasing nesting function calls limit

This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:

xdebug.max_nesting_level = 200

or in your PHP code:

ini_set('xdebug.max_nesting_level', 200);

As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Uncaught Typeerror: cannot read property 'innerHTML' of null

//Run with this HTML structure
<!DOCTYPE html>
<head>
    <title>OOJS</title>

</head>
<body>
    <div id="status">
    </div>
    <script type="text/javascript" src="scriptfile.js"></script>
</body>
</html>

How to perform a sum of an int[] array

Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:

int i = 0;        // Create a separate integer to serve as your array indexer.
while(i < 10) {   // The indexer needs to be less than 10, not A itself.
   sum += A[i];   // either sum = sum + ... or sum += ..., but not both
   i++;           // You need to increment the index at the end of the loop.
}

The above example uses a while loop, since that's the approach you took. A more appropriate construct would be a for loop, as in Bogdan's answer.

PHP Redirect to another page after form submit

Whenever you want to redirect, send the headers:

header("Location: http://www.example.com/");

Remember you cant send data to the client before that, though.

python capitalize first letter only

I came up with this:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str

Saving a Excel File into .txt format without quotes

PRN solution works only for simple data in the cells, for me it cuts only first 6 signs from 200 characters cell.

These are the main file formats in Excel 2007-2016, Note: In Excel for the Mac the values are +1

51 = xlOpenXMLWorkbook (without macro's in 2007-2016, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2016, xlsm)
50 = xlExcel12 (Excel Binary Workbook in 2007-2016 with or without macro's, xlsb)
56 = xlExcel8 (97-2003 format in Excel 2007-2016, xls)

From XlFileFormat FileFormat Property

Keep in mind others FileFormatNumbers for SaveAs method:

FileExtStr = ".csv": FileFormatNum = 6
FileExtStr = ".txt": FileFormatNum = -4158
FileExtStr = ".prn": FileFormatNum = 36

javascript regular expression to not match a word

This is what you are looking for:

^((?!(abc|def)).)*$

the explanation is here: Regular expression to match a line that doesn't contain a word?

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

What is "android.R.layout.simple_list_item_1"?

This is a part of the android OS. Here is the actual version of the defined XML file.

simple_list_item_1:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/listItemFirstLineStyle"
    android:paddingTop="2dip"
    android:paddingBottom="3dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

simple_list_item_2:

<TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="2dip"
    android:paddingBottom="2dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:id="@android:id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="?android:attr/listItemFirstLineStyle"/>

    <TextView android:id="@android:id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@android:id/text1"
        style="?android:attr/listItemSecondLineStyle" />

</TwoLineListItem> 

PHPmailer sending HTML CODE

all you need to do is just add $mail->IsHTML(true); to the code it works fine..

Convert Python dictionary to JSON array

If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.

# -*- coding: UTF-8 -*-

This will fix some Unicode problems and make your life easier.

How to use the pass statement?

Here's an example where I was extracting particular data from a list where I had multiple data types (that's what I'd call it in R-- sorry if it's the wrong nomenclature) and I wanted to extract only integers/numeric and NOT character data.

The data looked like:

>>> a = ['1', 'env', '2', 'gag', '1.234', 'nef']
>>> data = []
>>> type(a)
<class 'list'>
>>> type(a[1])
<class 'str'>
>>> type(a[0])
<class 'str'>

I wanted to remove all alphabetical characters, so I had the machine do it by subsetting the data, and "passing" over the alphabetical data:

a = ['1', 'env', '2', 'gag', '1.234', 'nef']
data = []
for i in range(0, len(a)):
    if a[i].isalpha():
        pass
    else:
        data.append(a[i])
print(data)
['1', '2', '1.234']

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

How to format date string in java?

package newpckg;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StrangeDate {

    public static void main(String[] args) {

        // string containing date in one format
        // String strDate = "2012-05-20T09:00:00.000Z";
        String strDate = "2012-05-20T09:00:00.000Z";

        try {
            // create SimpleDateFormat object with source string date format
            SimpleDateFormat sdfSource = new SimpleDateFormat(
                    "yyyy-MM-dd'T'hh:mm:ss'.000Z'");

            // parse the string into Date object
            Date date = sdfSource.parse(strDate);

            // create SimpleDateFormat object with desired date format
            SimpleDateFormat sdfDestination = new SimpleDateFormat(
                    "dd/MM/yyyy, ha");

            // parse the date into another format
            strDate = sdfDestination.format(date);

            System.out
                    .println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
            System.out.println("Converted date is : " + strDate.toLowerCase());

        } catch (ParseException pe) {
            System.out.println("Parse Exception : " + pe);
        }
    }
}

How to connect to a remote Git repository?

Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.

The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git

For example, cloning a repository on a machine to which you have SSH access using the "dev" user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:

git clone ssh://[email protected]/srv/repositories/awesomeproject.git

How to completely remove Python from a Windows machine?

I know it is an old question, but I ran into this problem with 2.7 and 3.5. Though 2.7 would not show up in my default windows uninstall list, it showed up fine in the ccleaner tools tab under uninstall. Uninstalled and reinstalled afterwards and it has been smooth coding ever since.

generate random string for div id

I think some folks here haven't really focused on your particular question. It looks like the problem you have is in putting the random number in the page and hooking the player up to it. There are a number of ways to do that. The simplest is with a small change to your existing code like this to document.write() the result into the page. I wouldn't normally recommend document.write(), but since your code is already inline and what you were trying do already was to put the div inline, this is the simplest way to do that. At the point where you have the random number, you just use this to put it and the div into the page:

var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');

and then, you refer to that in the jwplayer set up code like this:

jwplayer(randomId).setup({

And the whole block of code would look like this:

<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>'); 

  jwplayer(randomId).setup({
    'flashplayer': 'player.swf',
    'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
    'controlbar': 'bottom',
    'width': '470',
    'height': '320'
  });
</script>

Another way to do it

I might add here at the end that generating a truly random number just to create a unique div ID is way overkill. You don't need a random number. You just need an ID that won't otherwise exist in the page. Frameworks like YUI have such a function and all they do is have a global variable that gets incremented each time the function is called and then combine that with a unique base string. It can look something like this:

var generateID = (function() {
    var globalIdCounter = 0;
    return function(baseStr) {
        return(baseStr + globalIdCounter++);
    }
})();

And, then in practical use, you would do something like this:

var randomId = generateID("myMovieContainer");  // "myMovieContainer1"
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({

What is an HttpHandler in ASP.NET

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page via the page handler.

The ASP.NET page handler is only one type of handler. ASP.NET comes with several other built-in handlers such as the Web service handler for .asmx files.

You can create custom HTTP handlers when you want special handling that you can identify using file name extensions in your application. For example, the following scenarios would be good uses of custom HTTP handlers:

RSS feeds To create an RSS feed for a site, you can create a handler that emits RSS-formatted XML. You can then bind the .rss extension (for example) in your application to the custom handler. When users send a request to your site that ends in .rss, ASP.NET will call your handler to process the request.

Image server If you want your Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them back to the user as the handler's response.

HTTP handlers have access to the application context, including the requesting user's identity (if known), application state, and session information. When an HTTP handler is requested, ASP.NET calls the ProcessRequest method on the appropriate handler. The handler's ProcessRequest method creates a response, which is sent back to the requesting browser. As with any page request, the response goes through any HTTP modules that have subscribed to events that occur after the handler has run.

Error after upgrading pip: cannot import name 'main'

You must have inadvertently upgraded your system pip (probably through something like sudo pip install pip --upgrade)

pip 10.x adjusts where its internals are situated. The pip3 command you're seeing is one provided by your package maintainer (presumably debian based here?) and is not a file managed by pip.

You can read more about this on pip's issue tracker

You'll probably want to not upgrade your system pip and instead use a virtualenv.

To recover the pip3 binary you'll need to sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall.

If you want to continue in "unsupported territory" (upgrading a system package outside of the system package manager), you can probably get away with python3 -m pip ... instead of pip3.

Visual Studio 2015 doesn't have cl.exe

For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
You can now execute your command in it, for example: cl /?

UITextField text change event

Swift Version tested:

//Somewhere in your UIViewController, like viewDidLoad(){ ... }
self.textField.addTarget(
        self, 
        action: #selector(SearchViewController.textFieldDidChange(_:)),
        forControlEvents: UIControlEvents.EditingChanged
)

Parameters explained:

self.textField //-> A UITextField defined somewhere in your UIViewController
self //-> UIViewController
.textFieldDidChange(_:) //-> Can be named anyway you like, as long as it is defined in your UIViewController

Then add the method you created above in your UIViewController:

//Gets called everytime the text changes in the textfield.
func textFieldDidChange(textField: UITextField){

    print("Text changed: " + textField.text!)

}

What is pipe() function in Angular

You have to look to official ReactiveX documentation: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md.

This is a good article about piping in RxJS: https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44.

In short .pipe() allows chaining multiple pipeable operators.

Starting in version 5.5 RxJS has shipped "pipeable operators" and renamed some operators:

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

Email address validation using ASP.NET MVC data type attributes

Scripts are usually loaded in the end of the html page, and MVC recommends the using of bundles, just saying. So my best bet is that your jquery.validate files got altered in some way or are not updated to the latest version, since they do validate e-mail inputs.

So you could either update/refresh your nuget package or write your own function, really.

Here's an example which you would add in an extra file after jquery.validate.unobtrusive:

$.validator.addMethod(
    "email",
    function (value, element) {
        return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
    },
    "This e-mail is not valid"
);

This is just a copy and paste of the current jquery.validate Regex, but this way you could set your custom error message/add extra methods to fields you might want to validate in the near future.

Access denied for user 'test'@'localhost' (using password: YES) except root user

According way you create your user, MySQL interprets a different manner. For instance, if you create a user like this:

create user user01 identified by 'test01';

MySQL expects you give some privilege using grant all on <your_db>.* to user01;

Don't forget to flush privileges;

But, if you create user like that (by passing an IP address), you have to change it to:

create user 'user02'@'localhost' identified by 'teste02';

so, to give some privileges you have to do that:

grant all on <your_db>.* to user02@localhost;
flush privileges;

Using Jquery Datatable with AngularJs

Take a look at this: AngularJS+JQuery(datatable)

FULL code: http://jsfiddle.net/zdam/7kLFU/

JQuery Datatables's Documentation: http://www.datatables.net/

var dialogApp = angular.module('tableExample', []);

    dialogApp.directive('myTable', function() {
        return function(scope, element, attrs) {

            // apply DataTable options, use defaults if none specified by user
            var options = {};
            if (attrs.myTable.length > 0) {
                options = scope.$eval(attrs.myTable);
            } else {
                options = {
                    "bStateSave": true,
                    "iCookieDuration": 2419200, /* 1 month */
                    "bJQueryUI": true,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bInfo": false,
                    "bDestroy": true
                };
            }

            // Tell the dataTables plugin what columns to use
            // We can either derive them from the dom, or use setup from the controller           
            var explicitColumns = [];
            element.find('th').each(function(index, elem) {
                explicitColumns.push($(elem).text());
            });
            if (explicitColumns.length > 0) {
                options["aoColumns"] = explicitColumns;
            } else if (attrs.aoColumns) {
                options["aoColumns"] = scope.$eval(attrs.aoColumns);
            }

            // aoColumnDefs is dataTables way of providing fine control over column config
            if (attrs.aoColumnDefs) {
                options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
            }

            if (attrs.fnRowCallback) {
                options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);
            }

            // apply the plugin
            var dataTable = element.dataTable(options);



            // watch for any changes to our data, rebuild the DataTable
            scope.$watch(attrs.aaData, function(value) {
                var val = value || null;
                if (val) {
                    dataTable.fnClearTable();
                    dataTable.fnAddData(scope.$eval(attrs.aaData));
                }
            });
        };
    });

function Ctrl($scope) {

    $scope.message = '';            

        $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {            
            $('td:eq(2)', nRow).bind('click', function() {
                $scope.$apply(function() {
                    $scope.someClickHandler(aData);
                });
            });
            return nRow;
        };

        $scope.someClickHandler = function(info) {
            $scope.message = 'clicked: '+ info.price;
        };

        $scope.columnDefs = [ 
            { "mDataProp": "category", "aTargets":[0]},
            { "mDataProp": "name", "aTargets":[1] },
            { "mDataProp": "price", "aTargets":[2] }
        ]; 

        $scope.overrideOptions = {
            "bStateSave": true,
            "iCookieDuration": 2419200, /* 1 month */
            "bJQueryUI": true,
            "bPaginate": true,
            "bLengthChange": false,
            "bFilter": true,
            "bInfo": true,
            "bDestroy": true
        };


        $scope.sampleProductCategories = [

              {
                "name": "1948 Porsche 356-A Roadster",
                "price": 53.9,
                  "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1948 Porsche Type 356 Roadster",
                "price": 62.16,
            "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1949 Jaguar XK 120",
                "price": 47.25,
            "category": "Classic Cars",
                  "action":"x"
              }
              ,
              {
                "name": "1936 Harley Davidson El Knucklehead",
                "price": 24.23,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1957 Vespa GS150",
                "price": 32.95,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1960 BSA Gold Star DBD34",
                "price": 37.32,
            "category": "Motorcycles",
                  "action":"x"
              }
           ,
              {
                "name": "1900s Vintage Bi-Plane",
                "price": 34.25,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1900s Vintage Tri-Plane",
                "price": 36.23,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1928 British Royal Navy Airplane",
                "price": 66.74,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1980s Black Hawk Helicopter",
                "price": 77.27,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "ATA: B757-300",
                "price": 59.33,
            "category": "Planes",
                  "action":"x"
              }

        ];            

}

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

How to make CREATE OR REPLACE VIEW work in SQL Server?

SQL Server 2016 Answer

With SQL Server 2016 you can now do (MSDN Source):

DROP VIEW IF EXISTS dbo.MyView

Changing :hover to touch/click for mobile devices

I am a CSS noob but I have noticed that hover will work for touch screens so long as it's a "hoverable" element: image, link, button. You can do it all with CSS using the following trick.

Change your div background to an actual image tag within the div or create a dummy link around the entire div, it will then register as a hover when you touch the image.

Doing this will mean that you need the rest of your page to also be "hoverable" so when you touch outside of the image it recognizes that info-slide:hover has ended. My trick is to make all of my other content dummy links.

It's not very elegant but it works.

How to iterate over a string in C?

You need a pointer to the first char to have an ANSI string.

printf("%s", source + i);

will do the job

Plus, of course you should have meant strlen(source), not sizeof(source).

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

Using Math.round to round to one decimal place?

If you need this and similar operations more often, it may be more convenient to find the right library instead of implementing it yourself.

Here are one-liners solving your question from Apache Commons Math using Precision, Colt using Functions, and Weka using Utils:

double value = 540.512 / 1978.8 * 100;
// Apache commons math
double rounded1 = Precision.round(value, 1);
double rounded2 = Precision.round(value, 1, BigDecimal.ROUND_HALF_UP);
// Colt
double rounded3 = Functions.round(0.1).apply(value)
// Weka
double rounded4 = Utils.roundDouble(value, 1)

Maven dependencies:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.5</version>
</dependency>

<dependency>
    <groupId>colt</groupId>
    <artifactId>colt</artifactId>
    <version>1.2.0</version>
</dependency>

<dependency>
    <groupId>nz.ac.waikato.cms.weka</groupId>
    <artifactId>weka-stable</artifactId>
    <version>3.6.12</version>
</dependency>

How can I define colors as variables in CSS?

If you have Ruby on your system you can do this:

http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html

This was made for Rails, but see below for how to modify it to run it stand alone.

You could use this method independently from Rails, by writing a small Ruby wrapper script which works in conjunction with site_settings.rb and takes your CSS-paths into account, and which you can call every time you want to re-generate your CSS (e.g. during site startup)

You can run Ruby on pretty much any operating system, so this should be fairly platform independent.

e.g. wrapper: generate_CSS.rb (run this script whenever you need to generate your CSS)

#/usr/bin/ruby  # preferably Ruby 1.9.2 or higher
require './site_settings.rb' # assuming your site_settings file is on the same level 

CSS_IN_PATH  = File.join( PATH-TO-YOUR-PROJECT, 'css-input-files')
CSS_OUT_PATH = File.join( PATH-TO-YOUR-PROJECT, 'static' , 'stylesheets' ) 

Site.generate_CSS_files( CSS_IN_PATH , CSS_OUT_PATH )

the generate_CSS_files method in site_settings.rb then needs to be modified like this:

module Site
#   ... see above link for complete contents

  # Module Method which generates an OUTPUT CSS file *.css for each INPUT CSS file *.css.in we find in our CSS directory
  # replacing any mention of Color Constants , e.g. #SomeColor# , with the corresponding color code defined in Site::Color
  #
  # We will only generate CSS files if they are deleted or the input file is newer / modified
  #
  def self.generate_CSS_files(input_path = File.join( Rails.root.to_s , 'public' ,'stylesheets') , 
                              output_path = File.join( Rails.root.to_s , 'public' ,'stylesheets'))
    # assuming all your CSS files live under "./public/stylesheets"
    Dir.glob( File.join( input_path, '*.css.in') ).each do |filename_in|
      filename_out = File.join( output_path , File.basename( filename_in.sub(/.in$/, '') ))

      # if the output CSS file doesn't exist, or the the input CSS file is newer than the output CSS file:
      if (! File.exists?(filename_out)) || (File.stat( filename_in ).mtime > File.stat( filename_out ).mtime)
        # in this case, we'll need to create the output CSS file fresh:
        puts " processing #{filename_in}\n --> generating #{filename_out}"

        out_file = File.open( filename_out, 'w' )
        File.open( filename_in , 'r' ).each do |line|
          if line =~ /^\s*\/\*/ || line =~ /^\s+$/             # ignore empty lines, and lines starting with a comment
            out_file.print(line)
            next
          end
          while  line =~ /#(\w+)#/  do                         # substitute all the constants in each line
            line.sub!( /#\w+#/ , Site::Color.const_get( $1 ) ) # with the color the constant defines
          end
          out_file.print(line)
        end
        out_file.close
      end # if ..
    end
  end # def self.generate_CSS_files

end # module Site

Best practices for styling HTML emails

I find that image mapping works pretty well. If you have any headers or footers that are images make sure that you apply a bgcolor="fill in the blank" because outlook in most cases wont load the image and you will be left with a transparent header. If you at least designate a color that works with the over all feel of the email it will be less of a shock for the user. Never try and use any styling sheets. Or CSS at all! Just avoid it.

Depending if you're copying content from a word or shared google Doc be sure to (command+F) Find all the (') and (") and replace them within your editing software (especially dreemweaver) because they will show up as code and it's just not good.

ALT is your best friend. use the ALT tag to add in text to all your images. Because odds are they are not going to load right. And that ALT text is what gets people to click the (see images) button. Also define your images Width, Height and make the boarder 0 so you dont get weird lines around your image.

Consider editing all images within Photoshop with a 15px boarder on each side (make background transparent and save as a PNG 24) of image. Sometimes the email clients do not read any padding styles that you apply to the images so it avoids any weird formatting!

Also i found the line under links particularly annoying so if you apply < style="text-decoration:none; color:#whatever color you want here!" > it will remove the line and give you the desired look.

There is alot that can really mess with the over all look and feel.

simulate background-size:cover on <video> or <img>

jsFiddle

Using background cover is fine for images, and so is width 100%. These are not optimal for <video>, and these answers are overly complicated. You do not need jQuery or JavaScript to accomplish a full width video background.

Keep in mind that my code will not cover a background completely with a video like cover will, but instead it will make the video as big as it needs to be to maintain aspect ratio and still cover the whole background. Any excess video will bleed off the page edge, which sides depend on where you anchor the video.

The answer is quite simple.

Just use this HTML5 video code, or something along these lines: (test in Full Page)

_x000D_
_x000D_
html, body {_x000D_
  width: 100%; _x000D_
  height:100%; _x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
#vid{_x000D_
  position: absolute;_x000D_
  top: 50%; _x000D_
  left: 50%;_x000D_
  -webkit-transform: translateX(-50%) translateY(-50%);_x000D_
  transform: translateX(-50%) translateY(-50%);_x000D_
  min-width: 100%; _x000D_
  min-height: 100%; _x000D_
  width: auto; _x000D_
  height: auto;_x000D_
  z-index: -1000; _x000D_
  overflow: hidden;_x000D_
}
_x000D_
<video id="vid" video autobuffer autoplay>_x000D_
  <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">_x000D_
</video>
_x000D_
_x000D_
_x000D_

The min-height and min-width will allow the video to maintain the aspect ratio of the video, which is usually the aspect ratio of any normal browser at a normal resolution. Any excess video bleeds off the side of the page.

Cast Object to Generic Type for returning

You have to use a Class instance because of the generic type erasure during compilation.

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
    try {
        return clazz.cast(o);
    } catch(ClassCastException e) {
        return null;
    }
}

The declaration of that method is:

public T cast(Object o)

This can also be used for array types. It would look like this:

final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);

Note that when someObject is passed to convertToInstanceOfObject it has the compile time type Object.

What can be the reasons of connection refused errors?

Check at the server side that it is listening at the port 2080. First try to confirm it on the server machine by issuing telnet to that port:

telnet localhost 2080

If it is listening, it is able to respond.

Angularjs - Pass argument to directive

Controller code

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
    $scope.person = {
        name:"sangeetha PH",
       address:"first Block"
    }
}]);

Directive Code

myApp.directive('searchResult',function(){
   return{
       restrict:'AECM',
       templateUrl:'directives/search.html',
       replace: true,
       scope:{
           personName:"@",
           personAddress:"@"
       }
   } 
});

USAGE

File :directives/search.html
content:

<h1>{{personName}} </h1>
<h2>{{personAddress}}</h2>

the File where we use directive

<search-result person-name="{{person.name}}" person-address="{{person.address}}"></search-result>

How to get the real and total length of char * (char array)?

Given just the pointer, you can't. You'll have to keep hold of the length you passed to new[] or, better, use std::vector to both keep track of the length, and release the memory when you've finished with it.

Note: this answer only addresses C++, not C.

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

background: fixed no repeat not working on mobile

Thanks to the efforts of Vincent and work by Joey Hayes, I have this codepen working on android mobile that supports multiple fixed backgrounds

HTML:

<html>

<body>
  <nav>Nav to nowhere</nav>
  <article>

    <section class="bg-img bg-img1">
      <div class="content">
        <h1>Fixed backgrounds on a mobile browser</h1>
      </div>
    </section>

    <section class="solid">
      <h3>Scrolling Foreground Here</h3>
    </section>

    <section>
      <div class="content">
        <p>Quid securi etiam tamquam eu fugiat nulla pariatur. Cum ceteris in veneratione tui montes, nascetur mus. Quisque placerat facilisis egestas cillum dolore. Ambitioni dedisse scripsisse iudicaretur. Quisque ut dolor gravida, placerat libero vel,
          euismod.
        </p>
      </div>
    </section>

    <section class="solid">
      <h3>Scrolling Foreground Here</h3>
    </section>

    <section class="footer">
      <div class="content">
        <h3>The end is nigh.</h3>
      </div>
    </section>

  </article>
  </body>

CSS:

* {
  box-sizing: border-box;
}

body {
  font-family: "source sans pro";
  font-weight: 400;
  color: #fdfdfd;
}
body > section >.footer {
  overflow: hidden;
}

nav {
  position: fixed;
  top: 0;
  left: 0;
  height: 70px;
  width: 100%;
  background-color: silver;
  z-index: 999;
  text-align: center;
  font-size: 2em;
  opacity: 0.8;
}

article {
  position: relative;
  font-size: 1em;
}

section {
  height: 100vh;
  padding-top: 5em;
}

.bg-img::before {
  position: fixed;
  content: ' ';
  display: block;
  width: 100vw;
  min-height: 100vh;  
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-position: center;
  background-size: cover;
  z-index: -10; 
}

.bg-img1:before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326836/3balls_1280.jpg');
}
.bg-img2::before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326840/icebubble-1280.jpg');
}
.bg-img3::before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326844/soap-bubbles_1280.jpg');
}

h1, h2, h3 {
  font-family: lato;
  font-weight: 300;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.content {
  max-width: 50rem;
  margin: 0 auto;
}
.solid {
  min-height: 100vh;
  width: 100%;
  margin: auto;
  border: 1px solid white;
  background: rgba(255, 255, 255, 0.6);
}

.footer {
  background: rgba(2, 2, 2, 0.5);
}

JS/JQUERY

window.onload = function() {

  // Alternate Background Page with scrolling content (Bg Pages are odd#s)
  var $bgImg = $('.bg-img');
  var $nav = $('nav');
  var winh = window.innerHeight;
  var scrollPos = 0;
  var page = 1;
  var page1Bottom = winh;
  var page3Top = winh;
  var page3Bottom = winh * 3;
  var page5Top = winh * 3;
  var page5Bottom = winh * 5;

  $(window).on('scroll', function() {

    scrollPos = Number($(window).scrollTop().toFixed(2));
    page = Math.floor(Number(scrollPos / winh) +1);
    if (scrollPos >= 0 && scrollPos < page1Bottom ) {    
      if (! $bgImg.hasClass('bg-img1')) {

        removeBg( $bgImg, 2, 3, 1 ); // element, low, high, current
        $bgImg.addClass('bg-img1');
      }
    } else if (scrollPos >= page3Top && scrollPos <= page3Bottom) {
      if (! $bgImg.hasClass('bg-img2')) {

        removeBg( $bgImg, 1, 3, 2 ); // element, low, high, current
        $bgImg.addClass('bg-img2');
      }
    } else if (scrollPos >= page5Top && scrollPos <= page5Bottom) {
      if (! $bgImg.hasClass('bg-img3')) {

        removeBg( $bgImg, 1, 2, 3 ); // element, low, high, current
        $bgImg.addClass('bg-img3');
      }
    }
    $nav.html("Page# " + page + " window position: " + scrollPos);

  });
}

// This function was created to fix a problem where the mouse moves off the
// screen, this results in improper removal of background image class. Fix
// by removing any background class not applicable to current page.
function removeBg( el, low, high, current ) {
  if (low > high || low <= 0 || high <= 0) {
    console.log ("bad low/high parameters in removeBg");
  }
  for (var i=low; i<=high; i++) {
    if ( i != current ) { // avoid removing class we are trying to add
      if (el.hasClass('bg-img' +i )) {
        el.removeClass('bg-img' +i );
      }
    }
  } 
} // removeBg()

Is Xamarin free in Visual Studio 2015?

No, it only contains a free 30 day trial. But I think there would be a package if you buy Visual Studio + Xamarin.

Session variables in ASP.NET MVC

Great answers from the guys but I would caution you against always relying on the Session. It is quick and easy to do so, and of course would work but would not be great in all cicrumstances.

For example if you run into a scenario where your hosting doesn't allow session use, or if you are on a web farm, or in the example of a shared SharePoint application.

If you wanted a different solution you could look at using an IOC Container such as Castle Windsor, creating a provider class as a wrapper and then keeping one instance of your class using the per request or session lifestyle depending on your requirements.

The IOC would ensure that the same instance is returned each time.

More complicated yes, if you need a simple solution just use the session.

Here are some implementation examples below out of interest.

Using this method you could create a provider class along the lines of:

public class CustomClassProvider : ICustomClassProvider
{
    public CustomClassProvider(CustomClass customClass)
    { 
        CustomClass = customClass;
    }

    public string CustomClass { get; private set; }
}

And register it something like:

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(
            Component.For<ICustomClassProvider>().UsingFactoryMethod(
                () => new CustomClassProvider(new CustomClass())).LifestylePerWebRequest());
    }

Using scanner.nextLine()

Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.

Can I call methods in constructor in Java?

Can I put my method readConfig() into constructor?

Invoking a not overridable method in a constructor is an acceptable approach.
While if the method is only used by the constructor you may wonder if extracting it into a method (even private) is really required.

If you choose to extract some logic done by the constructor into a method, as for any method you have to choose a access modifier that fits to the method requirement but in this specific case it matters further as protecting the method against the overriding of the method has to be done at risk of making the super class constructor inconsistent.

So it should be private if it is used only by the constructor(s) (and instance methods) of the class.
Otherwise it should be both package-private and final if the method is reused inside the package or in the subclasses.

which would give me benefit of one time calling or is there another mechanism to do that ?

You don't have any benefit or drawback to use this way.
I don't encourage to perform much logic in constructors but in some cases it may make sense to init multiple things in a constructor.
For example the copy constructor may perform a lot of things.
Multiple JDK classes illustrate that.
Take for example the HashMap copy constructor that constructs a new HashMap with the same mappings as the specified Map parameter :

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

Extracting the logic of the map populating in putMapEntries() is a good thing because it allows :

  • reusing the method in other contexts. For example clone() and putAll() use it too
  • (minor but interesting) giving a meaningful name that conveys the performed logic

Center a column using Twitter Bootstrap 3

Bootstrap 3 now has a built-in class for this .center-block

.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

If you are still using 2.X then just add this to your CSS.

angular js unknown provider

For me, this error was caused by running the minified version of my angular app. Angular docs suggest a way to work around this. Here is the relevant quote describing the issue, and you can find the suggested solution in the docs themselves here:

A Note on Minification Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.

Better way to represent array in java properties file

here is another way to do by implementing yourself the mechanism. here we consider that the array should start with 0 and would have no hole between indice

    /**
     * get a string property's value
     * @param propKey property key
     * @param defaultValue default value if the property is not found
     * @return value
     */
    public static String getSystemStringProperty(String propKey,
            String defaultValue) {
        String strProp = System.getProperty(propKey);
        if (strProp == null) {
            strProp = defaultValue;
        }
        return strProp;
    }

    /**
     * internal recursive method to get string properties (array)
     * @param curResult current result
     * @param paramName property key prefix
     * @param i current indice
     * @return array of property's values
     */
    private static List<String> getSystemStringProperties(List<String> curResult, String paramName, int i) {
        String paramIValue = getSystemStringProperty(paramName + "." + String.valueOf(i), null);
        if (paramIValue == null) {
            return curResult;
        }
        curResult.add(paramIValue);
        return getSystemStringProperties(curResult, paramName, i+1);
    }

    /**
     * get the values from a property key prefix
     * @param paramName property key prefix
     * @return string array of values
     */
    public static String[] getSystemStringProperties(
            String paramName) {
        List<String> stringProperties = getSystemStringProperties(new ArrayList<String>(), paramName, 0);
        return stringProperties.toArray(new String[stringProperties.size()]);
    }

Here is a way to test :

    @Test
    public void should_be_able_to_get_array_of_properties() {
        System.setProperty("my.parameter.0", "ooO");
        System.setProperty("my.parameter.1", "oO");
        System.setProperty("my.parameter.2", "boo");
        // WHEN 
        String[] pluginParams = PropertiesHelper.getSystemStringProperties("my.parameter");

        // THEN
        assertThat(pluginParams).isNotNull();
        assertThat(pluginParams).containsExactly("ooO","oO","boo");
        System.out.println(pluginParams[0].toString());
    }

hope this helps

and all remarks are welcome..

Java; String replace (using regular expressions)?

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

Getting the parent div of element

The property pDoc.parentElement or pDoc.parentNode will get you the parent element.

How to delete a workspace in Eclipse?

Just delete the whole directory. This will delete all the projects but also the Eclipse cache and settings for the workspace. These are kept in the .metadata folder of an Eclipse workspace. Note that you can configure Eclipse to use project folders that are outside the workspace folder as well, so you may want to verify the location of each of the projects.

You can remove the workspace from the suggested workspaces by going into the General/Startup and Shutdown/Workspaces section of the preferences (via Preferences > General > Startup & Shudown > Workspaces > [Remove] ). Note that this does not remove the files itself. For old versions of Eclipse you will need to edit the org.eclipse.ui.ide.prefs file in the configuration/.settings directory under your installation directory (or in ~/.eclipse on Unix, IIRC).

How are zlib, gzip and zip related? What do they have in common and how are they different?

Short form:

.zip is an archive format using, usually, the Deflate compression method. The .gz gzip format is for single files, also using the Deflate compression method. Often gzip is used in combination with tar to make a compressed archive format, .tar.gz. The zlib library provides Deflate compression and decompression code for use by zip, gzip, png (which uses the zlib wrapper on deflate data), and many other applications.

Long form:

The ZIP format was developed by Phil Katz as an open format with an open specification, where his implementation, PKZIP, was shareware. It is an archive format that stores files and their directory structure, where each file is individually compressed. The file type is .zip. The files, as well as the directory structure, can optionally be encrypted.

The ZIP format supports several compression methods:

    0 - The file is stored (no compression)
    1 - The file is Shrunk
    2 - The file is Reduced with compression factor 1
    3 - The file is Reduced with compression factor 2
    4 - The file is Reduced with compression factor 3
    5 - The file is Reduced with compression factor 4
    6 - The file is Imploded
    7 - Reserved for Tokenizing compression algorithm
    8 - The file is Deflated
    9 - Enhanced Deflating using Deflate64(tm)
   10 - PKWARE Data Compression Library Imploding (old IBM TERSE)
   11 - Reserved by PKWARE
   12 - File is compressed using BZIP2 algorithm
   13 - Reserved by PKWARE
   14 - LZMA
   15 - Reserved by PKWARE
   16 - IBM z/OS CMPSC Compression
   17 - Reserved by PKWARE
   18 - File is compressed using IBM TERSE (new)
   19 - IBM LZ77 z Architecture 
   20 - deprecated (use method 93 for zstd)
   93 - Zstandard (zstd) Compression 
   94 - MP3 Compression 
   95 - XZ Compression 
   96 - JPEG variant
   97 - WavPack compressed data
   98 - PPMd version I, Rev 1
   99 - AE-x encryption marker (see APPENDIX E)

Methods 1 to 7 are historical and are not in use. Methods 9 through 98 are relatively recent additions and are in varying, small amounts of use. The only method in truly widespread use in the ZIP format is method 8, Deflate, and to some smaller extent method 0, which is no compression at all. Virtually every .zip file that you will come across in the wild will use exclusively methods 8 and 0, likely just method 8. (Method 8 also has a means to effectively store the data with no compression and relatively little expansion, and Method 0 cannot be streamed whereas Method 8 can be.)

The ISO/IEC 21320-1:2015 standard for file containers is a restricted zip format, such as used in Java archive files (.jar), Office Open XML files (Microsoft Office .docx, .xlsx, .pptx), Office Document Format files (.odt, .ods, .odp), and EPUB files (.epub). That standard limits the compression methods to 0 and 8, as well as other constraints such as no encryption or signatures.

Around 1990, the Info-ZIP group wrote portable, free, open-source implementations of zip and unzip utilities, supporting compression with the Deflate format, and decompression of that and the earlier formats. This greatly expanded the use of the .zip format.

In the early '90s, the gzip format was developed as a replacement for the Unix compress utility, derived from the Deflate code in the Info-ZIP utilities. Unix compress was designed to compress a single file or stream, appending a .Z to the file name. compress uses the LZW compression algorithm, which at the time was under patent and its free use was in dispute by the patent holders. Though some specific implementations of Deflate were patented by Phil Katz, the format was not, and so it was possible to write a Deflate implementation that did not infringe on any patents. That implementation has not been so challenged in the last 20+ years. The Unix gzip utility was intended as a drop-in replacement for compress, and in fact is able to decompress compress-compressed data (assuming that you were able to parse that sentence). gzip appends a .gz to the file name. gzip uses the Deflate compressed data format, which compresses quite a bit better than Unix compress, has very fast decompression, and adds a CRC-32 as an integrity check for the data. The header format also permits the storage of more information than the compress format allowed, such as the original file name and the file modification time.

Though compress only compresses a single file, it was common to use the tar utility to create an archive of files, their attributes, and their directory structure into a single .tar file, and to then compress it with compress to make a .tar.Z file. In fact, the tar utility had and still has an option to do the compression at the same time, instead of having to pipe the output of tar to compress. This all carried forward to the gzip format, and tar has an option to compress directly to the .tar.gz format. The tar.gz format compresses better than the .zip approach, since the compression of a .tar can take advantage of redundancy across files, especially many small files. .tar.gz is the most common archive format in use on Unix due to its very high portability, but there are more effective compression methods in use as well, so you will often see .tar.bz2 and .tar.xz archives.

Unlike .tar, .zip has a central directory at the end, which provides a list of the contents. That and the separate compression provides random access to the individual entries in a .zip file. A .tar file would have to be decompressed and scanned from start to end in order to build a directory, which is how a .tar file is listed.

Shortly after the introduction of gzip, around the mid-1990s, the same patent dispute called into question the free use of the .gif image format, very widely used on bulletin boards and the World Wide Web (a new thing at the time). So a small group created the PNG losslessly compressed image format, with file type .png, to replace .gif. That format also uses the Deflate format for compression, which is applied after filters on the image data expose more of the redundancy. In order to promote widespread usage of the PNG format, two free code libraries were created. libpng and zlib. libpng handled all of the features of the PNG format, and zlib provided the compression and decompression code for use by libpng, as well as for other applications. zlib was adapted from the gzip code.

All of the mentioned patents have since expired.

The zlib library supports Deflate compression and decompression, and three kinds of wrapping around the deflate streams. Those are: no wrapping at all ("raw" deflate), zlib wrapping, which is used in the PNG format data blocks, and gzip wrapping, to provide gzip routines for the programmer. The main difference between zlib and gzip wrapping is that the zlib wrapping is more compact, six bytes vs. a minimum of 18 bytes for gzip, and the integrity check, Adler-32, runs faster than the CRC-32 that gzip uses. Raw deflate is used by programs that read and write the .zip format, which is another format that wraps around deflate compressed data.

zlib is now in wide use for data transmission and storage. For example, most HTTP transactions by servers and browsers compress and decompress the data using zlib, specifically HTTP header Content-Encoding: deflate means deflate compression method wrapped inside the zlib data format.

Different implementations of deflate can result in different compressed output for the same input data, as evidenced by the existence of selectable compression levels that allow trading off compression effectiveness for CPU time. zlib and PKZIP are not the only implementations of deflate compression and decompression. Both the 7-Zip archiving utility and Google's zopfli library have the ability to use much more CPU time than zlib in order to squeeze out the last few bits possible when using the deflate format, reducing compressed sizes by a few percent as compared to zlib's highest compression level. The pigz utility, a parallel implementation of gzip, includes the option to use zlib (compression levels 1-9) or zopfli (compression level 11), and somewhat mitigates the time impact of using zopfli by splitting the compression of large files over multiple processors and cores.

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

Regarding Bruce Adams answer:

Your answer creates dangerous confusion. DESTDIR is intended for installs out of the root tree. It allows one to see what would be installed in the root tree if one did not specify DESTDIR. PREFIX is the base directory upon which the real installation is based.

For example, PREFIX=/usr/local indicates that the final destination of a package is /usr/local. Using DESTDIR=$HOME will install the files as if $HOME was the root (/). If, say DESTDIR, was /tmp/destdir, one could see what 'make install' would affect. In that spirit, DESTDIR should never affect the built objects.

A makefile segment to explain it:

install:
    cp program $DESTDIR$PREFIX/bin/program

Programs must assume that PREFIX is the base directory of the final (i.e. production) directory. The possibility of symlinking a program installed in DESTDIR=/something only means that the program does not access files based upon PREFIX as it would simply not work. cat(1) is a program that (in its simplest form) can run from anywhere. Here is an example that won't:

prog.pseudo.in:
    open("@prefix@/share/prog.db")
    ...

prog:
    sed -e "s/@prefix@/$PREFIX/" prog.pseudo.in > prog.pseudo
    compile prog.pseudo

install:
    cp prog $DESTDIR$PREFIX/bin/prog
    cp prog.db $DESTDIR$PREFIX/share/prog.db

If you tried to run prog from elsewhere than $PREFIX/bin/prog, prog.db would never be found as it is not in its expected location.

Finally, /etc/alternatives really does not work this way. There are symlinks to programs installed in the root tree (e.g. vi -> /usr/bin/nvi, vi -> /usr/bin/vim, etc.).

Concatenate two char* strings in a C program

Here is a working solution:

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

int main(int argc, char** argv) 
{
      char str1[16];
      char str2[16];
      strcpy(str1, "sssss");
      strcpy(str2, "kkkk");
      strcat(str1, str2);
      printf("%s", str1);
      return 0;
}

Output:

ssssskkkk

You have to allocate memory for your strings. In the above code, I declare str1 and str2 as character arrays containing 16 characters. I used strcpy to copy characters of string literals into them, and strcat to append the characters of str2 to the end of str1. Here is how these character arrays look like during the execution of the program:

After declaration (both are empty): 
str1: [][][][][][][][][][][][][][][][][][][][] 
str2: [][][][][][][][][][][][][][][][][][][][]

After calling strcpy (\0 is the string terminator zero byte): 
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][] 
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]

After calling strcat: 
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][] 
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]

Excel - match data from one range to another and get the value from the cell to the right of the matched data

I have added the following on my excel sheet

=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)

Still doesn't seem to work. I get an #N/A
BUT

=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)

Works

What is the difference between a data flow diagram and a flow chart?

Between the above answers its been explained but I will try to expand slightly...

The point about the cup of tea is a good one. A flow chart is concerned with the physical aspects of a task and as such is used to represent something as it is currently. This is useful in developing understanding about a situation/communication/training etc etc..You will likley have come across these in your work places, certainly if they have adopted the ISO9000 standards.

A data flow diagram is concerned with the logical aspects of an activity so again the cup of tea analogy is a good one. If you use a data flow diagram in conjunction with a process flow your data flow would only be concerned with the flow of data/information regarding a process, to the exclusion of the physical aspects. If you wonder why that would be useful then its because data flow diagrams allow us to move from the 'as it is' situation and see it that something as it could/will be. These two modelling approaches are common in structured analysis and design and typically used by systems/business analysts as part of business process improvement/re-engineering.

an htop-like tool to display disk activity in linux

nmon shows a nice display of disk activity per device. It is available for linux.

? Disk I/O ?????(/proc/diskstats)????????all data is Kbytes per second???????????????????????????????????????????????????????????????
?DiskName Busy  Read WriteKB|0          |25         |50          |75       100|                                                      ?
?sda        0%    0.0  127.9|>                                                |                                                      ?
?sda1       1%    0.0  127.9|>                                                |                                                      ?
?sda2       0%    0.0    0.0|>                                                |                                                      ?
?sda5       0%    0.0    0.0|>                                                |                                                      ?
?sdb       61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdb1      61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdc       52%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdc1      53%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdd       56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sdd1      56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sde       57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sde1      57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sdf       53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?sdf1      53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?md0        0% 1726.0 2093.6|>disk busy not available                         |                                                      ?
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

How can I nullify css property?

You have to reset each individual property back to its default value. It's not great, but it's the only way, given the information you've given us.

In your example, you would do:

.c1 {
    height: auto;
}

You should search for each property here:

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

For example, height:

Initial value : auto

Another example, max-height:

Initial value : none


In 2017, there is now another way, the unset keyword:

.c1 {
    height: unset;
}

Some documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/unset

The unset CSS keyword is the combination of the initial and inherit keywords. Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not. In other words, it behaves like the inherit keyword in the first case and like the initial keyword in the second case.

Browser support is good: http://caniuse.com/css-unset-value

How can I include null values in a MIN or MAX?

Use IsNull

SELECT recordid, MIN(startdate), MAX(IsNull(enddate, Getdate()))
FROM tmp 
GROUP BY recordid

I've modified MIN in the second instruction to MAX

How do you store Java objects in HttpSession?

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here

Zoom in on a point (using scale and translate)

I want to put here some information for those, who do separately drawing of picture and moving -zooming it.

This may be useful when you want to store zooms and position of viewport.

Here is drawer:

function redraw_ctx(){
   self.ctx.clearRect(0,0,canvas_width, canvas_height)
   self.ctx.save()
   self.ctx.scale(self.data.zoom, self.data.zoom) // 
   self.ctx.translate(self.data.position.left, self.data.position.top) // position second
   // Here We draw useful scene My task - image:
   self.ctx.drawImage(self.img ,0,0) // position 0,0 - we already prepared
   self.ctx.restore(); // Restore!!!
}

Notice scale MUST be first.

And here is zoomer:

function zoom(zf, px, py){
    // zf - is a zoom factor, which in my case was one of (0.1, -0.1)
    // px, py coordinates - is point within canvas 
    // eg. px = evt.clientX - canvas.offset().left
    // py = evt.clientY - canvas.offset().top
    var z = self.data.zoom;
    var x = self.data.position.left;
    var y = self.data.position.top;

    var nz = z + zf; // getting new zoom
    var K = (z*z + z*zf) // putting some magic

    var nx = x - ( (px*zf) / K ); 
    var ny = y - ( (py*zf) / K);

    self.data.position.left = nx; // renew positions
    self.data.position.top = ny;   
    self.data.zoom = nz; // ... and zoom
    self.redraw_ctx(); // redraw context
    }

and, of course, we would need a dragger:

this.my_cont.mousemove(function(evt){
    if (is_drag){
        var cur_pos = {x: evt.clientX - off.left,
                       y: evt.clientY - off.top}
        var diff = {x: cur_pos.x - old_pos.x,
                    y: cur_pos.y - old_pos.y}

        self.data.position.left += (diff.x / self.data.zoom);  // we want to move the point of cursor strictly
        self.data.position.top += (diff.y / self.data.zoom);

        old_pos = cur_pos;
        self.redraw_ctx();

    }


})

How to encode a string in JavaScript for displaying in HTML?

Do not bother with encoding. Use a text node instead. Data in text node is guaranteed to be treated as text.

document.body.appendChild(document.createTextNode("Your&funky<text>here"))

jQuery table sort

To the response of James I will only change the sorting function to make it more universal. This way it will sort text alphabetical and numbers like numbers.

if( $.text([a]) == $.text([b]) )
    return 0;
if(isNaN($.text([a])) && isNaN($.text([b]))){
    return $.text([a]) > $.text([b]) ? 
       inverse ? -1 : 1
       : inverse ? 1 : -1;
}
else{
    return parseInt($.text([a])) > parseInt($.text([b])) ? 
      inverse ? -1 : 1
      : inverse ? 1 : -1;
}

Are HTTP headers case-sensitive?

the Headers word are not case sensitive, but on the right like the Content-Type, is good practice to write it this way, because its case sensitve. like my example below

headers = headers.set('Content-Type'

File input 'accept' attribute - is it useful?

Back in 2008 this wasn't important because of the lack of mobile OS'es but now quite important thing.

When you set accepted mime types, then in for example Android user is given system dialog with apps which can provide him the content of mime which file input accepts, what is great because navigating through files in file explorer on mobile devices is slow and often stressful.

One important thing is that some mobile browsers (based on Android version of Chrome 36 and Chrome Beta 37) does not support app filtering over extension(s) and multiple mime types.

This Activity already has an action bar supplied by the window decor

 <style name="AppCompatTheme" parent="@style/Theme.AppCompat.Light">
            <item name="android:windowActionBar">false</item>
    </style>

    Change this to NoActionBar 

        <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
            <!-- Customize your theme here. -->

        </style>

    This one worked for me

React won't load local images

Another way to do:

First, install these modules: url-loader, file-loader

Using npm: npm install --save-dev url-loader file-loader

Next, add this to your Webpack config:

module: {
    loaders: [
      { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
  }

limit: Byte limit to inline files as Data URL

You need to install both modules: url-loader and file-loader

Finally, you can do:

<img src={require('./my-path/images/my-image.png')}/>

You can investigate these loaders further here:

url-loader: https://www.npmjs.com/package/url-loader

file-loader: https://www.npmjs.com/package/file-loader

How to replace plain URLs with links?

Try the below function :

function anchorify(text){
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  var text1=text.replace(exp, "<a href='$1'>$1</a>");
  var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
  return text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
}

alert(anchorify("Hola amigo! https://www.sharda.ac.in/academics/"));

Make a borderless form movable?

Best way I've found (modified of course)

// This adds the event handler for the control
private void AddDrag(Control Control) { Control.MouseDown += new System.Windows.Forms.MouseEventHandler(this.DragForm_MouseDown); }
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

private void DragForm_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
        // Checks if Y = 0, if so maximize the form
        if (this.Location.Y == 0) { this.WindowState = FormWindowState.Maximized; }
    }
}

To apply drag to a control simply insert this after InitializeComponent()

AddDrag(NameOfControl);

How to read a file in other directory in python

For folks like me looking at the accepted answer, and not understanding why it's not working, you need to add quotes around your sub directory, in the green checked example,

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

should actually be

x_file = open(os.path.join('direct', "5_1.txt"), "r")   

.NET Format a string with fixed spaces

You've been shown PadLeft and PadRight. This will fill in the missing PadCenter.

public static class StringUtils
{
    public static string PadCenter(this string s, int width, char c)
    {
        if (s == null || width <= s.Length) return s;

        int padding = width - s.Length;
        return s.PadLeft(s.Length + padding / 2, c).PadRight(width, c);
    }
}

Note to self: don't forget to update own CV: "One day, I even fixed Joel Coehoorn's code!" ;-D -Serge

Java Error: "Your security settings have blocked a local application from running"

My problem case was to run portecle.jnlp file locally using Java8.

What worked for me was

  1. Start Programs --> Java --> Configure Java...
  2. Go to Security --> Edit Site List...
  3. Add http://portecle.sourceforce.net
  4. Start javaws portecle.jnlp in CMD prompt

On step 3, you might try also to add file:///c:/path/portecle.jnlp, but this addition didn't help with my case.

List of Java class file format major version numbers?

These come from the class version. If you try to load something compiled for java 6 in a java 5 runtime you'll get the error, incompatible class version, got 50, expected 49. Or something like that.

See here in byte offset 7 for more info.

Additional info can also be found here.

How to detect idle time in JavaScript elegantly?

The implementation I'm proposing here is different to the other answers in the following ways:

  • the idle event (by default named 'idleTimeSeconds') is fired every 10 seconds, so you can have multiple subscribers to the same event
  • there is only one timer set per the document instance
  • the timer is fired more often then the idle event (by default every 1 second vs every 10 seconds) - this will make for the default interval precision
  • the timestamp of when the idle time started is recorded and is used to calculate the total idle time; other solutions propose to incrementally add seconds to the idle time counter, which is less prices because the actual delay of a timer may be longer than configured, see "Reasons for delays longer than specified in WindowOrWorkerGlobalScope.setTimeout()" for examples.
  • the timer is never cancelled / reset, as proposed by some other solutions; cancelling and resetting timers is more expensive

File Idle.js:

import $ from 'jquery';

export const IDLE_EVENT_NAME = 'idleTimeSeconds';

/**
 * How often an 'idleTimeSeconds' event is fired on the document instance.
 *
 * @type {number}
 */
const IDLE_EVENT_RATE_SECONDS = 10;

/**
 * How often the idle time is checked against the IDLE_EVENT_RATE_SECONDS.
 *
 * Should be much smaller than the value of IDLE_EVENT_RATE_SECONDS
 * (the smaller the value is, the more precisely the event is fired) -
 * because the actual delay may be longer, see "Reasons for delays
 * longer than specified in WindowOrWorkerGlobalScope.setTimeout() for examples":
 * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified
 *
 * @type {number}
 */
const IDLE_TIMER_RATE_SECONDS = 1;

/**
 * Because the actual timer delay may be longer, we track the timestamp
 * when the idle time started, instead of incrementally adding to the total idle time.
 * Having a starting point, we can always calculate the idle time precisely
 * without accumulating delay errors.
 *
 * @type {number}
 */
let idleStartTimeMilliseconds;

/**
 * Holds the interval reference.
 */
let idleInterval;

/**
 * Holds the value of the latest idle time value
 * for which the event was fired (integer value in seconds).
 *
 * The value is therefore factor of IDLE_EVENT_RATE_SECONDS.
 *
 * @type {number}
 */
let lastFiredSeconds;

const $document = $(document);

/**
 * Resets the idle timer.
 * Called on user interaction events, like keydown or touchstart.
 */
function resetIdleStartTime() {

    // Reset the timestamp when the idle time started
    idleStartTimeMilliseconds = (new Date).getTime();

    // Reset the latest idle time value for which the even was fired
    // (integer value in seconds).
    lastFiredSeconds = 0;
}

/**
 * Ticks every IDLE_TIMER_RATE_SECONDS, which is more often than the expected
 * idle event firing rate.
 *
 * Fires the 'idleTimeSeconds' event on the document instance.
 */
function timerCallback() {

    const nowMilliseconds = (new Date).getTime();
    const idleTimeSeconds = Math.floor((nowMilliseconds - idleStartTimeMilliseconds) / 1000);

    // When do we expect the idle event to be fired again?
    // For example, if the event firing rate is 10 seconds,
    // and last time it was fired at 40 seconds of idle time,
    // the next one will be at 40 + 10 = 50 seconds.
    const nextIdleSecondsToFire = lastFiredSeconds + IDLE_EVENT_RATE_SECONDS;

    if (idleTimeSeconds >= nextIdleSecondsToFire) {

        // Record last fired idle time that is factor of the rate,
        // so that we keep firing the event as close to the desired rate as possible
        lastFiredSeconds = nextIdleSecondsToFire;

        $document.triggerHandler(IDLE_EVENT_NAME, [idleTimeSeconds]);
    }
}

// Initialize the idle timer once only per the document instance
$(function() {

    // Start the idle timer
    idleInterval = setInterval(timerCallback, IDLE_TIMER_RATE_SECONDS * 1000);

    // Reset the idle time start timestamp
    $document.on('mousemove keydown mousedown touchstart', resetIdleStartTime);
});

Example usage (e.g. file index.js):

import {IDLE_EVENT_NAME} from './Idle';
import $ from 'jquery';

$(function() {
    $(document).on(IDLE_EVENT_NAME, function(e, idleSeconds) {
        console.log('IDLE SECONDS:', idleSeconds);
    });
});

Example output (excerpt):

IDLE SECONDS: 580
IDLE SECONDS: 590
IDLE SECONDS: 600
IDLE SECONDS: 610
IDLE SECONDS: 620
IDLE SECONDS: 630
IDLE SECONDS: 640
IDLE SECONDS: 650
IDLE SECONDS: 660
IDLE SECONDS: 670
IDLE SECONDS: 680
IDLE SECONDS: 691
IDLE SECONDS: 700
IDLE SECONDS: 710
IDLE SECONDS: 720
IDLE SECONDS: 730
IDLE SECONDS: 740
IDLE SECONDS: 750
IDLE SECONDS: 761
IDLE SECONDS: 770
IDLE SECONDS: 780
IDLE SECONDS: 790
IDLE SECONDS: 800
IDLE SECONDS: 810
IDLE SECONDS: 820
IDLE SECONDS: 830
IDLE SECONDS: 840
IDLE SECONDS: 850
IDLE SECONDS: 860
IDLE SECONDS: 871
IDLE SECONDS: 880
IDLE SECONDS: 890
IDLE SECONDS: 900
IDLE SECONDS: 910
IDLE SECONDS: 921

The output above is produced when I switch to another tab(s) and do some activities there for a while. As it can be seen, the timer is sometimes delayed (I suppose because it is not a priority for the timer to get fired with precise rate when in a background tab). But the idle timer still fires at the correct intervals +/- 1 second. In this case, 1 second is the precision of the idle timer (configured via the IDLE_TIMER_RATE_SECONDS constant in Idle.js).

Reading a simple text file

Here is a simple class that handles both raw and asset files :

public class ReadFromFile {

public static String raw(Context context, @RawRes int id) {
    InputStream is = context.getResources().openRawResource(id);
    int size = 0;
    try {
        size = is.available();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return readFile(size, is);
}

public static String asset(Context context, String fileName) {
    InputStream is = null;
    int size = 0;
    try {
        is = context.getAssets().open(fileName);
        AssetFileDescriptor fd = null;
        fd = context.getAssets().openFd(fileName);
        size = (int) fd.getLength();
        fd.close();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return readFile(size, is);
}


private static String readFile(int size, InputStream is) {
    try {
        byte buffer[] = new byte[size];
        is.read(buffer);
        is.close();
        return new String(buffer);
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

}

For example :

ReadFromFile.raw(context, R.raw.textfile);

And for asset files :

ReadFromFile.asset(context, "file.txt");

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

Here is how to build a function that returns a result set that can be queried as if it were a table:

SQL> create type emp_obj is object (empno number, ename varchar2(10));
  2  /

Type created.

SQL> create type emp_tab is table of emp_obj;
  2  /

Type created.

SQL> create or replace function all_emps return emp_tab
  2  is
  3     l_emp_tab emp_tab := emp_tab();
  4     n integer := 0;
  5  begin
  6     for r in (select empno, ename from emp)
  7     loop
  8        l_emp_tab.extend;
  9        n := n + 1;
 10       l_emp_tab(n) := emp_obj(r.empno, r.ename);
 11     end loop;
 12     return l_emp_tab;
 13  end;
 14  /

Function created.

SQL> select * from table (all_emps);

     EMPNO ENAME
---------- ----------
      7369 SMITH
      7499 ALLEN
      7521 WARD
      7566 JONES
      7654 MARTIN
      7698 BLAKE
      7782 CLARK
      7788 SCOTT
      7839 KING
      7844 TURNER
      7902 FORD
      7934 MILLER

Trying to make bootstrap modal wider

You could try:

.modal.modal-wide .modal-dialog {
  width: 90%;
}

.modal-wide .modal-body {
  overflow-y: auto;
}

Just add .modal-wide to your classes

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

How can I capitalize the first letter of each word in a string using JavaScript?

A complete and simple solution goes here:

String.prototype.replaceAt=function(index, replacement) {
        return this.substr(0, index) + replacement+ this.substr(index
  + replacement.length);
}
var str = 'k j g           u              i l  p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
    for(let i  = 0; i < str.length-1; i++) {
        if(str[i] === ' ' && str[i+1] !== '')
            str = str.replaceAt(i+1, str[i+1].toUpperCase());
    }
    return str.replaceAt(0, str[0].toUpperCase()).replace(/\s+/g, ' ');
}
console.log(capitalizeAndRemoveMoreThanOneSpaceInAString(str));

The equivalent of a GOTO in python

answer = None
while True:
    answer = raw_input("Do you like pie?")
    if answer in ("yes", "no"): break
    print "That is not a yes or a no"

Would give you what you want with no goto statement.

Check if application is on its first run

There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings! a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever the user launches the app you request the server and check if it's there in your database or it is new.

How do I preserve line breaks when getting text from a textarea?

Similar questions are here

detect line breaks in a text area input

detect line break in textarea

You can try this:

_x000D_
_x000D_
var submit = document.getElementById('submit');_x000D_
_x000D_
submit.addEventListener('click', function(){_x000D_
var textContent = document.querySelector('textarea').value;_x000D_
  _x000D_
document.getElementById('output').innerHTML = textContent.replace(/\n/g, '<br/>');_x000D_
  _x000D_
_x000D_
});
_x000D_
<textarea cols=30 rows=10 >This is some text_x000D_
this is another text_x000D_
_x000D_
Another text again and again</textarea>_x000D_
<input type='submit' id='submit'>_x000D_
_x000D_
_x000D_
<p id='output'></p>
_x000D_
_x000D_
_x000D_

document.querySelector('textarea').value; will get the text content of the textarea and textContent.replace(/\n/g, '<br/>') will find all the newline character in the source code /\n/g in the content and replace it with the html line-break <br/>.


Another option is to use the html <pre> tag. See the demo below

_x000D_
_x000D_
var submit = document.getElementById('submit');_x000D_
_x000D_
submit.addEventListener('click', function(){_x000D_
_x000D_
  var content = '<pre>';_x000D_
  _x000D_
  var textContent = document.querySelector('textarea').value;_x000D_
  _x000D_
  content += textContent;_x000D_
  _x000D_
  content += '</pre>';_x000D_
_x000D_
  document.getElementById('output').innerHTML = content;_x000D_
_x000D_
});
_x000D_
<textarea cols=30 rows=10>This is some text_x000D_
this is another text_x000D_
_x000D_
Another text again and again </textarea>_x000D_
<input type='submit' id='submit'>_x000D_
_x000D_
<div id='output'> </div>
_x000D_
_x000D_
_x000D_

Purge or recreate a Ruby on Rails database

You can use this following command line:

rake db:drop db:create db:migrate db:seed db:test:clone

How to convert an int array to String with toString method in Java

Very much agreed with @Patrik M, but the thing with Arrays.toString is that it includes "[" and "]" and "," in the output. So I'll simply use a regex to remove them from outout like this

String strOfInts = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", "");

and now you have a String which can be parsed back to java.lang.Number, for example,

long veryLongNumber = Long.parseLong(intStr);

Or you can use the java 8 streams, if you hate regex,

String strOfInts = Arrays
            .stream(intArray)
            .mapToObj(String::valueOf)
            .reduce((a, b) -> a.concat(",").concat(b))
            .get();

How to parse month full form string using DateFormat in Java?

You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.

Try specifying the locale you wish to use, for example Locale.US:

DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27,  2007");

Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.

The type java.lang.CharSequence cannot be resolved in package declaration

"Java 8 support for Eclipse Kepler SR2", and the new "JavaSE-1.8" execution environment showed up automatically.

Download this one:- Eclipse kepler SR2

and then follow this link:- Eclipse_Java_8_Support_For_Kepler

Getting request URL in a servlet

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

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

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

JavaScript regex for alphanumeric string with length of 3-5 chars

add {3,5} to your expression which means length between 3 to 5

/^([a-zA-Z0-9_-]){3,5}$/

C# Clear all items in ListView

Try this ...

myListView.DataSource = null;
myListView.Items.Clear();

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How should I read a file line-by-line in Python?

Yes,

with open('filename.txt') as fp:
    for line in fp:
        print line

is the way to go.

It is not more verbose. It is more safe.

How can I exit from a javascript function?

you can use

return false; or return; within your condition.

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ....
    if(some_condition) {
      return false;
    }
}

How to resize the jQuery DatePicker control

Another approach:

$('.your-container').datepicker({
    beforeShow: function(input, datepickerInstance) {
        datepickerInstance.dpDiv.css('font-size', '11px');
    }
});

Textarea to resize based on content length

You can achieve this by using a span and a textarea.

You have to update the span with the text in textarea each time the text is changed. Then set the css width and height of the textarea to the span's clientWidth and clientHeight property.

Eg:

.textArea {
    border: #a9a9a9 1px solid;
    overflow: hidden;
    width:  expression( document.getElementById("spnHidden").clientWidth );
    height: expression( document.getElementById("spnHidden").clientHeight );
}

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

Setting the filter to an OpenFileDialog to allow the typical image formats?

For those who don't want to remember the syntax everytime here is a simple encapsulation:

public class FileDialogFilter : List<string>
{
    public string Explanation { get; }

    public FileDialogFilter(string explanation, params string[] extensions)
    {
        Explanation = explanation;
        AddRange(extensions);
    }

    public string GetFileDialogRepresentation()
    {
        if (!this.Any())
        {
            throw new ArgumentException("No file extension is defined.");
        }

        StringBuilder builder = new StringBuilder();

        builder.Append(Explanation);

        builder.Append(" (");
        builder.Append(String.Join(", ", this));
        builder.Append(")");

        builder.Append("|");
        builder.Append(String.Join(";", this));

        return builder.ToString();
    }
}

public class FileDialogFilterCollection : List<FileDialogFilter>
{
    public string GetFileDialogRepresentation()
    {
        return String.Join("|", this.Select(filter => filter.GetFileDialogRepresentation()));
    }
}

Usage:

FileDialogFilter filterImage = new FileDialogFilter("Image Files", "*.jpeg", "*.bmp");
FileDialogFilter filterOffice = new FileDialogFilter("Office Files", "*.doc", "*.xls", "*.ppt");

FileDialogFilterCollection filters = new FileDialogFilterCollection
{
    filterImage,
    filterOffice
};

OpenFileDialog fileDialog = new OpenFileDialog
{
    Filter = filters.GetFileDialogRepresentation()
};

fileDialog.ShowDialog();

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []