text:
<?php

class Dibspw_Dibspw_Model_Sales_Order_Total_Creditmemo_Fee extends Mage_Sales_Model_Order_Creditmemo_Total_Abstract
{
	public function collect(Mage_Sales_Model_Order_Creditmemo $creditmemo)
	{
		$order = $creditmemo->getOrder();
		$feeAmountLeft = $order->getFeeAmountInvoiced() - $order->getFeeAmountRefunded();
		$basefeeAmountLeft = $order->getBaseFeeAmountInvoiced() - $order->getBaseFeeAmountRefunded();
		if ($basefeeAmountLeft > 0) {
			$creditmemo->setGrandTotal($creditmemo->getGrandTotal() + $feeAmountLeft);
			$creditmemo->setBaseGrandTotal($creditmemo->getBaseGrandTotal() + $basefeeAmountLeft);
			$creditmemo->setFeeAmount($feeAmountLeft);
			$creditmemo->setBaseFeeAmount($basefeeAmountLeft);
		}
		return $this;
	}
}


text:
(function(){
  'use strict';

  angular.module('officeAddin')
         .controller('homeController', homeController);

  /**
   * Controller constructor
   */
  function homeController(){
    var vm = this;  // jshint ignore:line
    var userId = Office.context.mailbox.item.from.emailAddress.split('@')[0];
    vm.userId = userId;
    console.log(userId);
    vm.dataObject = {};

    //getDataFromService();

    // var request = {
    //         url: 'https://gateway.marvel.com/v1/public/characters/'+userId+'?apikey=326b9124ce39cf26bf0c3746d03d5e73&hash=9921fd504791b84506e01303bb73edbe&ts=1',
    //         method: 'GET'
    //     }
    //     $http(request).then(function(response){
    //         $log.debug(response);
    //         if(response.data !== null){
    //             vm.data = response.data;
    //         }
    //     },function(error){
    //         $log.debug(error);
    //     })
  }

})();

redpajama_set_name: RedPajamaGithub


text:
    <!doctype html>
    <html lang="en">
    <head>

    {% include meta.html %}

    <title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.name }} – {{ site.description }}</title>
    <link rel="stylesheet" href="{{ site.url }}/css/style.css">
    <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
    <link rel="icon" href="{{ site.url }}/images/RWICON.png">
    </head>
    <body>

        {{ content }}

    <script id="dsq-count-scr" src="//robert-wadsworth.disqus.com/count.js" async></script>

    </body>
    {% include analytics.html %}

    </html>


text:
package pl.grzeslowski.jsupla.protocol.impl.encoders;

import org.junit.Test;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import pl.grzeslowski.jsupla.protocol.api.encoders.Encoder;
import pl.grzeslowski.jsupla.protocol.api.encoders.PrimitiveEncoder;
import pl.grzeslowski.jsupla.protocol.api.types.ProtoWithSize;

import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyByte;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static pl.grzeslowski.jsupla.protocol.api.consts.JavaConsts.BYTE_SIZE;
import static pl.grzeslowski.jsupla.protocol.api.consts.JavaConsts.INT_SIZE;
import static pl.grzeslowski.jsupla.protocol.api.consts.JavaConsts.LONG_SIZE;

@SuppressWarnings("WeakerAccess")
public abstract class EncoderTest<ProtoT extends ProtoWithSize> {
    @Mock protected PrimitiveEncoder primitiveEncoder;

    protected void givenEncodeEntity() {
        given(primitiveEncoder.writeByte(anyByte(), any(), anyInt())).willReturn(BYTE_SIZE);
        given(primitiveEncoder.writeUnsignedByte(anyByte(), any(), anyInt())).willReturn(BYTE_SIZE);
        given(primitiveEncoder.writeInteger(anyInt(), any(), anyInt())).willReturn(INT_SIZE);
        given(primitiveEncoder.writeLong(anyLong(), any(), anyInt())).willReturn(LONG_SIZE);
        given(primitiveEncoder.writeUnsignedInteger(anyInt(), any(), anyInt())).willReturn(INT_SIZE);
        given(primitiveEncoder.writeBytes(any(byte[].class), any(), anyInt())).willAnswer(new Answer<Integer>() {
            @Override
            public Integer answer(final InvocationOnMock invocationOnMock) throws Throwable {
                return invocationOnMock.getArgumentAt(0, byte[].class).length;
            }
        });
    }

    @Test
    public final void shouldEncodeEntity() throws Exception {

        // given
        givenEncodeEntity();
        final ProtoT proto = getProto();

        // when
        final byte[] encode = getEncoder().encode(proto);

        // then
        verifyEncodeEntity(encode, proto);
        verifyNoMoreInteractions(primitiveEncoder);
    }

    protected abstract void verifyEncodeEntity(final byte[] encode, final ProtoT proto);

    @Test(expected = NullPointerException.class)
    public abstract void shouldThrowNpeWhenPrimitiveParserIsNull() throws Exception;

    public abstract Encoder<ProtoT> getEncoder();

    public abstract ProtoT getProto();

    protected final byte[] bytesToWriteInto() {
        return bytesToWriteInto(getProto());
    }

    protected final byte[] bytesToWriteInto(ProtoT proto) {
        return new byte[proto.size()];
    }
}


text:
            ×

Trigger details

                Identity

                Summary

                Schedule

                Job Data Map

            Close


text:
using System.Runtime.CompilerServices;

namespace System.Html {
	[Imported, Serializable]
	public partial class AnimationEventInit : EventInit {
		public string AnimationName {
			get;
			set;
		}

		public double ElapsedTime {
			get;
			set;
		}

		public string PseudoElement {
			get;
			set;
		}
	}
}


text:
package com.vmware.vim25;

/**
 * @author Steve Jin (http://www.doublecloud.org)
 * @version 5.1
 */

@SuppressWarnings("all")
public class OvfConsumerCommunicationError extends OvfConsumerCallbackFault {
    public String description;

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}


text:
/* global app:true */

(function() {
  'use strict';

  app = app || {};

  app.Signup = Backbone.Model.extend({
    url: '/signup/',
    defaults: {
      errors: [],
      errfor: {},
      username: '',
      email: '',
      password: '',
      password2: ''
    }
  });

  app.SignupView = Backbone.View.extend({
    el: '#signup',
    template: _.template( $('#tmpl-signup').html() ),
    events: {
      'submit form': 'preventSubmit',
      'keypress [name="password"]': 'signupOnEnter',
      'click .btn-signup': 'signup'
    },
    initialize: function() {
      this.model = new app.Signup();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes ));
      this.$el.find('[name="username"]').focus();
    },
    preventSubmit: function(event) {
      event.preventDefault();
    },
    signupOnEnter: function(event) {
      if (event.keyCode !== 13) { return; }
      if ($(event.target).attr('name') !== 'password') { return; }
      event.preventDefault();
      this.signup();
    },
    signup: function() {
      this.$el.find('.btn-signup').attr('disabled', true);

      this.model.save({
        username: this.$el.find('[name="username"]').val(),
        email: this.$el.find('[name="email"]').val(),
        password: this.$el.find('[name="password"]').val(),
        password2: this.$el.find('[name="password2"]').val()
      },{
        success: function(model, response) {
          if (response.success) {
            location.href = '/account/';
          }
          else {
            model.set(response);
          }
        }
      });
    }
  });

  $(document).ready(function() {
    app.signupView = new app.SignupView();
  });
}());


text:
package com.jivesoftware.addons.example.services;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.codahale.metrics.annotation.Timed;
import com.jivesoftware.sdk.definition.api.tile.TileRegister;
import com.jivesoftware.sdk.definition.api.tile.TileUnregister;
import com.jivesoftware.sdk.services.jersey.filters.JiveAuthorizationValidation;

@Path("/tile")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TileService {

    @POST
    @Path("/register")
    @JiveAuthorizationValidation
    @Timed
    public Response register(TileRegister data) {
        return Response.ok().entity("{ \"status\": \"tile registered\" }").build();
    }

    @POST
    @Path("/unregister")
    @Timed
    @JiveAuthorizationValidation
    public Response unregister(TileUnregister data) {
        return Response.ok().entity("{ \"status\": \"tile unregistered\" }").build();
    }
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.ntp;

import android.os.Environment;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;

import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.DisableIf;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.UrlConstants;
import org.chromium.chrome.browser.omnibox.LocationBarLayout;
import org.chromium.chrome.browser.omnibox.UrlBar;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeTabbedActivityTestBase;
import org.chromium.chrome.test.util.ChromeTabUtils;
import org.chromium.chrome.test.util.NewTabPageTestUtils;
import org.chromium.chrome.test.util.OmniboxTestUtils;
import org.chromium.content.browser.test.util.CallbackHelper;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import org.chromium.content.browser.test.util.KeyUtils;
import org.chromium.content.browser.test.util.TestTouchUtils;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.util.TestWebServer;
import org.chromium.ui.base.PageTransition;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Tests for the native android New Tab Page.
 */
public class NewTabPageTest extends ChromeTabbedActivityTestBase {

    private static final String TEST_PAGE = "/chrome/test/data/android/navigate/simple.html";

    private static final String[] FAKE_MOST_VISITED_TITLES = new String[] { "Simple" };
    private static final String[] FAKE_MOST_VISITED_WHITELIST_ICON_PATHS = new String[] { "" };

    private Tab mTab;
    private NewTabPage mNtp;
    private View mFakebox;
    private ViewGroup mMostVisitedLayout;
    private String[] mFakeMostVisitedUrls;
    private FakeMostVisitedSites mFakeMostVisitedSites;
    private EmbeddedTestServer mTestServer;

    @Override
    protected void setUp() throws Exception {
        mTestServer = EmbeddedTestServer.createAndStartFileServer(
                getInstrumentation().getContext(), Environment.getExternalStorageDirectory());
        mFakeMostVisitedUrls = new String[] { mTestServer.getURL(TEST_PAGE) };
        super.setUp();
    }

    @Override
    protected void tearDown() throws Exception {
        mTestServer.stopAndDestroyServer();
        super.tearDown();
    }

    @Override
    public void startMainActivity() throws InterruptedException {
        startMainActivityOnBlankPage();
        mTab = getActivity().getActivityTab();

        try {
            runTestOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Create FakeMostVisitedSites after starting the activity, since it depends on
                    // native code.
                    mFakeMostVisitedSites =
                            new FakeMostVisitedSites(mTab.getProfile(), FAKE_MOST_VISITED_TITLES,
                                    mFakeMostVisitedUrls, FAKE_MOST_VISITED_WHITELIST_ICON_PATHS);
                }
            });
        } catch (Throwable t) {
            fail(t.getMessage());
        }
        NewTabPage.setMostVisitedSitesForTests(mFakeMostVisitedSites);

        loadUrl(UrlConstants.NTP_URL);
        NewTabPageTestUtils.waitForNtpLoaded(mTab);

        assertTrue(mTab.getNativePage() instanceof NewTabPage);
        mNtp = (NewTabPage) mTab.getNativePage();
        mFakebox = mNtp.getView().findViewById(R.id.search_box);
        mMostVisitedLayout = (ViewGroup) mNtp.getView().findViewById(R.id.most_visited_layout);
        assertEquals(mFakeMostVisitedUrls.length, mMostVisitedLayout.getChildCount());
    }

    /**
     * Tests that clicking on the fakebox causes it to animate upwards and focus the omnibox, and
     * defocusing the omnibox causes the fakebox to animate back down.
     */
    @SmallTest
    @Feature({"NewTabPage"})
    public void testFocusFakebox() throws InterruptedException {
        int initialFakeboxTop = getFakeboxTop(mNtp);

        singleClickView(mFakebox);
        waitForFakeboxFocusAnimationComplete(mNtp);
        UrlBar urlBar = (UrlBar) getActivity().findViewById(R.id.url_bar);
        OmniboxTestUtils.waitForFocusAndKeyboardActive(urlBar, true);
        int afterFocusFakeboxTop = getFakeboxTop(mNtp);
        assertTrue(afterFocusFakeboxTop < initialFakeboxTop);

        OmniboxTestUtils.toggleUrlBarFocus(urlBar, false);
        waitForFakeboxTopPosition(mNtp, initialFakeboxTop);
        OmniboxTestUtils.waitForFocusAndKeyboardActive(urlBar, false);
    }

    /**
     * Tests that clicking on the fakebox causes it to focus the omnibox and allows typing and
     * navigating to a URL.
     */
    @SmallTest
    @Feature({"NewTabPage"})
    @DisableIf.Build(sdk_is_greater_than = 22, message = "crbug.com/593007")
    public void testSearchFromFakebox() throws InterruptedException {
        singleClickView(mFakebox);
        waitForFakeboxFocusAnimationComplete(mNtp);
        final UrlBar urlBar = (UrlBar) getActivity().findViewById(R.id.url_bar);
        OmniboxTestUtils.waitForFocusAndKeyboardActive(urlBar, true);

        getInstrumentation().sendStringSync(TEST_PAGE);
        LocationBarLayout locationBar =
                (LocationBarLayout) getActivity().findViewById(R.id.location_bar);
        OmniboxTestUtils.waitForOmniboxSuggestions(locationBar);

        ChromeTabUtils.waitForTabPageLoaded(mTab, new Runnable() {
            @Override
            public void run() {
                KeyUtils.singleKeyEventView(getInstrumentation(), urlBar, KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    /**
     * Tests clicking on a most visited item.
     */
    @SmallTest
    @Feature({"NewTabPage"})
    public void testClickMostVisitedItem() throws InterruptedException {
        ChromeTabUtils.waitForTabPageLoaded(mTab, new Runnable() {
            @Override
            public void run() {
                View mostVisitedItem = mMostVisitedLayout.getChildAt(0);
                singleClickView(mostVisitedItem);
            }
        });
        assertEquals(mFakeMostVisitedUrls[0], mTab.getUrl());
    }

    /**
     * Tests opening a most visited item in a new tab.
     */
    @DisabledTest // Flaked on the try bot. http://crbug.com/543138
    @SmallTest
    @Feature({"NewTabPage"})
    public void testOpenMostVisitedItemInNewTab() throws InterruptedException {
        invokeContextMenuAndOpenInANewTab(mMostVisitedLayout.getChildAt(0),
                NewTabPage.ID_OPEN_IN_NEW_TAB, false, mFakeMostVisitedUrls[0]);
    }

    /**
     * Tests opening a most visited item in a new incognito tab.
     */
    @SmallTest
    @Feature({"NewTabPage"})
    public void testOpenMostVisitedItemInIncognitoTab() throws InterruptedException {
        invokeContextMenuAndOpenInANewTab(mMostVisitedLayout.getChildAt(0),
                NewTabPage.ID_OPEN_IN_INCOGNITO_TAB, true, mFakeMostVisitedUrls[0]);
    }

    /**
     * Tests deleting a most visited item.
     */
    @SmallTest
    @Feature({"NewTabPage"})
    public void testRemoveMostVisitedItem() {
        View mostVisitedItem = mMostVisitedLayout.getChildAt(0);
        ArrayList<View> views = new ArrayList<View>();
        mMostVisitedLayout.findViewsWithText(views, FAKE_MOST_VISITED_TITLES[0],
                View.FIND_VIEWS_WITH_TEXT);
        assertEquals(1, views.size());

        TestTouchUtils.longClickView(getInstrumentation(), mostVisitedItem);
        assertTrue(getInstrumentation().invokeContextMenuAction(getActivity(),
                NewTabPage.ID_REMOVE, 0));

        assertTrue(mFakeMostVisitedSites.isUrlBlacklisted(mFakeMostVisitedUrls[0]));
    }

    @MediumTest
    @Feature({"NewTabPage"})
    public void testUrlFocusAnimationsDisabledOnLoad() throws InterruptedException {
        assertFalse(getUrlFocusAnimatonsDisabled());
        ChromeTabUtils.waitForTabPageLoaded(mTab, new Runnable() {
            @Override
            public void run() {
                ThreadUtils.runOnUiThreadBlocking(new Runnable() {
                    @Override
                    public void run() {
                        int pageTransition =
                                PageTransition.TYPED | PageTransition.FROM_ADDRESS_BAR;
                        mTab.loadUrl(new LoadUrlParams(mTestServer.getURL(TEST_PAGE),
                                pageTransition));
                        // It should be disabled as soon as a load URL is triggered.
                        assertTrue(getUrlFocusAnimatonsDisabled());
                    }
                });
            }
        });
        // Ensure it is still marked as disabled once the new page is fully loaded.
        assertTrue(getUrlFocusAnimatonsDisabled());
    }

    @LargeTest
    @Feature({"NewTagPage"})
    public void testUrlFocusAnimationsEnabledOnFailedLoad() throws Exception {
        // TODO(jbudorick): switch this to EmbeddedTestServer.
        TestWebServer webServer = TestWebServer.start();
        try {
            final Semaphore delaySemaphore = new Semaphore(0);
            Runnable delayAction = new Runnable() {
                @Override
                public void run() {
                    try {
                        assertTrue(delaySemaphore.tryAcquire(10, TimeUnit.SECONDS));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            final String testPageUrl = webServer.setResponseWithRunnableAction(
                    "/ntp_test.html",
                    "", null, delayAction);

            assertFalse(getUrlFocusAnimatonsDisabled());

            clickFakebox();
            UrlBar urlBar = (UrlBar) getActivity().findViewById(R.id.url_bar);
            OmniboxTestUtils.waitForFocusAndKeyboardActive(urlBar, true);
            typeInOmnibox(testPageUrl, false);
            LocationBarLayout locationBar =
                    (LocationBarLayout) getActivity().findViewById(R.id.location_bar);
            OmniboxTestUtils.waitForOmniboxSuggestions(locationBar);

            final CallbackHelper loadedCallback = new CallbackHelper();
            mTab.addObserver(new EmptyTabObserver() {
                @Override
                public void onPageLoadFinished(Tab tab) {
                    loadedCallback.notifyCalled();
                    tab.removeObserver(this);
                }
            });

            final View v = urlBar;
            KeyUtils.singleKeyEventView(getInstrumentation(), v, KeyEvent.KEYCODE_ENTER);

            waitForUrlFocusAnimationsDisabledState(true);
            waitForTabLoading();

            ThreadUtils.runOnUiThreadBlocking(new Runnable() {
                @Override
                public void run() {
                    mTab.stopLoading();
                }
            });
            waitForUrlFocusAnimationsDisabledState(false);
            delaySemaphore.release();
            loadedCallback.waitForCallback(0);
            assertFalse(getUrlFocusAnimatonsDisabled());
        } finally {
            webServer.shutdown();
        }
    }

    private boolean getUrlFocusAnimatonsDisabled() {
        return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return mNtp.getNewTabPageView().urlFocusAnimationsDisabled();
            }
        });
    }

    private void waitForUrlFocusAnimationsDisabledState(boolean disabled)
            throws InterruptedException {
        CriteriaHelper.pollInstrumentationThread(Criteria.equals(disabled, new Callable<Boolean>() {
            @Override
            public Boolean call() {
                return getUrlFocusAnimatonsDisabled();
            }
        }));
    }

    private void waitForTabLoading() throws InterruptedException {
        CriteriaHelper.pollUiThread(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return mTab.isLoading();
            }
        });
    }

    private void waitForFakeboxFocusAnimationComplete(NewTabPage ntp) throws InterruptedException {
        waitForUrlFocusPercent(ntp, 1f);
    }

    private void waitForUrlFocusPercent(final NewTabPage ntp, float percent)
            throws InterruptedException {
        CriteriaHelper.pollUiThread(Criteria.equals(percent, new Callable<Float>() {
            @Override
            public Float call() {
                return ntp.getNewTabPageView().getUrlFocusChangeAnimationPercent();
            }
        }));
    }

    private void clickFakebox() {
        View fakebox = mNtp.getView().findViewById(R.id.search_box);
        singleClickView(fakebox);
    }

    /**
     * @return The position of the top of the fakebox relative to the window.
     */
    private int getFakeboxTop(final NewTabPage ntp) {
        return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Integer>() {
            @Override
            public Integer call() {
                final View fakebox = ntp.getView().findViewById(R.id.search_box);
                int[] location = new int[2];
                fakebox.getLocationInWindow(location);
                return location[1];
            }
        });
    }

    /**
     * Waits until the top of the fakebox reaches the given position.
     */
    private void waitForFakeboxTopPosition(final NewTabPage ntp, int position)
            throws InterruptedException {
        CriteriaHelper.pollUiThread(Criteria.equals(position, new Callable<Integer>() {
            @Override
            public Integer call() {
                return getFakeboxTop(ntp);
            }
        }));
    }
}


text:
using System;
using System.Reflection.Emit;
using WebAssembly.Runtime.Compilation;

namespace WebAssembly.Instructions;

/// <summary>
/// Provides shared functionality for instructions that do truncation with saturation.
/// </summary>
public abstract class TruncateSaturateInstruction : MiscellaneousInstruction
{
    private protected TruncateSaturateInstruction()
        : base()
    {
    }

    private protected abstract WebAssemblyValueType InputValueType { get; }
    private protected abstract WebAssemblyValueType OutputValueType { get; }
    private protected abstract HelperMethod ConversionHelper { get; }
    private protected abstract Type InputType { get; }
    private protected abstract Type OutputType { get; }

    internal sealed override void Compile(CompilationContext context)
    {
        var stack = context.Stack;

        context.PopStackNoReturn(this.OpCode, InputValueType);

        context.Emit(OpCodes.Call, context[ConversionHelper, (helper, c) =>
        {
            var builder = c.CheckedExportsBuilder.DefineMethod(
                $"☣ {ConversionHelper}",
                CompilationContext.HelperMethodAttributes,
                OutputType,
                new[] { InputType }
            );

                // The following code is an IL version of this C#,
                // with "float" and "int" replaced by "double" and "uint"
                // as appropriate for the overriding class:
                //
                // public static int Int32TruncateSaturateFloat32Signed(float f)
                // {
                //     if (f >= int.MaxValue)
                //         return int.MaxValue;
                //
                //     if (f <= int.MinValue)
                //         return int.MinValue;
                //
                //     if (float.IsNaN(f))
                //         return 0;
                //
                //     return (int)f;
                // }

                var il = builder.GetILGenerator();

            var notAboveRangeLabel = il.DefineLabel();
            var notBelowRangeLabel = il.DefineLabel();
            var notNaNLabel = il.DefineLabel();

                // if (f >= int.MaxValue)
                il.Emit(OpCodes.Ldarg_0);
            EmitLoadFloatMaxValue(il);
            il.Emit(OpCodes.Blt_Un_S, notAboveRangeLabel);

                // return int.MaxValue
                EmitLoadIntegerMaxValue(il);
            il.Emit(OpCodes.Ret);

                // if (f <= int.MinValue)
                il.MarkLabel(notAboveRangeLabel);
            il.Emit(OpCodes.Ldarg_0);
            EmitLoadFloatMinValue(il);
            il.Emit(OpCodes.Bgt_Un_S, notBelowRangeLabel);

                // return int.MinValue
                EmitLoadIntegerMinValue(il);
            il.Emit(OpCodes.Ret);

                // if (float.IsNaN(f))
                il.MarkLabel(notBelowRangeLabel);
            il.Emit(OpCodes.Ldarg_0);
            il.EmitCall(OpCodes.Call, InputType.GetMethod(nameof(float.IsNaN))!, null);
            il.Emit(OpCodes.Brfalse_S, notNaNLabel);

                // return 0
                EmitLoadIntegerZero(il);
            il.Emit(OpCodes.Ret);

                // return (int)f
                il.MarkLabel(notNaNLabel);
            il.Emit(OpCodes.Ldarg_0);
            EmitConvert(il);
            il.Emit(OpCodes.Ret);

            return builder;
        }
        ]);

        stack.Push(OutputValueType);
    }

    private protected abstract void EmitLoadFloatMaxValue(ILGenerator il);
    private protected abstract void EmitLoadIntegerMaxValue(ILGenerator il);
    private protected abstract void EmitLoadFloatMinValue(ILGenerator il);
    private protected abstract void EmitLoadIntegerMinValue(ILGenerator il);
    private protected abstract void EmitLoadIntegerZero(ILGenerator il);
    private protected abstract void EmitConvert(ILGenerator il);
}


text:
#include <statement.hpp>
#include <resultset.hpp>
#include <logger.hpp>
#include <odbcerror.hpp>
#include <sqlexception.hpp>

namespace cppsqlx
{

Statement::Statement(SQLHENV henv,SQLHDBC hdbc):_henv(henv),_hdbc(hdbc)
{
    SQLAllocHandle(SQL_HANDLE_STMT, _hdbc, &_hstmt);
    LOG_DEBUG("Statement::Statement");
}

Statement::~Statement()
{
   LOG_DEBUG("Statement::~Statement");
}

std::shared_ptr<Resultset>   Statement::executeQuery(std::string query)
{
    SQLRETURN retcode = SQLExecDirect(_hstmt, (SQLCHAR*)query.c_str(), SQL_NTS);
    if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
    {
       if(retcode == SQL_SUCCESS_WITH_INFO)
       {
          ODBCError err;
          LOG_WARN(err("SQLExecDirect", _hstmt, SQL_HANDLE_STMT));
       }
       std::shared_ptr<Resultset> resultset(new Resultset(_henv,_hdbc,_hstmt));
       return move(resultset);
    }
    else
    {
       if(retcode == SQL_INVALID_HANDLE)
       {
          throw SQLException("Statement object is invalid, see associated connection object");
       }
       ODBCError err;
       throw SQLException(err("SQLExecDirect", _hstmt, SQL_HANDLE_STMT));
    }
}

int  Statement::executeUpdate(std::string query)
{
    SQLINTEGER value;
    SQLRETURN retcode = SQLExecDirect(_hstmt, (SQLCHAR*)query.c_str(), SQL_NTS);
    if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
    {
       if(retcode == SQL_SUCCESS_WITH_INFO)
       {
          ODBCError err;
          LOG_WARN(err("SQLExecDirect", _hstmt, SQL_HANDLE_STMT));
       }

       SQLRETURN retcode = SQLRowCount(_hstmt,(SQLLEN*)&value);
       return (int)value;
    }
    else
    {
       ODBCError err;
       LOG_ERROR(err("SQLExecDirect", _hstmt, SQL_HANDLE_STMT));
       throw SQLException(err("SQLExecDirect", _hstmt, SQL_HANDLE_STMT));
       return 0;
    }
}

void Statement::execute(std::string query)
{
    SQLINTEGER value;
    SQLRETURN retcode = SQLExecDirect(_hstmt, (SQLCHAR*)query.c_str(), SQL_NTS);
    if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
    {
       if(retcode == SQL_SUCCESS_WITH_INFO)
       {
          ODBCError err;
          LOG_WARN(err("SQLExecDirect", _hstmt, SQL_HANDLE_STMT));
       }
    }
    else
    {
       ODBCError err;
       LOG_ERROR(err("SQLExecDirect", _hstmt, SQL_HANDLE_STMT));
       throw SQLException(err("SQLExecDirect", _hstmt, SQL_HANDLE_STMT));
    }
}

};/*namespace cppsqlx*/


text:
package com.svbio.cloudkeeper.testkit;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;

/**
 * {@link Executor} implementation that runs all tasks in the current thread upon invocation of {@link #executeNext()}
 * or {@link #executeAll()}.
 */
public final class CallingThreadExecutor implements Executor {
    private final ConcurrentLinkedQueue<Task> pendingTasks = new ConcurrentLinkedQueue<>();

    private static final class Task {
        private final long submissionTimeMillis;
        private final StackTraceElement[] stackTrace;
        private final Runnable runnable;

        private Task(Runnable runnable) {
            submissionTimeMillis = System.currentTimeMillis();
            stackTrace = Thread.currentThread().getStackTrace();
            this.runnable = runnable;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder(256);
            builder.append("Task submitted at time ").append(submissionTimeMillis);
            if (stackTrace.length > 0) {
                for (StackTraceElement element: stackTrace) {
                    builder.append("\n\tat ").append(element);
                }
            }
            return builder.toString();
        }
    }

    @Override
    public void execute(Runnable command) {
        pendingTasks.add(new Task(command));
    }

    public boolean hasPendingTasks() {
        return !pendingTasks.isEmpty();
    }

    /**
     * Runs the next task, in the current thread.
     *
     * @throws java.util.NoSuchElementException if there are no more pending tasks
     */
    public void executeNext() {
        Task task = pendingTasks.remove();
        task.runnable.run();
    }

    /**
     * Runs all pending tasks in the current thread, until the queue of pending tasks is empty.
     */
    public void executeAll() {
        while (hasPendingTasks()) {
            executeNext();
        }
    }
}


text:
package storage

import (
	"github.com/otsimo/otsimopb"
)

type Event interface {
	GamesAtRange(childID string, from int64, to int64) ([]*otsimopb.GameWithVersions, error)
	UsersAtRange(countryCodes []string, from int64, to int64, s Sender) error
	Analyze(in *otsimopb.AnalyzeRequest) (*otsimopb.DataSet, error)
	GameInfo(gameID string) (*otsimopb.GameInfoResponse, error)
}

type AppEvent interface {
	DataAtRange(int64, int64) ([]otsimopb.AppEventData, error)
	GetActiveUsersAnalytics(in *otsimopb.ActiveUsersRequest) *otsimopb.DataSet
	GetRetention(int64, string, string) (float32, error)
	InactiveUsers(activeFrom int64, activeTo int64, inactiveFrom int64, inactiveTo int64, appID string, s Sender) error
	ActiveUsers(from int64, to int64, appID string, s Sender) error
	Events() (*otsimopb.GameInfoResponse, error)
}


text:
module RubyEventStore
  module Mappers
    module Transformation
      class SymbolizeMetadataKeys
        def dump(record)
          symbolize(record)
        end

        def load(record)
          symbolize(record)
        end

        private

        def symbolize(record)
          Record.new(
            event_id: record.event_id,
            event_type: record.event_type,
            data: record.data,
            metadata: TransformKeys.symbolize(record.metadata),
            timestamp: record.timestamp,
            valid_at: record.valid_at
          )
        end
      end
    end
  end
end


text:
Your Library

Books by {{author}} Back to all books

		<input type="text" ng-model="search" placeholder="search books" class="form-control ">

		Sort By Title | Sort by Author

		Grid View | List View

			<ng-include src="'/partials/booksGridView.html'"></ng-include>

			<ng-include src="'/partials/booksListView.html'"></ng-include>


text:
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs/Observable';
import { Broadcaster } from './broadcaster';

import { UserService } from './user.service';
import { User } from '../models/user';

@Injectable()
export class LoginService {
  static user: User
  private googleAuthUrl = `${environment.apiRoot}/omniauth/google_redirect`;

  constructor(private userService: UserService, private broadcaster: Broadcaster) { }

  getGoogleOAuthUrl(currentUrl): string {
    return this.googleAuthUrl + '?return_url=' + encodeURIComponent(currentUrl);
  }

  getUser(): Promise<User> {
    if (LoginService.user) {
      return new Promise((resolve, reject) => {
        resolve(LoginService.user);
        return LoginService.user;
      });
    } else {
      return this.userService.getUser().then((user) => {
        LoginService.user = user;
        this.broadcaster.broadcast('login', LoginService.user);
        return LoginService.user;
      }).catch(this.handleError);
    }
  }

  on(key: string): Observable<User> {
    return this.broadcaster.on<User>(key);
  }

  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }
}


text:
package mblog.core.biz.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import mblog.base.lang.EnumPrivacy;
import mblog.base.upload.FileRepo;
import mblog.core.biz.PostBiz;
import mblog.core.data.Attach;
import mblog.core.data.Post;
import mblog.core.event.FeedsEvent;
import mblog.core.persist.service.AttachService;
import mblog.core.persist.service.FeedsService;
import mblog.core.persist.service.PostService;
import mtons.modules.pojos.Paging;

/**
 * @author langhsu
 *
 */
@Service
public class PostBizImpl implements PostBiz {
	@Autowired
	private PostService postService;
	@Autowired
	private AttachService attachService;
	@Autowired
	private FeedsService feedsService;
	@Autowired
	private FileRepo fileRepo;
	@Autowired
	private ApplicationContext applicationContext;

	/**
	 * 分页查询文章, 带缓存
	 * - 缓存key规则: list_分组ID排序方式_页码_每页条数
	 * @param paging
	 * @param group
	 * @param ord
	 * @return
	 */
	@Override
	@Cacheable(value = "postsCaches", key = "'list_' + #group + #ord + '_' + #paging.getPageNo() + '_' + #paging.getMaxResults()")
	public Paging paging(Paging paging, int group, String ord) {
		postService.paging(paging, group, ord, true);
		return paging;
	}

	@Override
	@Cacheable(value = "postsCaches", key = "'uhome' + #uid + '_' + #privacy.getIndex() + '_' + #paging.getPageNo()")
	public Paging pagingByAuthorId(Paging paging, long uid, EnumPrivacy privacy) {
		postService.pagingByAuthorId(paging, uid, privacy);
		return paging;
	}

	@Override
	@Cacheable(value = "postsCaches", key = "'gallery_' + #group + #ord + '_' + #paging.getPageNo() + '_' + #paging.getMaxResults()")
	@SuppressWarnings("unchecked")
	public Paging gallery(Paging paging, int group, String ord) {
		postService.paging(paging, group, ord, false);

		// 查询图片, 这里只加载文章的最后一张图片
		List<Post> results = (List<Post>) paging.getResults();
		Set<Long> imageIds = new HashSet<Long>();

		results.forEach(p -> {
			if (p.getLastImageId() > 0) {
				imageIds.add(p.getLastImageId());
			}
		});

		if (!imageIds.isEmpty()) {
			Map<Long, Attach> ats = attachService.findByIds(imageIds);

			results.forEach(p -> {
				if (p.getLastImageId() > 0) {
					p.setAlbum(ats.get(p.getLastImageId()));
				}
			});
		}
		return paging;
	}

	@Override
	@Cacheable(value = "postsCaches", key = "'view_' + #id")
	public Post getPost(long id) {
		return postService.get(id);
	}

	@Override
	@CacheEvict(value = "postsCaches", allEntries = true)
	public void post(Post post) {
		long id = postService.post(post);

		FeedsEvent event = new FeedsEvent("feedsEvent");
		event.setPostId(id);
		event.setAuthorId(post.getAuthorId());
		event.setPrivacy(post.getPrivacy());
		applicationContext.publishEvent(event);
	}

	@Override
	@CacheEvict(value = "postsCaches", allEntries = true)
	public void updateFeatured(long id, int featured) {
		postService.updateFeatured(id, featured);
	}

	@Override
	@Cacheable(value = "postsCaches", key = "'post_recents'")
	public List<Post> findRecents(int maxResults, long ignoreUserId) {
		return postService.findLatests(maxResults, ignoreUserId);
	}

	@Override
	@Cacheable(value = "postsCaches", key = "'post_hots'")
	public List<Post> findHots(int maxResults, long ignoreUserId) {
		return postService.findHots(maxResults, ignoreUserId);
	}

	@Override
	@CacheEvict(value = "postsCaches", allEntries = true)
	public void delete(long id, long authorId) {
		List<Attach> atts = attachService.findByTarget(id);
		postService.delete(id, authorId);

		// 时刻保持清洁, 物理删除图片
		if (!atts.isEmpty()) {
			atts.forEach(a -> {
				fileRepo.deleteFile(a.getPreview());
				fileRepo.deleteFile(a.getOriginal());
				fileRepo.deleteFile(a.getScreenshot());
			});
		}

		feedsService.deleteByTarget(id);
	}

	@Override
	@CacheEvict(value = "postsCaches", allEntries = true)
	public void delete(Collection<Long> ids) {
		for (Long id : ids) {
			List<Attach> atts = attachService.findByTarget(id);
			postService.delete(id);

			// 时刻保持清洁, 物理删除图片
			if (!atts.isEmpty()) {
				atts.forEach(a -> {
					fileRepo.deleteFile(a.getPreview());
					fileRepo.deleteFile(a.getOriginal());
					fileRepo.deleteFile(a.getScreenshot());
				});
			}

			feedsService.deleteByTarget(id);
		}
	}

	@Override
	@CacheEvict(value = "postsCaches", key = "'view_' + #postId")
	public void favor(long userId, long postId) {
		postService.favor(userId, postId);
	}

	@Override
	@CacheEvict(value = "postsCaches", key = "'view_' + #postId")
	public void unfavor(long userId, long postId) {
		postService.unfavor(userId, postId);
	}

	/**
	 * 更新文章:更新文章并清空缓存
	 * @param p
	 */
	@Override
	@CacheEvict(value = "postsCaches", allEntries = true)
	public void update(Post p) {
		postService.update(p);
	}

}


text:
package org.apache.reef.io;

import org.apache.reef.annotations.Unstable;

// FIXME:
// This was another more type safe
// alternative to integer partitions
@Unstable
public class PartitionSpec {
  private final Type type;
  private final int id;

  public PartitionSpec(final Type type, final int id) {
    this.type = type;
    this.id = id;
  }

  public Type getType() {
    return type;
  }

  public int getId() {
    return id;
  }

  public enum Type {
    SINGLE,
    ALL,
    NONE
  }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="Content-Language" content="en"/>

	<title>Topics: Semantics - Web Standards Sherpa</title>
	<meta name="robots" content="index,follow,archive" />

	<meta name='description' content='Web Standards Sherpa’s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.' />
	<meta name='DC.description' content='Web Standards Sherpa’s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.' />
	<meta name='keywords' content='web standards,best practices,web design,web development' />
	<meta name='DC.subject' content='web standards,best practices,web design,web development' />

	<link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" />
	<link rel="schema.DCTERMS" href="http://purl.org/dc/terms/" />
	<meta name="DC.title" content="Topics: Semantics - Web Standards Sherpa" />
	<meta name="DC.creator" content="Web Standards Sherpa" />
	<meta name="DC.publisher" content="The Web Standards Project" />
	<meta name="DC.date.created" scheme="DCTERMS.W3CDTF" content="2015-12-07T14:45:28-05:00" />
	<meta name="DC.date.modified" scheme="DCTERMS.W3CDTF" content="1453-05-14T23:00:00-05:00" />
	<meta name="DC.date.valid" scheme="DCTERMS.W3CDTF" content="2015-12-13T16:45:28-05:00" />
	<meta name="DC.type" scheme="DCTERMS.DCMIType" content="Text" />
	<meta name="DC.rights" scheme="DCTERMS.URI" content="(cc) Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License">
	<meta name="Copyright" content="(cc) Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License"/>
	<meta name="DC.format" content="text/html" />
	<meta name="DC.identifier" scheme="DCTERMS.URI" content="http://webstandardssherpa.com/archive/topics/semantics" />
	<meta name="MSSmartTagsPreventParsing" content="true"/>
	<meta name="Rating" content="General"/>

	<meta name="viewport" content="width=device-width, initial-scale=1"/>
	<link rel="home" href="../../index.html"/>
	<link rel="copyright" href="index.html#license"/>
	<link rel="shortcut icon" type="image/png" href="../../favicon.png"/>
	<link rel="author" type="text/plain" href="../../humans.txt.html"/>

		<link rel="stylesheet" type="text/css" href="../../c/main.css" media="screen"/>

	<link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Reviews (Summary)" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Reviews-Summary"/>
	<link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Reviews (Full Text)" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Reviews"/>
	<link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Discussions" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Discussions"/>

Web Standards Sherpa

Home

Reviews

Ask the Sherpas

Topics

Topics: Semantics

Everyone strives for meaning in this world of ours, so let them find it in your HTML. Using meaningful elements can improve both the accessibility of your content as well as your search rankings.

HTML for Restaurant Menus

Answered by Allison Wagner on 14 January 2014

						Oh, you mean besides linking to a PDF? I kid. Though, not really. Unfortunately, a PDF has become the “menu solution” for many restaurant sites. This presents a host of issues,…

Acronyms in Body Copy

Answered by Derek Featherstone on 19 February 2013

						Screen Reader Defaults
Providing abbreviation expansions in the title attribute is “what we do,” but it does rely on the some customization of settings for some screen…

Choosing a Structured Data Technology

Answered by Emily Lewis on 12 December 2012

						Answering this question is really about goals: your goals as a developer, your employer’s or client’s goals, and project goals. But before answering that question, let’s first talk about what&…

(Issue No. 13)
 Making the Transition to HTML5

by Emily Lewis

<time datetime="2011-08-18T15:38:01" pubdate="pubdate">18 August 2011</time>

Accessibility

Compatibility

Semantics

Interested in HTML5, but not sure where to go after changing the DOCTYPE? Emily details how a reader-submitted site, Pelizzoli World, can start using HTML5 today to add structure and semantics.

(Issue No. 6)
 A Legendary Misunderstanding

by Aaron Gustafson

<time datetime="2011-03-31T12:34:11" pubdate="pubdate">31 March 2011</time>

Accessibility

Semantics

Usability

Aaron unearths code consistency issues at American Express, and shows how we can use fieldset and legend more effectively in the markup of web forms.

Next page

Page 1 of 2

This Week

Issue No. 38

Sass for Big Sites, Part 2

by Jackie Balzer

In part 2 of our series on Sass for large sites and teams, Jackie shares how Behance maintains a living Style Guide and documents its code base.

Begin the climb

Topics

Accessibility

Business

Compatibility

Content

CSS

Design / UX

HTML

Javascript

Performance

Semantics

Usability

Workflow / Process

Follow us

Twitter

Facebook

Google+

RSS

  		<form style="display: none" id="search-form" method="post" action="../../index.html"  >

<input type="hidden" name="ACT" value="6" />
<input type="hidden" name="XID" value="dd08d68980d9cef6fb3e73d76e80b930c07e5686" />
<input type="hidden" name="RES" value="10" />
<input type="hidden" name="meta" value="vJed+IEhaFn3W7jNVVY8C6VK4KKB0doGerxtt+3TXJkJkrK5M3OFhLNfv7UrH+uJhVYy/SM2Y8CEBzxS9ZAY+5Ry234MoWdF0KwpptDKKX/rJJg1NP4Y7SntDPwMKWd0mrV/+nbWgdpLXyGAXHtWDd/W8QMHWePL8qfhqCpJzaK4pU2LxFEhOj26ZDN4P+8d8hXffYqEVMiMRDrkUYAlZAa+r08a/igafmWKpfXqcmFAHWq/qsh+zoaTz9V6wiUJl2MMAdfHTEZ76nZbWvE5NUZpcvtxRexke8gSzhsFUK46dJJ8pJfmOvPccKB8bfwmBU4cgAZ668OleVhPUZRHiYhGfX21C2DodUFydLdhuEPR2Upj1jdw5RfdVF8nWXwA5G5T4DRd4xKMtKvVvr1BpJKZ37Gid+DBZjiqIcAhYCY=" />
<input type="hidden" name="site_id" value="1" />

			Looking for something?
			<input type="search" name="keywords" id="query" value=""/>
			<button type="submit">Search</button>

	</form>

Sign up

Log in

Web Standards Sherpa’s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.

More about us

Contact us

Participate

Submit a site

Submit a question

Sign upLog in

Learn

Reviews

Ask Sherpas

Authors

Glossary

We thank our sponsors

Web Standards Sherpa is an outreach effort by the Web Standards Project (WaSP).

The content of this site is licensed under Creative Commons.


text:
namespace maps
{
    namespace multi
    {
        template <typename T>
        class PlusAggregator : public IAggregator
        {
        public:
            virtual void AggregateToHost(IDatum *datum, const void *src, size_t stride_bytes,
                                         void *dst) const
            {
                const T *psrc = (const T *)src;
                T *pdst = (T *)dst;

                unsigned int ndim = datum->GetDataDimensions();
                size_t totalsize = stride_bytes / sizeof(T);
                for (unsigned int i = 1; i < ndim; ++i)
                    totalsize *= datum->GetDataDimension(i);

                for (size_t i = 0; i < totalsize; ++i)
                    pdst[i] += psrc[i];
            }
        };

    } // namespace multi

} // namespace maps

#endif // __MAPS_MULTI_AGGREGATORS_H


text:
package cn.nsx.yaoyiyao;

/*
 * ʹÓûù±¾¶¨Î»¹¦ÄÜ:¸ù¾ÝÓû§Êµ¼ÊÐèÇ󣬷µ»ØÓû§µ±Ç°Î»ÖõĻù´¡¶¨Î»·þÎñ¡£
 * »ù±¾¶¨Î»¹¦ÄÜͬʱ»¹Ö§³Ö½áºÏ¶¨Î»½á¹ûµÄ·´µØÀí±àÂ빦ÄÜ£¬ÀëÏ߶¨Î»£¬Î»ÖÃÌáÐѹ¦Äܺ͵ØÀíΧÀ¸¹¦ÄÜ¡£
 */
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MyLocation extends Activity {

	private LinearLayout layout;
	private TextView locationText;
	//Hight_Accuracy¸ß¾«¶È¡¢Battery_SavingµÍ¹¦ºÄ¡¢Device_Sensors½öÉ豸(GPS)
	private LocationMode tempMode = LocationMode.Hight_Accuracy;
	private String tempcoor = "gcj02";

	public LocationClient mLocationClient = null;
	public MyLocationListener mMyLocationListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mylocation);
		// dialog=new MyDialog(this);
		locationText = (TextView) findViewById(R.id.mylocation);

		/* 1¡¢³õ'»¯LocationClientÀà,LocationClientÀà±ØÐëÔÚÖ÷Ïß³ÌÖÐÉùÃ÷ */
		mLocationClient = new LocationClient(this.getApplicationContext());// ÉùÃ÷LocationClientÀà
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);// 3¡¢×¢²á¼àÌýº¯Êý

		layout = (LinearLayout) findViewById(R.id.my_location_layout);
		layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "Ìáʾ£ºµã»÷´°¿ÚÍⲿ¹Ø±Õ´°¿Ú£¡",
						Toast.LENGTH_SHORT).show();
			}
		});
		InitLocation();
		mLocationClient.start();//4¡¢start£ºÆô¶¯¶¨Î»SDK¡£
	}

	/**
	 * 5¡¢ÊµÏÖBDLocationListener½Ó¿Ú£¬ÊµÏÖʵλ»Øµ÷¼àÌý
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// BDLocationÀ࣬·â×°Á˶¨Î»SDKµÄ¶¨Î»½á¹û£¬ÔÚBDLocationListenerµÄonReceive·½·¨ÖлñÈ¡¡£
			// ͨ¹ý¸ÃÀàÓû§¿ÉÒÔ»ñÈ¡error code£¬Î»ÖõÄ×ø±ê£¬¾«¶È°ë¾¶µÈÐÅÏ¢¡£
			if (location == null)
				return;
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());

			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());

			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\ndirection : ");
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				sb.append(location.getDirection());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				// ÔËÓªÉÌÐÅÏ¢
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
			}
			logMsg(sb.toString());
			Log.i("BaiduLocationApiDem", sb.toString());
		}

	}

	/**
	 * ÏÔʾÇëÇó×Ö·û´®
	 *
	 */
	public void logMsg(String str) {
		try {
			if (locationText != null)
				locationText.setText(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		finish();
		mLocationClient.stop();//stop£º¹Ø±Õ¶¨Î»SDK¡£
		return true;
	}

	/* 2¡¢ÉèÖö¨Î»²ÎÊý */
	private void InitLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(tempMode);// ÉèÖö¨Î»Ä£Ê½
		option.setCoorType(tempcoor);// ·µ»ØµÄ¶¨Î»½á¹ûÊǰٶȾÎ³¶È£¬Ä¬ÈÏÖµgcj02
		int span = 1000;
		option.setScanSpan(span);// ÉèÖ÷¢Æð¶¨Î»ÇëÇóµÄ¼ä¸ôʱ¼äΪ5000ms
		option.setIsNeedAddress(true);// ÐèÒª·´±àÂëµØÀíλÖ㬷µ»ØµÄ¶¨Î»½á¹û°üº¬µØÖ·ÐÅÏ¢
		option.setNeedDeviceDirect(true);// ·µ»ØµÄ¶¨Î»½á¹û°üº¬ÊÖ»ú»úÍ·µÄ·½Ïò
		mLocationClient.setLocOption(option);// ÉèÖòÎÊý
	}

}


text:
package de.andrew.demoZITF.ui.quote;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import de.andrew.demoZITF.R;

import de.andrew.demoZITF.myDataModels.DatabaseHandler;
import de.andrew.demoZITF.myDataModels.Place;
import de.andrew.demoZITF.ui.base.BaseActivity;
import de.andrew.demoZITF.ui.quote.dummy.DummyContent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * An activity representing a list of Places. This activity
 * has different presentations for handset and tablet-size devices. On
 * handsets, the activity presents a list of items, which when touched,
 * lead to a {@link PlaceDetailActivity} representing
 * item details. On tablets, the activity presents the list of items and
 * item details side-by-side using two vertical panes.
 */
public class PlaceListActivity extends BaseActivity {
    RecyclerView mRecyclerView;
    SwipeRefreshLayout mSwipeRefreshLayout;
    SimpleItemRecyclerViewAdapter myAdapter;

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_place_list);
//        DatabaseHandler db = new DatabaseHandler(this);
//        db.deleteAll();
        setupToolbar();

        // Show the Up button in the action bar.
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        View recyclerView = findViewById(R.id.place_list);
        assert recyclerView != null;
        setupRecyclerView((RecyclerView) recyclerView);

        if (findViewById(R.id.place_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-w900dp).
            // If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;
        }

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setRefreshing(true);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Refresh items
                refreshItems();
            }
        });

    }
    void refreshItems() {
        // Load items
        // ...

//        DownloadContentTask downloadContentTask =new DownloadContentTask();
//        downloadContentTask.execute();
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        // Load complete
        onItemsLoadComplete();
    }

    void onItemsLoadComplete() {
        // Update the adapter and notify data set changed
        // ...

        // Stop refresh animation
        mSwipeRefreshLayout.setRefreshing(false);
    }
    private void setupToolbar() {
        final ActionBar ab = getActionBarToolbar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                openDrawer();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        int id = item.getItemId();
//        if (id == android.R.id.home) {
//            // This ID represents the Home or Up button. In the case of this
//            //  details, see the Navigation pattern on Android Design:
//            //
//            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
//            //activity, the Up button is shown. Use NavUtils to allow users
//            // to navigate up one level in the application structure. For
//            // more
//            NavUtils.navigateUpFromSameTask(this);
//            return true;
//        }
//        return super.onOptionsItemSelected(item);
//    }

    private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
//        DatabaseHandler db = new DatabaseHandler(PlaceListActivity.this);
//        List<Place> places = db.getAllPlaces();
        mRecyclerView = recyclerView;
        DownloadContentTask downloadContentTask =new DownloadContentTask();
        downloadContentTask.execute();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setHasFixedSize(true);
        setUpItemTouchHelper();
        setUpAnimationDecoratorHelper();
//        ItemTouchHelper.Callback callback = new PlaceTouchHelper(myAdapter);
//        ItemTouchHelper helper = new ItemTouchHelper(callback);
//        helper.attachToRecyclerView(recyclerView);
    }

    @Override
    protected int getSelfNavDrawerItem() {
        return R.id.nav_location;
    }

    @Override
    public boolean providesActivityToolbar() {
        return true;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    private void setUpItemTouchHelper() {

        ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {

            // we want to cache these and not allocate anything repeatedly in the onChildDraw method
            Drawable background;
            Drawable xMark;
            int xMarkMargin;
            boolean initiated;

            private void init() {
                background = new ColorDrawable(Color.GREEN);
                xMark = ContextCompat.getDrawable(PlaceListActivity.this, R.drawable.ic_add_24dp);
                xMark.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                xMarkMargin = (int) PlaceListActivity.this.getResources().getDimension(R.dimen.ic_clear_margin);
                initiated = true;
            }

            // not important, we don't want drag & drop
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int position = viewHolder.getAdapterPosition();
                SimpleItemRecyclerViewAdapter testAdapter = (SimpleItemRecyclerViewAdapter) recyclerView.getAdapter();
                if (testAdapter.isUndoOn() && testAdapter.isPendingRemoval(position)) {
                    return 0;
                }
                return super.getSwipeDirs(recyclerView, viewHolder);
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
                int swipedPosition = viewHolder.getAdapterPosition();
                SimpleItemRecyclerViewAdapter adapter = (SimpleItemRecyclerViewAdapter) mRecyclerView.getAdapter();
                boolean undoOn = adapter.isUndoOn();
                if (undoOn) {
                    adapter.pendingRemoval(swipedPosition);
                } else {
                    adapter.remove(swipedPosition);
                }
            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                View itemView = viewHolder.itemView;

                // not sure why, but this method get's called for viewholder that are already swiped away
                if (viewHolder.getAdapterPosition() == -1) {
                    // not interested in those
                    return;
                }

                if (!initiated) {
                    init();
                }

                // draw Green background
                background.setBounds(itemView.getRight() + (int) dX, itemView.getTop(), itemView.getRight(), itemView.getBottom());
                background.draw(c);

                // draw x mark
                int itemHeight = itemView.getBottom() - itemView.getTop();
                int intrinsicWidth = xMark.getIntrinsicWidth();
                int intrinsicHeight = xMark.getIntrinsicWidth();

                int xMarkLeft = itemView.getRight() - xMarkMargin - intrinsicWidth;
                int xMarkRight = itemView.getRight() - xMarkMargin;
                int xMarkTop = itemView.getTop() + (itemHeight - intrinsicHeight) / 2;
                int xMarkBottom = xMarkTop + intrinsicHeight;
                xMark.setBounds(xMarkLeft, xMarkTop, xMarkRight, xMarkBottom);

                xMark.draw(c);

                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }

        };
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
    }

    /**
     * We're gonna setup another ItemDecorator that will draw the red background in the empty space while the items are animating to thier new positions
     * after an item is removed.
     */
    private void setUpAnimationDecoratorHelper() {
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {

            // we want to cache this and not allocate anything repeatedly in the onDraw method
            Drawable background;
            boolean initiated;

            private void init() {
                background = new ColorDrawable(Color.GREEN);
                initiated = true;
            }

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {

                if (!initiated) {
                    init();
                }

                // only if animation is in progress
                if (parent.getItemAnimator().isRunning()) {

                    // some items might be animating down and some items might be animating up to close the gap left by the removed item
                    // this is not exclusive, both movement can be happening at the same time
                    // to reproduce this leave just enough items so the first one and the last one would be just a little off screen
                    // then remove one from the middle

                    // find first child with translationY > 0
                    // and last one with translationY < 0
                    // we're after a rect that is not covered in recycler-view views at this point in time
                    View lastViewComingDown = null;
                    View firstViewComingUp = null;

                    // this is fixed
                    int left = 0;
                    int right = parent.getWidth();

                    // this we need to find out
                    int top = 0;
                    int bottom = 0;

                    // find relevant translating views
                    int childCount = parent.getLayoutManager().getChildCount();
                    for (int i = 0; i < childCount; i++) {
                        View child = parent.getLayoutManager().getChildAt(i);
                        if (child.getTranslationY() < 0) {
                            // view is coming down
                            lastViewComingDown = child;
                        } else if (child.getTranslationY() > 0) {
                            // view is coming up
                            if (firstViewComingUp == null) {
                                firstViewComingUp = child;
                            }
                        }
                    }

                    if (lastViewComingDown != null && firstViewComingUp != null) {
                        // views are coming down AND going up to fill the void
                        top = lastViewComingDown.getBottom() + (int) lastViewComingDown.getTranslationY();
                        bottom = firstViewComingUp.getTop() + (int) firstViewComingUp.getTranslationY();
                    } else if (lastViewComingDown != null) {
                        // views are going down to fill the void
                        top = lastViewComingDown.getBottom() + (int) lastViewComingDown.getTranslationY();
                        bottom = lastViewComingDown.getBottom();
                    } else if (firstViewComingUp != null) {
                        // views are coming up to fill the void
                        top = firstViewComingUp.getTop();
                        bottom = firstViewComingUp.getTop() + (int) firstViewComingUp.getTranslationY();
                    }

                    background.setBounds(left, top, right, bottom);
                    background.draw(c);

                }
                super.onDraw(c, parent, state);
            }

        });
    }

    /**
     * RecyclerView adapter enabling undo on a swiped away item.
     */

    public class SimpleItemRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {

        private static final int PENDING_REMOVAL_TIMEOUT = 3000; // 3sec

        List<Place> items;
        List<Place> itemsPendingRemoval;
        int lastInsertedIndex; // so we can add some more items for testing purposes
        boolean undoOn = true; // is undo on, you can turn it on from the toolbar menu

        private Handler handler = new Handler(); // hanlder for running delayed runnables
        HashMap<Place, Runnable> pendingRunnables = new HashMap<>(); // map of items to pending runnables, so we can cancel a removal if need be

        public SimpleItemRecyclerViewAdapter(List<Place> mItems) {
            List<Place> mValues = mItems;
            items = new ArrayList<>();
            itemsPendingRemoval = new ArrayList<>();
                        // this should give us a couple of screens worth
            for (int i=0; i< mValues.size(); i++) {
                items.add(mValues.get(i));
            }
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.place_list_content, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int mPosition) {
            holder.mItem = items.get(mPosition);
            holder.article_title.setText(items.get(mPosition).getPlaceName());
            holder.article_subtitle.setText(items.get(mPosition).getDescription());

            if (itemsPendingRemoval.contains(holder.mItem)) {
                // we need to show the "undo" state of the row
                holder.itemView.setBackgroundColor(Color.rgb(25,118,210));
                holder.article_title.setVisibility(View.GONE);
                holder.undoButton.setVisibility(View.VISIBLE);
                holder.undoButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // user wants to undo the removal, let's cancel the pending task
                        Runnable pendingRemovalRunnable = pendingRunnables.get(holder.mItem);
                        pendingRunnables.remove(holder.mItem);
                        if (pendingRemovalRunnable != null)
                            handler.removeCallbacks(pendingRemovalRunnable);
                        itemsPendingRemoval.remove(holder.mItem);
                        // this will rebind the row in "normal" state
                        notifyItemChanged(items.indexOf(holder.mItem));
                    }
                });

            } else {
                // we need to show the "normal" state
                holder.itemView.setBackgroundColor(Color.WHITE);
                holder.article_title.setVisibility(View.VISIBLE);
                holder.article_title.setText(holder.mItem.getPlaceName());
                holder.undoButton.setVisibility(View.GONE);
                holder.undoButton.setOnClickListener(null);
            }
            final ImageView mImg = holder.img;

            Glide.with(PlaceListActivity.this).load(items.get(mPosition).getImgURL()).asBitmap().fitCenter().into(new BitmapImageViewTarget(mImg) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(PlaceListActivity.this.getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    mImg.setImageDrawable(circularBitmapDrawable);
                }
            });

            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Snackbar.make(v, "Swipe it right to add ", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
//                    if (mTwoPane) {
//                        Bundle arguments = new Bundle();
//                        arguments.putInt(PlaceDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
//                        PlaceDetailFragment fragment = new PlaceDetailFragment();
//                        fragment.setArguments(arguments);
//                        getSupportFragmentManager().beginTransaction()
//                                .replace(R.id.place_detail_container, fragment)
//                                .commit();
//                    } else {
//                        Context context = v.getContext();
//                        Intent intent = new Intent(context, PlaceDetailActivity.class);
//                        intent.putExtra(PlaceDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
//
//                        context.startActivity(intent);
//                    }
                }
            });
        }

        /**
         * Utility method to add some rows for testing purposes. You can add rows from the toolbar menu.
         */
//        public void addItems(int howMany) {
//            if (howMany > 0) {
//                for (int i = lastInsertedIndex + 1; i <= lastInsertedIndex + howMany; i++) {
//                    items.add("Item " + i);
//                    notifyItemInserted(items.size() - 1);
//                }
//                lastInsertedIndex = lastInsertedIndex + howMany;
//            }
//        }

        public void setUndoOn(boolean undoOn) {
            this.undoOn = undoOn;
        }

        public boolean isUndoOn() {
            return undoOn;
        }

        public void pendingRemoval(int position) {
            final Place item = items.get(position);
            if (!itemsPendingRemoval.contains(item)) {
                itemsPendingRemoval.add(item);
                // this will redraw row in "undo" state
                notifyItemChanged(position);
                // let's create, store and post a runnable to remove the item
                Runnable pendingRemovalRunnable = new Runnable() {
                    @Override
                    public void run() {
                        remove(items.indexOf(item));
                    }
                };
                handler.postDelayed(pendingRemovalRunnable, PENDING_REMOVAL_TIMEOUT);
                pendingRunnables.put(item, pendingRemovalRunnable);
            }
        }

        public void remove(int position) {
            Place item = items.get(position);
            DatabaseHandler db = new DatabaseHandler(PlaceListActivity.this);
            if(db.addPlace(item)==true) {
                if (itemsPendingRemoval.contains(item)) {
                    itemsPendingRemoval.remove(item);
                }
                if (items.contains(item)) {
                    items.remove(position);
                    notifyItemRemoved(position);
                }
            }else {
                Toast.makeText(PlaceListActivity.this,"Record already in the database", Toast.LENGTH_SHORT).show();
            }
        }

        public boolean isPendingRemoval(int position) {
            Place item = items.get(position);
            return itemsPendingRemoval.contains(item);
        }

        @Override
        public int getItemCount() {
            return items.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public final View mView;
            public final TextView article_title;
            public final TextView article_subtitle;
            public final ImageView img;
            public final Button undoButton;
            public Place mItem;
//            final Place item = (Place) getItem(position);
//            ((TextView) convertView.findViewById(R.id.article_title)).setText(item.getPlaceName());
//            ((TextView) convertView.findViewById(R.id.article_subtitle)).setText(item.getDescription());
//            final ImageView img = (ImageView) convertView.findViewById(R.id.thumbnail);

            public ViewHolder(View view) {
                super(view);
                mView = view;
                article_title = (TextView) view.findViewById(R.id.article_title);
                article_subtitle = (TextView) view.findViewById(R.id.article_subtitle);
                img = (ImageView) view.findViewById(R.id.thumbnail);
                undoButton= (Button) view.findViewById(R.id.undo_button);
            }

            @Override
            public String toString() {
                return super.toString() + " '" + article_subtitle.getText() + "'";
            }
        }
    }
    /**
     * ViewHolder capable of presenting two states: "normal" and "undo" state.
     */

    private ArrayList<Place>getDataFromJson(String locationsJsonStr)
            throws JSONException {
        Log.e(LOG_TAG, "SUccessfully called Get data from JSON");
        // These are the names of the JSON objects that need to be extracted.
        final String LOC_LIST = "Data";
        final String LOC_ID = "ID";
        final String LOC_CONTENT = "post_content";
        final String LOC_ALTITUDE = "altitude";
        final String LOC_LATITUDE = "latitude";
        final String LOC_LONGITUDE = "longitude";
        final String LOC_CURRENCY = "currency";
        final String LOC_LANGUAGES = "languages";
        final String LOC_VISA_REQUIREMENTS = "visa_requirement";
        final String LOC_NIGHTLIFE = "location_nightlife";
        final String LOC_SPORTS = "location_sports_and_nature";
        final String LOC_TYPE = "place_type";
        final String LOC_TITLE = "post_title";
        final String LOC_IMG = "guid";

        JSONObject jsonResult = new JSONObject(locationsJsonStr);
        JSONArray locationArray = jsonResult.getJSONArray("data");
        if (locationArray!=null){
            Log.e(LOG_TAG, locationArray.getString(1).toString());
        }else {
            Log.e(LOG_TAG, "Location Array is empty");
        }

        ArrayList<Place> mResults = new ArrayList<Place>();
        Place[] resultStrs = new Place[locationArray.length()];

//            Log.e(LOG_TAG, "The length of Result Array is: "+locationArray.length());
        for(int i = 0; i < locationArray.length(); i++) {
            // Get the JSON object representing the Location
            JSONObject singleLocation = locationArray.getJSONObject(i);
            Place place = new Place();
            place.setLanguages(singleLocation.getString(LOC_LANGUAGES));
            place.setVisaequirements(singleLocation.getString(LOC_VISA_REQUIREMENTS));
            place.setPlaceType(singleLocation.getString(LOC_TYPE));
            place.setNightlife(singleLocation.getString(LOC_NIGHTLIFE));
            place.setSportsAndNature(singleLocation.getString(LOC_SPORTS));
            place.setLatitude(singleLocation.getInt(LOC_LATITUDE));
            place.setLongitude(singleLocation.getInt(LOC_LONGITUDE));
            place.setCurrencyUsed(LOC_CURRENCY);
            place.setId(singleLocation.getInt(LOC_ID));
            place.setPlaceName(singleLocation.getString(LOC_TITLE));
            place.setDescription(singleLocation.getString(LOC_CONTENT));
            place.setAltitude(singleLocation.getInt(LOC_ALTITUDE));
            String locationUrl = singleLocation.getString(LOC_IMG).replaceAll("localhost", "10.0.2.2");
            Log.e(LOG_TAG,"Location Url is "+locationUrl);
            place.setImgURL(locationUrl.replaceAll("\\\\",""));
            mResults.add(place);
            resultStrs[i] = place;

            Log.e(LOG_TAG, "Title " + 1 + " = " + place.getPlaceName());

        }

        for (Place s : resultStrs) {
            Log.e(LOG_TAG, "Place entry: " + s.getPlaceName().toString());
        }
        Log.e(LOG_TAG, "Place entry 1 : " + mResults.get(1).getPlaceName().toString());
        return mResults;
    }
    String LOG_TAG = "ASYNCTASK";

    private class DownloadContentTask extends AsyncTask<Void, Void, ArrayList<Place>> {

        protected ArrayList<Place> doInBackground(Void... voidsv) {

            //android.os.Debug.waitForDebugger();
            // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String mLocationsJsonStr = null;
            Log.e(LOG_TAG, "Starting background thread");
            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are avaiable at LOC's forecast API page, at
                // http://openweathermap.org/API#forecast
                String baseUrl = "http://10.0.2.2/mydemo/api.php";
                URL url = new URL(baseUrl);

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                mLocationsJsonStr = buffer.toString();
                Log.e(LOG_TAG, mLocationsJsonStr);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                // If the code didn't successfully get the data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }
            try {
                Log.e(LOG_TAG, "Calling the getData fromJSON method");
                return getDataFromJson(mLocationsJsonStr);
            }catch (JSONException e){
                e.printStackTrace();
            }
            return null;
        }

        protected void onProgressUpdate(Integer... progress) {
        }

        protected void onPostExecute(ArrayList<Place> result) {
            myAdapter = new SimpleItemRecyclerViewAdapter(result);
            mRecyclerView.setAdapter(myAdapter);
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
            for(Place place: result) {
                String thisPlace = place.getPlaceName();
            }

            Log.e(LOG_TAG, " Finished Executing ");

        }
    }

}


text:
<readable><title>3712742641_641282803e</title><content>
A black and white dog is swimming in a lake .
A black and white dog is swimming in a large green lake .
A dog swimming in a pond .
A dog treads through dark green water .
The black and white dog is swimming in the river .
</content></readable>


text:
package org.docksidestage.mysql.dbflute.exentity;

import java.time.LocalDateTime;

import org.docksidestage.mysql.dbflute.bsentity.BsSummaryWithdrawal;

/**
 * The entity of summary_withdrawal.
 * <p>
 * You can implement your original methods here.
 * This class remains when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 * @author jflute
 */
public class SummaryWithdrawal extends BsSummaryWithdrawal {

    /** Serial version UID. (Default) */
    private static final long serialVersionUID = 1L;

    // ===================================================================================
    //                                                             for test: Non-Specified
    //                                                             =======================
    public String xznocheckGetMemberStatusCode() {
        return _memberStatusCode;
    }

    public LocalDateTime xznocheckGetWithdrawalDatetime() {
        return _withdrawalDatetime;
    }
}


text:
use error::*;
use response::Response;

use rustc_serialize::Decoder;
use rustc_serialize::Decodable;

use std::fmt;

/// Documentation References:
/// https://developer.github.com/v3/activity/

/// All Activity::Events have the same response format.
/// The following structs represent this info found as a json response.

/// `Repository` contains all info regarding a git repository.
#[derive(Debug, RustcDecodable)]
pub struct Repository {
    pub id: u64,
    pub name: String,
    pub url: String,
}

/// `Actor` contains all info on the user generating the event.
#[derive(Debug, RustcDecodable)]
pub struct Actor {
    pub id: u64,
    pub login: String,
    pub gravatar_id: String,
    pub avatar_url: String,
    pub url: String,
    pub html_url: Option<String>,
    pub followers_url: Option<String>,
    pub following_url: Option<String>,
    pub gists_url: Option<String>,
    pub starred_url: Option<String>,
    pub subscriptions_url: Option<String>,
    pub organizations_url: Option<String>,
    pub repos_url: Option<String>,
    pub events_url: Option<String>,
    pub received_events_url: Option<String>,
    pub site_admin: Option<bool>,
}

/// `Organisation` contains all info on the organisation related to the event.
#[derive(Debug, RustcDecodable)]
pub struct Organisation {
    pub id: u64,
    pub login: String,
    pub gravatar_id: String,
    pub avatar_url: String,
    pub url: String,
}

/// `EventResponse` represents the response for almost
/// all event requests found in `activity::events` with issues as an exception.
#[derive(Debug, RustcDecodable)]
pub struct EventResponse {
    pub public: bool,
    pub repo: Repository,
    pub actor: Actor,
    pub org: Option<Organisation>,
    // todo: replace with proper time
    pub created_at: String,
    pub id: String,
}

/// `IssueEventType` is an enumuration of
/// all the different types of Issue Events.
#[derive(Debug)]
pub enum IssueEventType {
    /// The issue was closed by the `Actor`.
    Closed,
    /// The issue was reopened by the `Actor`.
    Reopened,
    /// The `Actor` subscribed to receive notifications for an issue.
    Subscribed,
    /// The issue was merged by the `Actor`.
    Merged,
    /// The issue was referenced from a commit message.
    Referenced,
    /// The `Actor` was @mentioned in an issue body.
    Mentioned,
    /// The issue was assigned to the `Actor`.
    Assigned,
    /// The issue was unassigned to the `Actor`.
    Unassigned,
    /// A label was added to the issue.
    Labeled,
    /// A label was removed from the issue.
    Unlabeled,
    /// The issue was added to a milestone.
    Milestoned,
    /// The issue was removed from a milestone.
    Demilestoned,
    /// The issue title was changed.
    Renamed,
    /// The issue was locked by the `Actor`.
    Locked,
    /// The issue was unlocked by the `Actor`.
    Unlocked,
    /// The pull request's branch was deleted.
    HeadRefDeleted,
    /// The pull request's branch was restored.
    HeadRefRestored,
    /// `Unknown(String)` is used as a last resort when an event is unknown.
    /// This should never happen, please report/resolve the issue when it does happen.
    Unknown(String),
}

/// Allowing `IssueEventType` to be printed via `{}`.
impl fmt::Display for IssueEventType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let msg: &str = match *self {
            IssueEventType::Closed => "closed",
            IssueEventType::Reopened => "reopened",
            IssueEventType::Subscribed => "subscribed",
            IssueEventType::Merged => "merged",
            IssueEventType::Referenced => "referenced",
            IssueEventType::Mentioned => "mentioned",
            IssueEventType::Assigned => "assigned",
            IssueEventType::Unassigned => "unassigned",
            IssueEventType::Labeled => "labeled",
            IssueEventType::Unlabeled => "unlabeled",
            IssueEventType::Milestoned => "milestoned",
            IssueEventType::Demilestoned => "demilestoned",
            IssueEventType::Renamed => "renamed",
            IssueEventType::Locked => "locked",
            IssueEventType::Unlocked => "unlocked",
            IssueEventType::HeadRefDeleted => "head reference deleted",
            IssueEventType::HeadRefRestored => "head reference restored",
            IssueEventType::Unknown(ref s) => &s,
        };

        write!(f, "{}", msg)
    }
}

/// Allowing `IssueEventType` to be decoded from json values.
/// Linked to the `event` key to the `IssueEventType` enumeration.
impl Decodable for IssueEventType {
    fn decode<D: Decoder>(d: &mut D) -> Result<IssueEventType, D::Error> {
        match d.read_str() {
            Ok(code) => Ok(match &*code {
                "closed" => IssueEventType::Closed,
                "reopened" => IssueEventType::Reopened,
                "subscribed" => IssueEventType::Subscribed,
                "merged" => IssueEventType::Merged,
                "referenced" => IssueEventType::Referenced,
                "mentioned" => IssueEventType::Mentioned,
                "assigned" => IssueEventType::Assigned,
                "unassigned" => IssueEventType::Unassigned,
                "labeled" => IssueEventType::Labeled,
                "unlabeled" => IssueEventType::Unlabeled,
                "milestoned" => IssueEventType::Milestoned,
                "demilestoned" => IssueEventType::Demilestoned,
                "renamed" => IssueEventType::Renamed,
                "locked" => IssueEventType::Locked,
                "unlocked" => IssueEventType::Unlocked,
                "head_ref_deleted" => IssueEventType::HeadRefDeleted,
                "head_ref_restored" => IssueEventType::HeadRefRestored,
                unknown => IssueEventType::Unknown(unknown.to_string()),
            }),
            Err(err) => Err(err),
        }
    }
}

/// `EventResponse` represents the response for
/// all issue event requests found in `activity::events`.
#[derive(Debug, RustcDecodable)]
pub struct IssueEventResponse {
    pub public: bool,
    pub repo: Repository,
    pub actor: Actor,
    pub org: Option<Organisation>,
    pub event: IssueEventType,
    pub created_at: String,
    pub commit_id: String,
    pub id: String,
}

/// `EventReturnType` is the return type for most event-requests.
pub type EventReturnType = Result<(Vec<EventResponse>, Response), ClientError>;
/// `EventReturnType` is the return type for issue-event-requests.
pub type IssueEventReturnType = Result<(Vec<IssueEventResponse>, Response), ClientError>;

pub mod events;


text:
static NSDateFormatter *dateFormatter;

@interface MGCDateRange ()

@property (nonatomic, readonly) NSDateFormatter *dateFormatter;  // for debugging only

@end

@implementation MGCDateRange

- (void)checkIfValid
{
	NSAssert([self.start compare:self.end] != NSOrderedDescending, @"End date earlier than start date in DateRange object!");
}

+ (instancetype)dateRangeWithStart:(NSDate*)start end:(NSDate*)end
{
	return [[self alloc] initWithStart:start end:end];
}

- (instancetype)initWithStart:(NSDate*)start end:(NSDate*)end
{
	if (self = [super init]) {
		_start = [start copy];
		_end = [end copy];
	}

	[self checkIfValid];

	return self;
}

// for debugging
- (NSDateFormatter*)dateFormatter
{
	if (!dateFormatter) {
		dateFormatter = [NSDateFormatter new];
		dateFormatter.dateStyle = NSDateFormatterMediumStyle;
		dateFormatter.timeStyle = NSDateFormatterMediumStyle;
	}
	return dateFormatter;
}

- (NSDateComponents*)components:(NSCalendarUnit)unitFlags forCalendar:(NSCalendar*)calendar
{
	[self checkIfValid];

	return [calendar components:unitFlags fromDate:self.start toDate:self.end options:0];
}

- (BOOL)containsDate:(NSDate*)date
{
	[self checkIfValid];

	return ([date compare:self.start] != NSOrderedAscending && [date compare:self.end] == NSOrderedAscending);
}

- (void)intersectDateRange:(MGCDateRange*)range
{
	[self checkIfValid];

	// range.end <= start || end <= range.start
	if ([range.end compare:self.start] != NSOrderedDescending || [self.end compare:range.start] != NSOrderedDescending)
		return;

	if ([self.start compare:range.start] == NSOrderedAscending) {
		self.start = range.start;
	}
	if ([range.end compare:self.end] == NSOrderedAscending) {
		self.end = range.end;
	}
}

- (BOOL)intersectsDateRange:(MGCDateRange*)range
{
	if ([range.end compare:self.start] != NSOrderedDescending || [self.end compare:range.start] != NSOrderedDescending)
		return NO;
	return YES;
}

- (BOOL)includesDateRange:(MGCDateRange*)range
{
	if ([range.start compare:self.start] == NSOrderedAscending || [self.end compare:range.end] == NSOrderedAscending)
		return NO;
	return YES;
}

- (void)unionDateRange:(MGCDateRange*)range
{
	[self checkIfValid];
	[range checkIfValid];

	self.start = [self.start earlierDate:range.start];
	self.end = [self.end laterDate:range.end];
}

- (void)enumerateDaysWithCalendar:(NSCalendar*)calendar usingBlock:(void (^)(NSDate *day, BOOL *stop))block
{
	NSDateComponents *comp = [NSDateComponents new];
	comp.day = 1;

	NSDate *date = self.start;
	BOOL stop = NO;

	while (!stop && [date compare:self.end] == NSOrderedAscending) {
		block(date, &stop);
		date = [calendar dateByAddingComponents:comp toDate:self.start options:0];
		comp.day++;
	}
}

- (BOOL)isEqualToDateRange:(MGCDateRange*)range
{
	return range && [range.start isEqualToDate:self.start] && [range.end isEqualToDate:self.end];
}

#pragma mark - NSObject

- (id)copyWithZone:(NSZone*)zone
{
    return [MGCDateRange dateRangeWithStart:self.start end:self.end];
}

- (BOOL)isEqual:(id)object
{
	if (self == object)
		return YES;

	if (![object isKindOfClass:[MGCDateRange class]])
		return NO;

	return [self isEqualToDateRange:(MGCDateRange*)object];
}

- (NSUInteger)hash
{
	return NSUINTROTATE([self.start hash], NSUINT_BIT / 2) ^ [self.end hash];
}

- (NSString*)description
{
	return [NSString stringWithFormat:@"[%@ - %@[", [self.dateFormatter stringFromDate:self.start], [self.dateFormatter stringFromDate:self.end]];
}

@end


text:
ALTER TABLE `addons` DROP COLUMN `app_domain`;
ALTER TABLE `addons` DROP COLUMN `is_packaged`;
ALTER TABLE `addons` DROP COLUMN `enable_new_regions`;
ALTER TABLE `addons` DROP COLUMN `manifest_url`;
ALTER TABLE `addons` DROP COLUMN `premium_type`;
ALTER TABLE `addons` DROP COLUMN `make_public`;
ALTER TABLE `addons` DROP COLUMN `vip_app`;

-- Make sure the following associated indexes have been dropped:
-- addons_609c04a9 (app_domain)
-- addons_is_packaged (is_packaged)
-- addons_enable_new_regions (enable_new_regions)
-- premium_type_idx (premium_type)


text:
require 'yaml'
module I18n::Tasks
  module Data
    module Adapter
      module YamlAdapter
        EMOJI_REGEX = /\\u[\da-f]{8}/i.freeze

        class << self
          # @return [Hash] locale tree
          def parse(str, options)
            if YAML.method(:load).arity.abs == 2
              YAML.safe_load(str, **(options || {}), permitted_classes: [Symbol], aliases: true)
            else
              # older jruby and rbx 2.2.7 do not accept options
              YAML.load(str)
            end
          end

          # @return [String]
          def dump(tree, options)
            restore_emojis(tree.to_yaml(options || {}))
          end

          # @return [String]
          def restore_emojis(yaml)
            yaml.gsub(EMOJI_REGEX) { |m| [m[-8..].to_i(16)].pack('U') }
          end
        end
      end
    end
  end
end


text:
INI_DIR="/usr/local/etc/php/conf.d"

DNH_INI_FILE="$INI_DIR/dnh-custom.ini"

rm -f $DNH_INI_FILE

echo "upload_max_filesize=$PHP_UPLOAD_MAX_FILESIZE" >> $DNH_INI_FILE
echo "post_max_size=$PHP_POST_MAX_FILESIZE" >> $DNH_INI_FILE
echo "memory_limit=$PHP_MEMORY_LIMIT" >> $DNH_INI_FILE
echo "max_execution_time=$PHP_MAX_EXECUTION_TIME" >> $DNH_INI_FILE
echo "session.cookie_secure=$PHP_SESSION_COOKIE_SECURE" >> $DNH_INI_FILE

OPCACHE_INI_FILE="$INI_DIR/opcache-custom.ini"

rm -f $OPCACHE_INI_FILE

if [ "$PHP_OPCACHE_ENABLE" == "1" ]; then
  echo "zend_extension=opcache.so" >> $OPCACHE_INI_FILE
  echo "opcache.enable=1" >> $OPCACHE_INI_FILE
  echo "opcache.memory_consumption=$PHP_OPCACHE_MEMORY_CONSUMPTION" >> $OPCACHE_INI_FILE
  echo "opcache.interned_strings_buffer=$PHP_OPCACHE_INTERNED_STRINGS_BUFFER" >> $OPCACHE_INI_FILE
  echo "opcache.max_accelerated_files=$PHP_OPCACHE_ACCELERATED_FILES" >> $OPCACHE_INI_FILE
  echo "opcache.revalidate_freq=$PHP_OPCACHE_REVALIDATE_FREQ" >> $OPCACHE_INI_FILE
  echo "opcache.fast_shutdown=$PHP_OPCACHE_FAST_SHUTDOWN" >> $OPCACHE_INI_FILE
fi

APC_INI_FILE="$INI_DIR/apcu.ini"

rm -f $APC_INI_FILE

if [ $PHP_APCU_ENABLE == '1' ]; then
  echo 'extension=apcu.so' > $APC_INI_FILE
fi


text:
package org.elasticsearch.action.index;

import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.junit.Test;

import static org.hamcrest.Matchers.is;

public class TransportIndexActionIT extends ESSingleNodeTestCase {

    /**
     * Validates that the autoGeneratedId index request attribute is correctly passed to the
     * {@link org.elasticsearch.index.engine.Engine.Create} class.
     */
    @Test
    public void testPrepareIndexOperationOnPrimaryCreateWithoutAutoGeneratedId() throws Exception {
        createIndex("test");
        IndicesService indicesService = getInstanceFromNode(IndicesService.class);
        IndexService indexService = indicesService.indexService("test");
        IndexShard indexShard = indexService.shard(0);

        TestIndexRequest indexRequest = new TestIndexRequest("test", "type", "1");
        indexRequest.timestamp("0");
        indexRequest.source("{}");
        indexRequest.opType(IndexRequest.OpType.CREATE);
        indexRequest.setCanHaveDuplicates();
        Engine.Create create = (Engine.Create) TransportIndexAction.prepareIndexOperationOnPrimary(null,
            indexRequest, indexShard);

        assertThat(create.canHaveDuplicates(), is(true));
        assertThat(create.autoGeneratedId(), is(false));
    }

    static class TestIndexRequest extends IndexRequest {

        boolean canHaveDuplicates = false;

        public TestIndexRequest(String index, String type, String id) {
            super(index, type, id);
        }

        public void setCanHaveDuplicates() {
            canHaveDuplicates = true;
        }

        @Override
        public boolean canHaveDuplicates() {
            return canHaveDuplicates;
        }
    }
}


text:
IFaceFrameSource::put\_FaceFrameFeatures Method
===============================================

Sets the flags that indicate which face frame features data are present in this face frame.

Syntax
======

<colgroup>
<col width="100%" />
</colgroup>

C++

public:
HRESULT put_FaceFrameFeatures(
         const DWORD faceFrameFeatures
)

#### Parameters

*faceFrameFeatures*
Type: DWORD
[in] The flags that indicate which face frame features data are present in this face frame.

#### Return value

Type: HRESULT
Returns S\_OK if successful; otherwise, returns a failure code.

Requirements
============

**Header:** kinect.face.h
**Library:** Kinect20.face.lib