text:
package com.hazelcast.durableexecutor;

import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.properties.ClusterProperty;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.io.Serializable;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class DurableLongRunningTaskTest extends HazelcastTestSupport {

    private static final int CALL_TIMEOUT = 3000;

    private HazelcastInstance hz;

    @Before
    public void setup() {
        Config config = smallInstanceConfig()
                .setProperty(ClusterProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + CALL_TIMEOUT);
        hz = createHazelcastInstance(config);
    }

    @Test
    public void test() {
        final String response = "foobar";
        SleepingCallable task = new SleepingCallable(response, 6 * CALL_TIMEOUT);
        final Future<String> f = hz.getDurableExecutorService("e").submit(task);
        assertTrueEventually(() -> {
            assertTrue(f.isDone());
            assertEquals(response, f.get());
        });
    }

    public static class SleepingCallable implements Callable<String>, Serializable, HazelcastInstanceAware {

        private final String response;
        private final int delayMs;
        private ILogger logger;

        SleepingCallable(String response, int delayMs) {
            this.response = response;
            this.delayMs = delayMs;
        }

        @Override
        public String call() throws Exception {
            logger.info("SleepingCallable task started");
            Thread.sleep(delayMs);
            return response;
        }

        @Override
        public void setHazelcastInstance(HazelcastInstance instance) {
            logger = instance.getLoggingService().getLogger("DurableLongRunningTaskTest");
        }
    }
}


text:
package org.apache.spark

import java.lang.Long

import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.executor.InputMetrics

import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.util.TaskMetricsMap
import org.apache.carbondata.hadoop.CarbonMultiBlockSplit
import org.apache.carbondata.spark.InitInputMetrics

/**
 * It gives statistics of number of bytes and record read
 */
class CarbonInputMetrics extends InitInputMetrics{
  @transient val LOGGER = LogServiceFactory.getLogService(this.getClass.getName)
    var inputMetrics: InputMetrics = _
    // bytes read before compute by other map rdds in lineage
    var existingBytesRead: Long = _
    var carbonMultiBlockSplit: CarbonMultiBlockSplit = _

  def initBytesReadCallback(context: TaskContext,
      carbonMultiBlockSplit: CarbonMultiBlockSplit) {
    inputMetrics = context.taskMetrics().inputMetrics
    existingBytesRead = inputMetrics.bytesRead
    this.carbonMultiBlockSplit = carbonMultiBlockSplit;
  }

  def incrementRecordRead(recordRead: Long) {
    val value : scala.Long = recordRead
    inputMetrics.incRecordsRead(value)
    if (inputMetrics.recordsRead % SparkHadoopUtil.UPDATE_INPUT_METRICS_INTERVAL_RECORDS == 0) {
      updateBytesRead()
    }
  }

  def updateBytesRead(): Unit = {
    inputMetrics
      .setBytesRead(existingBytesRead
                    + TaskMetricsMap.getInstance().getReadBytesSum(Thread.currentThread().getId))
  }

  def updateAndClose() {
    // if metrics supported file system ex: hdfs
    if (!TaskMetricsMap.getInstance().isCallbackEmpty(Thread.currentThread().getId)) {
      updateBytesRead()
     // after update clear parent thread entry from map.
      TaskMetricsMap.getInstance().removeEntry(Thread.currentThread().getId)
    } else if (carbonMultiBlockSplit.isInstanceOf[CarbonMultiBlockSplit]) {
      // If we can't get the bytes read from the FS stats, fall back to the split size,
      // which may be inaccurate.
      try {
        inputMetrics.incBytesRead(carbonMultiBlockSplit.getLength)
      } catch {
        case e: java.io.IOException =>
          LOGGER.warn("Unable to get input size to set InputMetrics for task:" + e.getMessage)
      }
    }
  }

  override def updateByValue(value: Object): Unit = {

  }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends "layout.html" %}

{% block page_title %}
  Declaration
{% endblock %}

{% block content %}

  {% include "../includes/phase_banner_beta.html" %}

          Your application has been sent

        Save a copy

        You can save a copy of your completed application

      <form action="what-happens-next" method="#" class="form">

          <fieldset class="">
            <legend>
            </legend>

             <input id="radio-inline-1a" type="radio" name="radio-inline-group" value="download">
              Download (not recommended on public computers)

              <input id="radio-inline-2a" type="radio" name="radio-inline-group" value="email">
              Email

               <input id="radio-inline-3a" type="radio" name="radio-inline-group" value="print">
               Print

                <input id="radio-inline-4a" type="radio" name="radio-inline-group" value="No">
                I do not want a copy

          </fieldset>

             Download a copy of your ESA application

             The download is in a PDF format. To read it you'll need Adobe Reader 4.0™ or above installed. You can download Adobe Reader if you need to.

               Email
               <input type="text" class="form-control" id="email">

             Print a copy of your ESA application

             You will not get another chance to save a copy of your application.

          <input type="submit" class="button" value="Complete application">

      </form>

{% endblock %}

{% block body_end %}
  {% include "includes/scripts.html" %}

{% endblock %}


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async, inject } from '@angular/core/testing';
import { UnauthGuardService } from './unauth-guard.service';

describe('UnauthGuardService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [UnauthGuardService]
    });
  });

  it('should ...', inject([UnauthGuardService], (service: UnauthGuardService) => {
    expect(service).toBeTruthy();
  }));
});


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Grevillea 16(no. 78): 28 (1887)

#### Original name
Polysaccum microcarpum Cooke & Massee, 1887

### Remarks
null


text:
import * as $ from 'jquery';
import addFlashMessage from './addFlashMessage';

$(() => {
  const flashUl = document.querySelector('.teams__flashMessages') as HTMLUListElement;
  const resendInviteLinks = document.querySelectorAll('.teams__resendInviteLink');

  if (!!flashUl && !!resendInviteLinks) {
    resendInviteLinks.forEach(item => {
      item.addEventListener('mousedown', (event) => {
        event.stopImmediatePropagation();
        const target = event.target as HTMLSelectElement;
        if (!target.matches('.teams__resendInviteLink')) return;

        const td = target?.parentElement?.parentElement?.parentElement?.parentElement as HTMLTableDataCellElement;
        td.classList.add('loading');

        const url = target.getAttribute('href') || '';
        const closeText = flashUl.getAttribute('data-close') || 'Close';

        fetch(url)
          .then(response => response.json())
          .then(data => {
            if (data !== 'ok') {
              addFlashMessage(flashUl, data, 'error', closeText);
              td.classList.remove('loading');
              return;
            }

            const resentInviteText = flashUl.getAttribute('data-resendInvite') || '';
            const email = target.getAttribute('data-email') || '';
            const message = resentInviteText.replace('<email>', email);
            addFlashMessage(flashUl, message, 'info', closeText);
            td.classList.remove('loading');
          })
          .catch(error => {
            addFlashMessage(flashUl, error.message, 'error', closeText);
            td.classList.remove('loading');
          });
      });
    });
  }
});


text:
require 'spec_helper'

describe 'nsclient', type: :class do
  let(:facts) do
    {
      osfamily: 'Windows'
    }
  end
  let(:params) do
    {
      package_source_location: 'https://github.com/mickem/nscp/releases/download/0.5.1.28',
      package_name: 'NSCP-0.5.1.28-x64.msi',
      download_destination: 'c:/temp'
    }
  end

  context 'using params defaults' do
    it { is_expected.to contain_class('nsclient') }
    it { is_expected.to contain_class('nsclient::install').that_comes_before('Class[nsclient::service]') }
    it { is_expected.to contain_class('nsclient::service') }
    it { is_expected.to contain_class('nsclient::params') }
    it do
      is_expected.to contain_download_file('NSCP-Installer').with(
        'url'                   => 'https://github.com/mickem/nscp/releases/download/0.5.1.28/NSCP-0.5.1.28-x64.msi',
        'destination_directory' => 'c:/temp'
      )
    end
    it do
      is_expected.to contain_package('NSCP-0.5.1.28-x64.msi').with(
        'ensure'   => 'installed',
        'provider' => 'windows',
        'source'   => 'c:/temp/NSCP-0.5.1.28-x64.msi',
        'require'  => 'Download_file[NSCP-Installer]'
      )
    end
    it { is_expected.to contain_service('nscp').with_ensure('running') }
    #
  end

  context 'installing a custom version' do
    let(:params) do
      {
        package_source: 'NSCP-Custom-build.msi',
        package_name: 'NSClient++ (x64)',
        package_source_location: 'http://myproxy.com:8080'
      }
    end

    it do
      is_expected.to contain_package('NSClient++ (x64)').with(
        'ensure'   => 'installed',
        'provider' => 'windows',
        'source'   => 'c:/temp/NSCP-Custom-build.msi',
        'require'  => 'Download_file[NSCP-Installer]'
      )
    end
  end

  context 'when trying to install on Ubuntu' do
    let(:facts) { { osfamily: 'Ubuntu' } }

    it do
      expect do
        is_expected.to contain_class('nsclient')
      end.to raise_error(Puppet::Error, %r{This module only works on Windows based systems.})
    end
  end

  context 'with service_state set to stopped' do
    let(:params) { { 'service_state' => 'stopped' } }

    it { is_expected.to contain_service('nscp').with_ensure('stopped') }
  end

  context 'with service_enable set to false' do
    let(:params) { { 'service_enable' => 'false' } }

    it { is_expected.to contain_service('nscp').with_enable('false') }
  end

  context 'with service_enable set to true' do
    let(:params) { { 'service_enable' => 'true' } }

    it { is_expected.to contain_service('nscp').with_enable('true') }
  end

  context 'when single value array of allowed hosts' do
    let(:params) { { 'allowed_hosts' => ['172.16.0.3'], 'service_state' => 'running', 'service_enable' => 'true' } }

    it { is_expected.to contain_file('C:\Program Files\NSClient++\nsclient.ini').with_content(%r{allowed hosts = 172\.16\.0\.3}) }
  end

  context 'when passing an array of allowed hosts' do
    let(:params) { { 'allowed_hosts' => ['10.21.0.0/22', '10.21.4.0/22'], 'service_state' => 'running', 'service_enable' => 'true' } }

    # it { should contain_file('C:\Program Files\NSClient++\nsclient.ini').with_content(/allowed hosts = 10\.21\.0\.0\/22,10\.21\.4\.0\/22/) }
    it { is_expected.to contain_file('C:\Program Files\NSClient++\nsclient.ini').with_content(%r{allowed hosts = 10.21.0.0/22,10.21.4.0/22}) }
  end

  context 'when passing password variable' do
    let(:params) { { 'password' => 'debian4ever', 'service_state' => 'running', 'service_enable' => 'true' } }

    it { is_expected.to contain_file('C:\Program Files\NSClient++\nsclient.ini').with_content(%r{password = debian4ever}) }
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package framework;

import com.jogamp.newt.Display;
import com.jogamp.newt.NewtFactory;
import com.jogamp.newt.Screen;
import com.jogamp.newt.opengl.GLWindow;
import static com.jogamp.opengl.GL2ES3.GL_COLOR;
import com.jogamp.opengl.GL4;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.util.Animator;

/**
 *
 * @author GBarbieri
 */
public class CheckAmdExtenstion implements GLEventListener {

    private final int screenIdx = 0;
    protected GLWindow glWindow;
    protected Animator animator;

    public static void main(String[] args) {
        new CheckAmdExtenstion();
    }

    public CheckAmdExtenstion() {
        Display display = NewtFactory.createDisplay(null);
        Screen screen = NewtFactory.createScreen(display, screenIdx);
        GLProfile glProfile = GLProfile.get(GLProfile.GL4);
        GLCapabilities glCapabilities = new GLCapabilities(glProfile);
        glWindow = GLWindow.create(screen, glCapabilities);

        assert glWindow != null;

        glWindow.setUndecorated(false);
        glWindow.setAlwaysOnTop(false);
        glWindow.setFullscreen(false);
        glWindow.setPointerVisible(true);
        glWindow.confinePointer(false);
        glWindow.setTitle("CheckAmdExtenstion");
        glWindow.setSize(640, 480);
        glWindow.setVisible(true);
        glWindow.addGLEventListener(this);

        animator = new Animator();
        animator.add(glWindow);
        animator.start();
    }

    String[] extenstions = new String[]{
        "GL_AMD_performance_monitor", // gl-430-perf-monitor-amd
        "GL_AMD_blend_minmax_factor", // gl-500-blend-op-amd
        "GL_AMD_pinned_memory", // gl-500-buffer-pinned-amd
        "GL_AMD_vertex_shader_viewport_index", // gl-500-fbo-layered-amd
        "GL_AMD_vertex_shader_layer", // gl-500-fbo-layered-amd
        "GL_AMD_sample_positions", // gl-500-fbo-multisample-position-amd
        "GL_AMD_depth_clamp_separate", // gl-500-test-depth-clamp-separate-amd
        "GL_AMD_sparse_texture" // gl-500-texture-sparse-amd
    };

    @Override
    public void init(GLAutoDrawable drawable) {

        GL4 gl4 = drawable.getGL().getGL4();

        for (String extenstion : extenstions) {
            System.out.println(extenstion + ": " + gl4.isExtensionAvailable(extenstion));
        }
    }

    @Override
    public void dispose(GLAutoDrawable drawable) {
        animator.stop();
        System.exit(0);
    }

    @Override
    public void display(GLAutoDrawable drawable) {

        GL4 gl4 = drawable.getGL().getGL4();

        gl4.glViewport(0, 0, 640, 480);
        gl4.glClearBufferfv(GL_COLOR, 0, new float[]{1.0f, 0.5f, 0.0f, 1.0f}, 0);
    }

    @Override
    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {

    }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ui-command xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>c007fbb6-c9ab-4c88-84aa-3a4b6e83b7b6</uuid>
    <file-application>eFapsApp-Accounting</file-application>
    <file-revision>$Rev$</file-revision>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Accounting_SubPeriodTree_CollectMenu_Document</name>
        <access>
            <role>Accounting_Admin</role>
            <role>Accounting_Manager</role>
        </access>
        <target>
            <menu>Accounting_SubPeriodTree_CollectMenu_Document_Menu</menu>

Accounting_SubPeriodDocumentSumTable

            <evaluate method="getDocuments" program="org.efaps.esjp.accounting.SubPeriod">
                <property name="Type">Sales_DocumentSumAbstract</property>
                <property name="StatusGroup01">Sales_InvoiceStatus</property>
                <property name="Status01">Open</property>
                <property name="StatusGroup02">Sales_InvoiceStatus</property>
                <property name="Status02">Paid</property>
                <property name="StatusGroup03">Sales_InvoiceStatus</property>
                <property name="Status03">Draft</property>
                <property name="StatusGroup04">Sales_ReceiptStatus</property>
                <property name="Status04">Open</property>
                <property name="StatusGroup05">Sales_ReceiptStatus</property>
                <property name="Status05">Paid</property>
                <property name="StatusGroup06">Sales_ReceiptStatus</property>
                <property name="Status06">Draft</property>
                <property name="StatusGroup07">Sales_CreditNoteStatus</property>
                <property name="Status07">Open</property>
                <property name="StatusGroup08">Sales_CreditNoteStatus</property>
                <property name="Status08">Paid</property>
                <property name="StatusGroup09">Sales_CreditNoteStatus</property>
                <property name="Status09">Draft</property>
                <property name="StatusGroup10">Sales_ReminderStatus</property>
                <property name="Status10">Open</property>
                <property name="StatusGroup11">Sales_ReminderStatus</property>
                <property name="Status11">Paid</property>
                <property name="StatusGroup12">Sales_ReminderStatus</property>
                <property name="Status12">Draft</property>
            </evaluate>
        </target>
        <property name="Target">content</property>
        <property name="TargetShowCheckBoxes">true</property>
        <property name="Label">Accounting_PeriodTree_CollectMenu_Document.Label</property>
        <property name="TargetTitle">Accounting_PeriodTree_CollectMenu_Document.Title</property>
    </definition>
</ui-command>


text:
if [ $# != 3 ]
  then
    echo -e "\nUse:\ninstall_app appname coderbase apppath\n"
    exit
fi

app=$1
base=$2
from=$3

mkdir "$base/apps/$app"
mkdir "$base/static/apps/$app"
mkdir "$base/static/apps/$app/js"
mkdir "$base/static/apps/$app/css"
mkdir "$base/static/apps/$app/media"
mkdir "$base/views/apps/$app"

cp $from/$app/app/* $base/apps/$app/
cp $from/$app/views/* $base/views/apps/$app/
cp $from/$app/static/js/* $base/static/apps/$app/js/
cp $from/$app/static/css/* $base/static/apps/$app/css/
cp $from/$app/static/media/* $base/static/apps/$app/media/


text:
package com.vodafone.v10.system.media;

public interface ResourceOperator {
	int getIndexOfResource(int id);

	int getResourceCount();

	int getResourceID(int index);

	String getResourceName(int id);

	String[] getResourceNames();

	int getResourceType();

	void setResource(MediaPlayer player, int index);

	void setResourceByID(MediaPlayer player, int id);

	void setResourceByTitle(MediaPlayer player, String name);
}


text:
"""
Submit a jip script to a remote cluster

usage: jip-submit [-f] [-k] [-P <profile>] [-s <spec>] [-t <time>] [-q <queue>]
                  [-p <prio>] [-A <account>] [-m <mem>] [-n <name>]
                  [-o <out>] [-e <err>] [-D <dir>] [-C <threads>] [-T <tasks>]
                  [-N <nodes>] [--tasks-per-node <n>] [-E <pe>]
                  [-H] [--dry] [--show] [--with-profiler] <tool> [<args>...]

Options:
  -f, --force              force command execution
  -k, --keep               do not perform a cleanup step after job failure or
                           cancellation
  -P, --profile <profile>  Select a job profile for resubmission
  -s, --spec <spec>        Job environment specification file (see jip specs)
  -t, --time <time>        Max wall-clock time for the job. Specify in minutes,
                           or use the suffixes 'h', 'm', and 's'. For example,
                           '3h30m'.
  -q, --queue <queue>      Job queue
  -p, --priority <prio>    Job priority
  -A, --account <account>  The account to use for submission
  -C, --threads <threads>  Number of threads for each task. If you do not
                           request > 1 tasks, this is the number of CPU's
                           assigned to the job.
  -T, --tasks <tasks>      Number of requested tasks. In case you submit MPI
                           jobs, this is the number of MPI CPU's the job
                           request
  -N, --nodes <nodes>      Number of nodes assigned to the job
  --tasks-per-node <n>     If supported by your grid engine, you can use this
                           to specify how many tasks should be scheduled on
                           each requested node
  -E, --environment <pe>   Specify an environment if your grid engine supports
                           it. For SGE, this is translated to the parallel
                           environment
  -m, --mem <mem>          Max memory assigned to the job in MB. Also supports
                           suffixes like G, M or K for Gigabyte, Megabyte and
                           Kilobyte
  -n, --name <name>        Job name
  -o, --out <out>          Stdout log file
  -e, --log <err>          Stderr log file
  -D, --working-dir <dir>  The jobs working directory
  -H, --hold               submit job put put in on hold and don't send
                           it to the queue
  --dry                    Do not submit but show the dry configuration
  --show                   Do not submit but show to commands that will be
                           executed
  --with-profiler          execute the run with a profiler
  <tool>                   the tool that will be executed
  <args>                   optional script argument

Other Options:
    -h --help             Show this help message

"""
import sys

import jip
import jip.profiles
from . import parse_args, show_dry, show_commands, colorize, RED, \
    YELLOW
import jip.jobs
from jip.logger import getLogger

log = getLogger("jip.cli.jip_submit")

def main(argv=None):
    args = parse_args(__doc__, argv=argv)
    script_file = args["<tool>"]
    script_args = args["<args>"]
    try:
        script = jip.find(script_file)
    except LookupError, e:
        print >>sys.stderr, str(e)
        sys.exit(1)

    # load profile
    profile = jip.profiles.get(name='default'
                               if not args['--profile']
                               else args['--profile'])
    profile.tool_name = script.name
    if args['--spec']:
        spec_prof = jip.profiles.Profile.from_file(args['--spec'])
        spec_prof.update(profile)
        profile = spec_prof

    profile.load_args(args)
    log.info("Profile: %s", profile)

    if args['--dry'] or args['--show']:
        # we handle --dry and --show separatly,
        # create the jobs and call the show commands
        jobs = jip.jobs.create_jobs(script, args=script_args, profile=profile)
        error = None
        try:
            jip.jobs.check_output_files(jobs)
            jip.jobs.check_queued_jobs(jobs)
        except Exception as err:
            error = err
        if args['--dry']:
            show_dry(jobs, options=script.options, profiles=True)
        if args['--show']:
            show_commands(jobs)
        if error:
            print >>sys.stderr, "%s\n" % (colorize("Validation error!", RED))
            print >>sys.stderr, str(error)
            sys.exit(1)
        return

    #####################################################
    # prepare jobs for submission
    #####################################################
    force = args['--force']
    jobs = jip.jobs.create_jobs(script, args=script_args, keep=args['--keep'],
                                profile=profile,
                                profiler=args['--with-profiler'])
    if len(jobs) == 0:
        return
    if args['--hold']:
        #####################################################
        # Only save the jobs and let them stay on hold
        #####################################################
        jip.db.save(jobs)
        print "Jobs stored and put on hold"
    else:
        try:
            #####################################################
            # Iterate the executions and submit
            #####################################################
            for exe in jip.jobs.create_executions(jobs, save=True,
                                                  check_outputs=not force,
                                                  check_queued=not force):
                if exe.completed and not force:
                    print colorize("Skipping %s" % exe.name, YELLOW)
                else:
                    if jip.jobs.submit_job(exe.job, force=force):
                        print "Submitted %s with remote id %s" % (
                            exe.job.id, exe.job.job_id
                        )
        except Exception as err:
            log.debug("Submission error: %s", err, exc_info=True)
            print >>sys.stderr, colorize("Error while submitting job:", RED), \
                colorize(str(err), RED)
            ##################################################
            # delete all submitted jobs
            ##################################################
            jip.jobs.delete(jobs, clean_logs=True)

if __name__ == "__main__":
    main()


text:
package com.littlechoc.olddriver.dao;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.littlechoc.olddriver.Application;
import com.littlechoc.olddriver.model.Pattern;
import com.littlechoc.olddriver.model.PatternCategory;
import com.littlechoc.olddriver.utils.JsonUtils;
import com.littlechoc.olddriver.utils.SpUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Junhao Zhou 2017/4/16
 */

public class PatternDao {

  public static final String TAG = "PatternDao";

  private static final String SP_NAME = "com.littlechoc.olddriver.pattern";

  private static final String KEY_CATEGORY = "category";

  private static final String KEY_IS_INIT = "is_init";

  private static final String PATTERN_PREFIX = "";

  ////////////// Init Begin

  private static final List<PatternCategory> DEFAULT_PATTERN_LIST = new ArrayList<>();

  private static final String[] COMMON_PATTERN_LIST = new String[]{
          "左转弯", "左急转弯", "右转弯", "右急转弯", "加速", "急加速", "刹车", "急刹车", "混合", "无"
  };

  static {
    PatternCategory commonCategory = new PatternCategory("common", PatternCategory.COMMON);
    PatternCategory sensorCategory = new PatternCategory("sensor", PatternCategory.SENSOR);
    PatternCategory obdCategory = new PatternCategory("obd", PatternCategory.OBD);
    DEFAULT_PATTERN_LIST.add(commonCategory);
    DEFAULT_PATTERN_LIST.add(sensorCategory);
    DEFAULT_PATTERN_LIST.add(obdCategory);

    List<Pattern> patterns = new ArrayList<>();
    commonCategory.setPatternList(patterns);
    int index = 0;
    for (String patternName : COMMON_PATTERN_LIST) {
      Pattern pattern = new Pattern();
      pattern.setName(patternName);
      pattern.setId(generatePatternId(commonCategory.getId(), index++));
      pattern.setCategoryId(commonCategory.getId());
      patterns.add(pattern);
    }
  }

  private final List<PatternCategory> categoryList = new ArrayList<>();

  private static volatile PatternDao instance;

  public static PatternDao getInstance() {
    if (instance == null) {
      synchronized (PatternDao.class) {
        if (instance == null) {
          instance = new PatternDao();
        }
      }
    }
    return instance;
  }

  private PatternDao() {
    init();
  }

  private void init() {
    SharedPreferences preferences = getPreferences();
    boolean isInit = preferences.getBoolean(KEY_IS_INIT, false);
    if (!isInit) {
      initDefaultData();
    } else {
      loadData();
    }
  }

  private void initDefaultData() {
    categoryList.addAll(DEFAULT_PATTERN_LIST);
    SharedPreferences.Editor editor = getPreferences().edit();
    JsonArray categoryArray = new JsonArray();
    for (PatternCategory patternCategory : DEFAULT_PATTERN_LIST) {
      JsonObject jsonObject = new JsonObject();
      categoryArray.add(jsonObject);
      jsonObject.addProperty("name", patternCategory.getName());
      jsonObject.addProperty("id", patternCategory.getId());

      List<Pattern> patterns = patternCategory.getPatternList();
      Gson gson = new Gson();
      editor.putString(PATTERN_PREFIX + patternCategory.getId(), gson.toJson(patterns));
    }
    editor.putString(KEY_CATEGORY, categoryArray.toString());
    editor.putBoolean(KEY_IS_INIT, true);
    SpUtils.commit(editor);
  }

  private void loadData() {
    SharedPreferences preferences = getPreferences();
    String categoryJson = preferences.getString(KEY_CATEGORY, "");
    if (!TextUtils.isEmpty(categoryJson)) {
      List<PatternCategory> categories;
      categories = JsonUtils.newInstance().fromJson(categoryJson, new TypeToken<List<PatternCategory>>() {
      }.getType());
      if (categories == null) {
        categories = new ArrayList<>();
      }
      categoryList.addAll(categories);
      for (PatternCategory category : categories) {
        category.setPatternList(loadPatterns(category.getId()));
      }
    }
  }

  private List<Pattern> loadPatterns(int categoryId) {
    List<Pattern> patterns;
    SharedPreferences preferences = getPreferences();
    String patternJson = preferences.getString(PATTERN_PREFIX + categoryId, "");
    if (!TextUtils.isEmpty(patternJson)) {
      patterns = JsonUtils.newInstance().fromJson(patternJson, new TypeToken<List<Pattern>>() {
      }.getType());
    } else {
      patterns = new ArrayList<>();
    }
    return patterns;
  }

  public void reset() {
    SharedPreferences.Editor editor = getPreferences().edit();
    editor.putBoolean(KEY_IS_INIT, false);
    SpUtils.commit(editor);
  }

  //////////////// Init End

  public List<PatternCategory> getCategoryList() {
    return categoryList;
  }

  /**
   * @param categoryId {@link PatternCategory#COMMON}, {@link PatternCategory#OBD}, {@link PatternCategory#SENSOR} or {@link PatternCategory#getId()}
   * @return pattern list
   */
  public List<Pattern> getPatternListByCategory(int categoryId) {
    for (PatternCategory category : categoryList) {
      if (category.getId() == categoryId) {
        return category.getPatternList();
      }
    }
    return new ArrayList<>();
  }

  /**
   * @param categoryName category name
   */
  public void addNewPatternCategory(String categoryName) {
    List<PatternCategory> categories = getCategoryList();
    int id = categories.size();
    PatternCategory category = new PatternCategory(categoryName, id);
    category.setPatternList(new ArrayList<Pattern>());
    categoryList.add(category);
    saveCategories();
  }

  /**
   * @param categoryId  category id
   * @param patternName patternName
   */
  public void addNewPattern(int categoryId, String patternName) {
    List<Pattern> patterns = getPatternListByCategory(categoryId);
    Pattern pattern = new Pattern();
    pattern.setCategoryId(categoryId);
    pattern.setId(generatePatternId(categoryId, patterns.size()));
    pattern.setName(patternName);
    patterns.add(pattern);

    savePatterns(categoryId);
  }

  /**
   * save
   */
  public void saveCategories() {
    SharedPreferences.Editor editor = getPreferences().edit();
    JsonArray categoryArray = new JsonArray();
    for (PatternCategory patternCategory : DEFAULT_PATTERN_LIST) {
      JsonObject jsonObject = new JsonObject();
      categoryArray.add(jsonObject);
      jsonObject.addProperty("name", patternCategory.getName());
      jsonObject.addProperty("id", patternCategory.getId());
    }
    editor.putString(KEY_CATEGORY, categoryArray.toString());
    SpUtils.commit(editor);
  }

  /**
   * @param categoryId category id
   */
  public void savePatterns(int categoryId) {
    List<Pattern> patterns = getPatternListByCategory(categoryId);
    Gson gson = new Gson();
    SharedPreferences.Editor editor = getPreferences().edit();
    editor.putString(PATTERN_PREFIX + categoryId, gson.toJson(patterns));
    SpUtils.commit(editor);
  }

  /**
   * @param id pattern id
   * @return pattern
   */
  public Pattern getPatternById(int id) {
    if (id == Pattern.UNKNOWN.getId()) {
      return Pattern.UNKNOWN;
    }
    int categoryId = getCategoryIdByPatternId(id);
    List<Pattern> patterns = getPatternListByCategory(categoryId);
    for (Pattern pattern : patterns) {
      if (pattern.getId() == id) {
        return pattern;
      }
    }
    return Pattern.UNKNOWN;
  }

  /**
   * mask of category id in pattern id
   */
  private static final int CATEGORY_MASK = 100;

  /**
   * @param categoryId category id
   * @param index      index of pattern in category
   * @return generated pattern id
   */
  private static int generatePatternId(int categoryId, int index) {
    return categoryId * CATEGORY_MASK + index;
  }

  /**
   * @param patternId pattern id
   * @return id of category which pattern belongs
   */
  private static int getCategoryIdByPatternId(int patternId) {
    return patternId / CATEGORY_MASK;
  }

  private static SharedPreferences getPreferences() {
    return Application.getInstance().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
  }
}


text:
% Retrieve CSV element
function result = csv_lookup(name,csv)
   % Initialize value
   result = 0;

   % Size of CSV data
   [rows,cols] = size(csv);

   % Find matching name column in csv data
   match = strcmpi(deblank(name),csv(1,:));
   % Retrieve value
   for i = 1:cols,
      if (match(i)),
         result = i;
      end
   end


text:
#main {
  max-width: 800px;
  margin: 0 auto;
}

.post {
  max-width: 600px;
  margin-right: 200px;
}

nav {
  float: right;
  width: 200px;
}

label {
    /* To make sure that all label have the same size and are properly align */
    display: inline-block;
    width: 90px;
    text-align: right;
}

input, textarea {
    /* To make sure that all text fields have the same font settings
       By default, textareas have a monospace font */
    font: 1em sans-serif;

    /* To give the same size to all text field */
    width: 600px;
    -moz-box-sizing: border-box;
    box-sizing: border-box;

    /* To harmonize the look & feel of text field border */
    border: 1px solid #999;
}

textarea {
    /* To properly align multiline text fields with their labels */
    vertical-align: top;

    /* To give enough room to type some text */
    height: 15em;

    /* To allow users to resize any textarea vertically
       It does not work on every browsers */
    resize: vertical;
}

input:focus, textarea:focus {
    /* To give a little highlight on active elements */
    border-color: #000;
}


text:
layout: post
title: "Major Internet Issues Today"
date: 2014-08-12 18:37:56 -0500
comments: false
categories:
- BGP
- Networking
- ISP
- Network Monitoring
- System Administration
- Troubleshooting
share: true
---
There has been a lot of noise in Canada on Twitter about the widespread network issues Shaw was experiencing, and also a lot of speculation about what the cause of those issues were. Simultaneously, the number of IPv4 routes advertised in the global routing table went over 512k, triggering memory overflows and crashes for some providers who had their heads in the sand about this problem that has been well known since 2007.

### Shaw Problems

I downed BGP with Shaw around 10am this morning. Connectivity into Shaw without Shaw BGP up seemed better than on Shaw's network itself. Epic Information Solutions turned up MTS Allstream BGP in place of Shaw around 4pm.

The Shaw issues were so widespread that [The Register](http://www.theregister.co.uk/2014/08/12/nationwide_outage_at_canadian_isp_shaw/) reported "Canadian ISP Shaw stumbles around internet with mystery 'routing' sickness".

{% img /static/blog-img/2014-08-12-shaw-outages.png %}

(from [http://canadianoutages.com/status/shaw/map/](http://canadianoutages.com/status/shaw/map/))

### BGP Routes/Updates

I don't have a graph of the BGP updates from a Shaw peering session specifically, but I do have graphs for sessions with Hurricane Electric.

Global BGP Routes:

{% img /static/blog-img/2014-08-12-bgp-routes.png %}

BGP Updates:

{% img /static/blog-img/2014-08-12-bgp-update-spike.png %}

You can see the spike of updates around the time that the routes hit 510k (where I was monitoring at least). This caused some routers to crash, and generally not operate as intended. Prefixes were withdrawn, and came back, and there was a lot of churn in the global routing table at this time. The other spikes of updates were a result of emergency unscheduled/un-coordinated changes to reboot and increase limits by numerous providers with affected equipment.

### Global Problems

A major US network with multiple ASNs (AS701 & AS705) had a network event which temporarily caused de-aggregation of their large prefixes, announcing more specific /24's covering large chunks of their less-specific advertisements. Apparently this added approximately 15,000 new networks into the global BGP table for a short period of time. Peers of these networks could have received these announcements over un-filtered peering sessions, installing them into their own networks, and causing a domino effect of failures.


text:
module Nexpose
  # Object used to manage the global settings of a Nexpose console.
  #
  class GlobalSettings
    # IP addresses and/or host names that will be excluded from scanning across
    # all sites.
    attr_accessor :asset_exclusions

    # Whether asset linking in enabled.
    attr_accessor :asset_linking

    # Whether control scanning in enabled. A feature tied to ControlsInsight
    # integration.
    attr_accessor :control_scanning

    # XML document representing the entire configuration.
    attr_reader :xml

    # Private constructor. See #load method for retrieving a settings object.
    #
    def initialize(xml)
      @xml = xml

      @asset_linking = parse_asset_linking_from_xml(xml)
      @asset_exclusions = HostOrIP.parse(xml)
      @control_scanning = parse_control_scanning_from_xml(xml)
    end

    # Returns true if controls scanning is enabled.
    def control_scanning?
      control_scanning
    end

    # Save any updates to this settings object to the Nexpose console.
    #
    # @param [Connection] nsc Connection to a Nexpose console.
    # @return [Boolean] Whether saving was successful.
    #
    def save(nsc)
      # load method can return XML missing this required attribute.
      unless REXML::XPath.first(xml, '//*[@recalculation_duration]')
        risk_model = REXML::XPath.first(xml, '//riskModel')
        risk_model.add_attribute('recalculation_duration', 'do_not_recalculate')
      end

      replace_exclusions(xml, asset_exclusions)
      add_control_scanning_to_xml(xml, control_scanning)
      add_asset_linking_to_xml(xml, asset_linking)

      response = AJAX.post(nsc, '/data/admin/global-settings', xml)
      XMLUtils.success? response
    end

    # Add an asset exclusion setting.
    #
    # @param [IPRange|HostName|String] host_or_ip Host or IP (range) to exclude
    #   from scanning by the Nexpose console.
    #
    def add_exclusion(host_or_ip)
      asset = host_or_ip
      unless host_or_ip.respond_to?(:host) || host_or_ip.respond_to?(:from)
        asset = HostOrIP.convert(host_or_ip)
      end
      @asset_exclusions << asset
    end

    # Remove an asset exclusion setting.
    # If you need to remove a range of IPs, be sure to explicitly supply an
    # IPRange object to the method.
    #
    # @param [IPRange|HostName|String] host_or_ip Host or IP (range) to remove
    #   from the exclusion list.
    #
    def remove_exclusion(host_or_ip)
      asset = host_or_ip
      unless host_or_ip.respond_to?(:host) || host_or_ip.respond_to?(:from)
        # Attept to convert String to appropriate object.
        asset = HostOrIP.convert(host_or_ip)
      end
      @asset_exclusions = asset_exclusions.reject { |a| a.eql? asset }
    end

    # Load the global settings from a Nexpose console.
    #
    # @param [Connection] nsc Connection to a Nexpose console.
    # @return [GlobalSettings] Settings object for the console.
    #
    def self.load(nsc)
      response = AJAX.get(nsc, '/data/admin/global-settings')
      new(REXML::Document.new(response))
    end

    private

    # Internal method for updating exclusions before saving.
    def replace_exclusions(xml, exclusions)
      xml.elements.delete('//ExcludedHosts')
      elem = xml.root.add_element('ExcludedHosts')
      exclusions.each do |exclusion|
        elem.add_element(exclusion.as_xml)
      end
    end

    # Internal method for parsing XML for whether control scanning in enabled.
    def parse_control_scanning_from_xml(xml)
      enabled = false
      if elem = REXML::XPath.first(xml, '//enableControlsScan[@enabled]')
        enabled = elem.attribute('enabled').value.to_i == 1
      end
      enabled
    end

    # Internal method for updating control scanning before saving.
    def add_control_scanning_to_xml(xml, enabled)
      if elem = REXML::XPath.first(xml, '//enableControlsScan')
        elem.attributes['enabled'] = enabled ? '1' : '0'
      else
        elem = REXML::Element.new('ControlsScan', xml.root)
        elem.add_element('enableControlsScan',
                         'enabled' => enabled ? '1' : '0')
      end
    end

    # Internal method for parsing XML for whether asset linking in enabled.
    def parse_asset_linking_from_xml(xml)
      enabled = true
      if elem = REXML::XPath.first(xml, '//AssetCorrelation[@enabled]')
        enabled = elem.attribute('enabled').value.to_i == 1
      end
      enabled
    end

    # Internal method for updating asset linking before saving.
    def add_asset_linking_to_xml(xml, enabled)
      elem = REXML::XPath.first(xml, '//AssetCorrelation')
      return nil unless elem

      elem.attributes['enabled'] = enabled ? '1' : '0'
    end
  end
end


text:
require "pig-media-server/version"
require 'pit'
require 'groonga'
require 'json'
require 'digest/md5'
require 'date'
require 'time'
require 'fileutils'
require 'sewell'
require 'uri'


text:
exports.loadApi = require('./lib/api/loadApi.js').default;
exports.loadApp = require('./lib/loadApp.js').default;


text:
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using AndroidX.Core.App;
using Toggl.Core;
using Toggl.Core.Analytics;
using Toggl.Core.Exceptions;
using Toggl.Core.Extensions;
using Toggl.Core.Interactors;
using Toggl.Droid.Helper;
using Toggl.Droid.Widgets;
using static Toggl.Droid.SystemServices.JobServicesConstants;
using static Toggl.Droid.Helper.NotificationsConstants;
using static Toggl.Droid.Widgets.WidgetsConstants;

namespace Toggl.Droid.SystemServices
{
    [Service(Permission = "android.permission.BIND_JOB_SERVICE", Exported = true)]
    public sealed class WidgetsForegroundService : IntentService
    {
        private IInteractorFactory interactorFactory => AndroidDependencyContainer.Instance.InteractorFactory;
        private ITimeService timeService => AndroidDependencyContainer.Instance.TimeService;

        protected override void OnHandleIntent(Intent intent)
        {
            if (OreoApis.AreAvailable)
            {
                var notificationManager = GetSystemService(NotificationService) as NotificationManager;
                var channel = new NotificationChannel(DefaultChannelId, DefaultChannelName, NotificationImportance.Low);
                channel.Description = DefaultChannelDescription;
                channel.EnableVibration(false);
                channel.SetVibrationPattern(NoNotificationVibrationPattern);
                notificationManager.CreateNotificationChannel(channel);
            }

            var notificationBuilder = new NotificationCompat.Builder(this, DefaultChannelId);
            notificationBuilder.SetVibrate(NoNotificationVibrationPattern);

            StartForeground(WidgetForegroundServiceJobId, notificationBuilder.Build());

            onHandleIntentAsync(intent);
        }

        private async void onHandleIntentAsync(Intent intent)
        {
            AndroidDependencyContainer.EnsureInitialized(Application.Context);
            AndroidDependencyContainer.Instance.WidgetsService.Start();

            var action = intent.Action;

            switch (action)
            {
                case StartTimeEntryAction:
                    await handleStartTimeEntry();
                    break;
                case StopRunningTimeEntryAction:
                    await handleStopRunningTimeEntry();
                    break;
                case SuggestionTapped:
                    await continueTimeEntryFromSuggestion(intent);
                    break;
                default:
                    throw new InvalidOperationException($"Cannot handle intent with action {action}");
            }

            StopForeground(true);
        }

        private async Task handleStartTimeEntry()
        {
            var now = timeService.CurrentDateTime;
            var workspaceId = (await interactorFactory.GetDefaultWorkspace().Execute()).Id;
            var prototype = "".AsTimeEntryPrototype(now, workspaceId);
            await interactorFactory.CreateTimeEntry(prototype, TimeEntryStartOrigin.Widget).Execute();
        }

        private async Task handleStopRunningTimeEntry()
        {
            var now = timeService.CurrentDateTime;

            try
            {
                await interactorFactory.StopTimeEntry(now, TimeEntryStopOrigin.Widget).Execute();
            }
            catch(NoRunningTimeEntryException)
            {
                /* There is no need to handle this because stopping a time entry should be
                 * idempotent operation. This happens only when user is tapping the widget's
                 * stop button multiple times in quick succession.
                 */
            }
        }

        private async Task continueTimeEntryFromSuggestion(Intent intent)
        {
            var index = intent.GetIntExtra(TappedSuggestionIndex, 0);

            var suggestions = WidgetSuggestionItem.SuggestionsFromSharedPreferences().ToList();
            var suggestion = suggestions[index];

            var now = timeService.CurrentDateTime;

            var timeEntryPrototype = suggestion.Description.AsTimeEntryPrototype(
                startTime: now,
                workspaceId: suggestion.WorkspaceId,
                projectId: suggestion.ProjectId,
                taskId: suggestion.TaskId,
                isBillable:suggestion.IsBillable,
                tagIds: suggestion.TagsIds);

            await interactorFactory.CreateTimeEntry(timeEntryPrototype, TimeEntryStartOrigin.Widget).Execute();
        }
    }
}


text:
declare module 'http-cache-semantics' {
  interface Request {
    url: string;
    method: string;
    headers: Headers;
  }

  interface Response {
    status: number;
    headers: Headers;
  }

  type Headers = { [name: string]: string };

  class CachePolicy {
    constructor(request: Request, response: Response);

    storable(): boolean;

    satisfiesWithoutRevalidation(request: Request): boolean;
    responseHeaders(): Headers;

    age(): number;
    timeToLive(): number;

    revalidationHeaders(request: Request): Headers;
    revalidatedPolicy(
      request: Request,
      response: Response,
    ): { policy: CachePolicy; modified: boolean };

    static fromObject(object: object): CachePolicy;
    toObject(): object;

    _url: string | undefined;
    _status: number;
    _rescc: { [key: string]: any };
  }

  export = CachePolicy;
}


text:
package org.apache.shiro.authc.pam;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Collection;

/**
 * {@link AuthenticationStrategy} implementation that only accepts the account data from
 * the first successfully consulted Realm and ignores all subsequent realms.  This is slightly
 * different behavior than {@link AtLeastOneSuccessfulStrategy}, so please review both to see
 * which one meets your needs better.
 *
 * @see AtLeastOneSuccessfulStrategy AtLeastOneSuccessfulAuthenticationStrategy
 * @since 0.9
 */
public class FirstSuccessfulStrategy extends AbstractAuthenticationStrategy {

    private boolean stopAfterFirstSuccess;

    public void setStopAfterFirstSuccess (boolean stopAfterFirstSuccess ) {

        this.stopAfterFirstSuccess  = stopAfterFirstSuccess ;
    }

    public boolean getStopAfterFirstSuccess() {
        return stopAfterFirstSuccess ;
    }

    /**
     * Returns {@code null} immediately, relying on this class's {@link #merge merge} implementation to return
     * only the first {@code info} object it encounters, ignoring all subsequent ones.
     */
    public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token) throws AuthenticationException {
        return null;
    }

    /**
     * Throws ShortCircuitIterationException if stopAfterFirstSuccess is set and authentication is
     * successful with a previously consulted realm.
     * Returns the aggregate method argument, without modification
     * otherwise.
     */
    public AuthenticationInfo beforeAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
        if (getStopAfterFirstSuccess() && aggregate != null && !isEmpty(aggregate.getPrincipals())) {
            throw new ShortCircuitIterationException();
        }
        return aggregate;
    }

    private static boolean isEmpty(PrincipalCollection pc) {
        return pc == null || pc.isEmpty();
    }

    /**
     * Returns the specified {@code aggregate} instance if is non null and valid (that is, has principals and they are
     * not empty) immediately, or, if it is null or not valid, the {@code info} argument is returned instead.
     *

     * This logic ensures that the first valid info encountered is the one retained and all subsequent ones are ignored,
     * since this strategy mandates that only the info from the first successfully authenticated realm be used.
     */
    protected AuthenticationInfo merge(AuthenticationInfo info, AuthenticationInfo aggregate) {
        if (aggregate != null && !isEmpty(aggregate.getPrincipals())) {
            return aggregate;
        }
        return info != null ? info : aggregate;
    }
}


text:
{% extends "layout-vary.html" %}

{% block page_title %}
  Example - Forms
{% endblock %}

{% block content %}

      <form action="/multiple-brands/verify/account-created" method="post" class="form">

          {% include "includes/passing-data.html" %}

      </form>

{% endblock %}


text:
<?php

namespace Base\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Paginator\Paginator,
    Zend\Paginator\Adapter\ArrayAdapter;
use Zend\Config\Reader\Xml;

use Zend\Authentication\AuthenticationService,
    Zend\Authentication\Storage\Session as SessionStorage;

class CompraController extends AbstractActionController
{
    public function indexAction()
    {
        $filter = new \NumberFormatter('pt_BR', \NumberFormatter::CURRENCY);
        $xml = new Xml();
        $cep = null;
        $valorFreteFormatado = null;
        $service = $this->getServiceLocator()->get('CarrinhoCompras\Model\Carrinho');
        $auth = new AuthenticationService;
        $auth->setStorage(new SessionStorage("Usuario"));
        $valorTotal = $service->calculoTotal(); //sem frete.
        if($auth->hasIdentity())
        {
            $em = $this->getServiceLocator()->get("Doctrine\ORM\EntityManager");
            $entity = $em->getRepository("Usuario\Entity\UsuarioCadastro")->findOneByusuariosusuarios($auth->getIdentity()->getIdusuario());
            $cep = $entity->getCep();
            $serviceFrete = $this->getServiceLocator()->get("DrkCorreios\Service\Frete");
            $serviceFrete->setSCepDestino($cep);
            $freteCalculo = $xml->fromString($serviceFrete->calcularFrete());
            if($freteCalculo['cServico']['Erro'] == 0)
            {
                $valueUpdated = str_replace("R$", "", $service->calculoTotal());
                $valueUpdated = str_replace(".", "", $valueUpdated);
                $valueUpdated = str_replace(",", ".", $valueUpdated);

                $valorFrete = str_replace(",", ".", $freteCalculo['cServico']['Valor']);
                $valorTotal = $filter->format($valorFrete+$valueUpdated); //Total com frete
                $valorFreteFormatado = $filter->format($valorFrete);
            }
        }
            $em = $this->getServiceLocator()->get("Doctrine\ORM\EntityManager");
            $repository = $em->getRepository("Produto\Entity\ProdutoProdutos");
            $produtosPublicidade = $repository->geraOfertasCarrinho();

                shuffle($produtosPublicidade);
    	return new viewModel(array("carrinhoLista" => array(
    				"listaAtual" =>  $service->lista(),
    				"valorTotal" => $valorTotal
    		),"cep" => $cep, "valorFrete" => $valorFreteFormatado, "produtosPublicidade" => $produtosPublicidade));
    }
    public function finalizaAction()
    {
        $filter = new \NumberFormatter('pt_BR', \NumberFormatter::CURRENCY);
        $xml = new Xml();
        //Cadastro
            $nome= null;
            $cep = null;
            $endereco = null;
            $numero = null;
            $bairro = null;
            $estados = null;
            $cidades = null;
            $cidadeEstadoUF = null;
            $cidadeSelected = null;
        ///frete
            $frete = null;
        $entity = null;
        $auth = new AuthenticationService;
        $auth->setStorage(new SessionStorage("Usuario"));
        $entityAlternativos = null;
        $service = $this->getServiceLocator()->get('CarrinhoCompras\Model\Carrinho');
        if($auth->hasIdentity())
        {
            $em = $this->getServiceLocator()->get("Doctrine\ORM\EntityManager");
            $entity = $em->getRepository("Usuario\Entity\UsuarioCadastro")->findOneBy(array("usuariosusuarios" => $auth->getIdentity()->getIdusuario(),"padrao" => "1"));
            $entityAlternativos = $em->getRepository("Usuario\Entity\UsuarioCadastro")->findBy(array("usuariosusuarios" => $auth->getIdentity()->getIdusuario(),"padrao" => "0"));
            $entityCadastroSelected = $em->getRepository("Usuario\Entity\UsuarioCadastro")->findOneBy(array("usuariosusuarios" => $auth->getIdentity()->getIdusuario(),"ativo" => "1"));

            $estados = $em->getRepository("Usuario\Entity\MapeamentoEstado")->findAll();
                    $nome = $entity->getNome();
                    $cep = $entity->getCep();
                    $cepAtivo = $entityCadastroSelected->getCep();
                    $endereco = $entity->getRua();
                    $numero = $entity->getNumero();
                    $bairro = $entity->getBairro();
                    if($entity->getMapeamentocidade())
                    {
                        $cidadeEstadoUF = $entity->getMapeamentocidade()->getMapeamentoestado()->getNomeclatura();
                        $cidadeSelected = $entity->getMapeamentocidade()->getIdcidade();
                    	$cidades = $em->getRepository("Usuario\Entity\MapeamentoCidade")->findBynomeclatura($cidadeEstadoUF);
                    }
                    if(!empty($cepAtivo))
                    {
                        $serviceFrete = $this->getServiceLocator()->get("DrkCorreios\Service\Frete");
                        $serviceFrete->setSCepDestino($cepAtivo);
                        $freteCalculo = $xml->fromString($serviceFrete->calcularFrete());
                        if($freteCalculo['cServico']['Erro'] == 0)
                        {
                            $valueUpdated = str_replace("R$", "", $service->calculoTotal());
                            $valueUpdated = str_replace(".", "", $valueUpdated);
                            $valueUpdated = str_replace(",", ".", $valueUpdated);

                            $valorFrete = str_replace(",", ".", $freteCalculo['cServico']['Valor']);
                            $frete = array("valorFrete" => $filter->format($valorFrete), "valorfreteTotal" => $filter->format($valorFrete+$valueUpdated));
                        }
                    }
        }
    	return new viewModel(array("carrinhoLista" => array(
    				"listaAtual" =>  $service->lista(),
    				"valorTotal" => $service->calculoTotal(),

    		),"auth" => $auth, "estados" => $estados,"cidades" => $cidades,"cidadeEstadoUF" => $cidadeEstadoUF,"cidadeSelected" => $cidadeSelected,"nomeCompleto" => $nome, "cep" => $cep,"endereco" => $endereco, "numero" => $numero, "bairro" => $bairro,"frete" =>$frete,"cadastro" => $entity,"cadastrosAlternativos" => $entityAlternativos));
    }

    public function getEstoqueAction()
    {
        $request = $this->getRequest();
        $info = array();
        if($request->isPost())
        {
            $post = $request->getPost()->toArray();
            if(!empty($post['actionId']))
            {
                $em = $this->getServiceLocator()->get("Doctrine\ORM\EntityManager");
               $produto = $em->getRepository("Produto\Entity\ProdutoProdutos")->findOneByidproduto($post['actionId']);
               $entity = $em->getRepository("Pagamento\Entity\PagamentoControleestoque")->findOneByprodutoproduto($produto);
                $info['produto'] = $entity;
            }
        }
        $viewModel = new ViewModel(array("data" => $info));
        $viewModel->setTerminal(true);
        return $viewModel;

    }
}


text:
"""Example showing how to use tfjs binary in python code."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import subprocess

def predict(binary_path,
            model_path,
            inputs_dir,
            outputs_dir,
            backend=None,
            tf_output_name_file=None):
  """Use tfjs binary to make inference and store output in file.

  Args:
    binary_path: Path to the nodejs binary. The path can be an absolute path
      (preferred) or a relative path from this python script's current
      directory.
    model_path: Directory to TensorFlow.js model's json file.
    inputs_dir: Directory to the inputs files, including data, shape and dtype
      files.
    outputs_dir: Directory to write the outputs files, including data, shape
      and dtype files.
    backend: Optional. Choose which TensorFlow.js backend to use. Supported
      backends include cpu and wasm. Default: cpu
    tf_output_name_file: Optional. File name of the tf_output_name, if file does
      not exist, will use the default outputs of the model.
  """
  model_path_option = '--model_path=' + model_path
  inputs_dir_option = '--inputs_dir=' + inputs_dir
  outputs_dir_option = '--outputs_dir=' + outputs_dir

  tfjs_inference_command = [
      binary_path, model_path_option, inputs_dir_option,
      outputs_dir_option
  ]

  if tf_output_name_file:
    tf_output_name_file_option = '--tf_output_name_file=' + tf_output_name_file
    tfjs_inference_command.append(tf_output_name_file_option)

  if backend:
    backend_option = '--backend=' + backend
    tfjs_inference_command.append(backend_option)

  popen = subprocess.Popen(
      tfjs_inference_command,
      stdin=subprocess.PIPE,
      stdout=subprocess.PIPE,
      stderr=subprocess.PIPE)
  stdout, stderr = popen.communicate()

  if popen.returncode != 0:
    raise ValueError('Inference failed with status %d\nstderr:\n%s' %
                     (popen.returncode, stderr.decode()))


text:
package org.jasig.cas.authentication;

import org.jasig.cas.authentication.handler.PasswordEncoder;
import org.jasig.cas.authentication.handler.PrincipalNameTransformer;
import org.jasig.cas.integration.pac4j.authentication.handler.support.UsernamePasswordWrapperAuthenticationHandler;
import org.pac4j.http.credentials.authenticator.Authenticator;
import org.pac4j.http.credentials.password.NopPasswordEncoder;
import org.pac4j.stormpath.credentials.authenticator.StormpathAuthenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * This is {@link StormpathAuthenticationHandler} that verifies accounts
 * against Stormpath Cloud.
 *
 * @author Misagh Moayyed
 * @since 4.2.0
 */
@Component("stormpathAuthenticationHandler")
public class StormpathAuthenticationHandler extends UsernamePasswordWrapperAuthenticationHandler {
    @Value("${cas.authn.stormpath.api.key:}")
    private String apiKey;

    @Value("${cas.authn.stormpath.app.id:}")
    private String applicationId;

    @Value("${cas.authn.stormpath.secret.key:}")
    private String secretkey;

    @Autowired(required=false)
    @Qualifier("stormpathPac4jPasswordEncoder")
    private org.pac4j.http.credentials.password.PasswordEncoder stormpathPasswordEncoder = new NopPasswordEncoder();

    @Autowired(required = false)
    @Override
    public void setPasswordEncoder(@Qualifier("stormpathPasswordEncoder")
                                   final PasswordEncoder passwordEncoder) {
        if (passwordEncoder != null) {
            super.setPasswordEncoder(passwordEncoder);
        }
    }

    @Autowired(required=false)
    @Override
    public void setPrincipalNameTransformer(@Qualifier("stormpathPrincipalNameTransformer")
                                            final PrincipalNameTransformer principalNameTransformer) {
        if (principalNameTransformer != null) {
            super.setPrincipalNameTransformer(principalNameTransformer);
        }
    }

    @Override
    protected Authenticator getAuthenticator(final Credential credential) {
        final StormpathAuthenticator authenticator = new StormpathAuthenticator(this.apiKey, this.secretkey, this.applicationId);
        authenticator.setPasswordEncoder(this.stormpathPasswordEncoder);
        return authenticator;
    }
}


text:
package moe.nightfall.instrumentality.editor

;

import java.awt._
import java.awt.image.BufferedImage

import moe.nightfall.instrumentality.Loader
import org.lwjgl.opengl.GL11
import org.lwjgl.util.vector.Vector2f;

/**
 * Does AWT-based font drawing.
 * Note that it is *SLOW*!!!
 * Created on 03/09/15.
 */
object UISystemFont {
    // We're /NOT/ uploading this to the GPU every frame just to copy it back down again as a UI draw.
    private val textTextures = scala.collection.mutable.HashMap[String, TextTexture]()
    // Sizes!
    private val textSizes = scala.collection.mutable.HashMap[String, (Vector2f, Vector2f, Double)]()

    // Used to avoid textTextures getting too big
    // (this is a ring, freeTextPtr goes around the ring as textures are alloc'd,
    //  when it runs into old text, it deletes it)
    private val freeTextRing = new Array[String](256)
    private var freeTextPtr = 0

    // Scratch buffer for font rendering (To measure how big the rendered text will be, we have to measure it first.)
    private val bi = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY)
    private val fontTestRender = bi.getGraphics()

    /**
     * Private since this should NEVER be called when we can safely use the "nice" text.
     * We don't want to discriminate against other languages, but we don't want to bludgeon appearance
     * (and potentially compatibility - I consider font rendering a black box, you put text in and you get pixels out)
     * because of (language) support, for better or worse.
     * The vertical size of one line should be 9u(opengl units) - the horizontal size is UNBOUNDED!
     *
     * @param str The text you want to display.
     * @return The resulting size.
     */
    def drawSystemLine(str: String, targetFont: Font): Vector2f = {
        GL11.glEnable(GL11.GL_TEXTURE_2D)
        var tex: TextTexture = null
        if (textTextures.contains(str)) {
            tex = textTextures.get(str).get
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex.tex)
        } else {
            if (freeTextRing(freeTextPtr) != null) {
                tex = textTextures.get(freeTextRing(freeTextPtr)).get
                textTextures.remove(freeTextRing(freeTextPtr))
                // reuse the texture object and hope for the best
            } else {
                tex = new TextTexture()
                tex.tex = GL11.glGenTextures()
            }
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex.tex)
            textTextures.put(str, tex)
            freeTextRing(freeTextPtr) = str
            freeTextPtr += 1
            freeTextPtr = freeTextPtr % freeTextRing.length
            if (freeTextPtr == 0)
                System.out.println("Cache ring runover")
            // Work out what we need
            val neededSize = sizeSystemLine(str, targetFont)
            val mainImage = new BufferedImage(neededSize._1.x.toInt, neededSize._1.y.toInt, BufferedImage.TYPE_INT_ARGB)
            val g = mainImage.createGraphics()
            g.setFont(targetFont)
            g.setColor(Color.BLACK)
            g.drawString(str, -neededSize._2.x.toInt, -neededSize._2.y.toInt)
            g.dispose()
            Loader.writeGLTexImg(mainImage, GL11.GL_LINEAR)
            tex.w = mainImage.getWidth()
            tex.h = mainImage.getHeight()

            tex.scale = neededSize._3
        }
        GL11.glEnable(GL11.GL_BLEND)
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA)
        GL11.glBegin(GL11.GL_QUADS)
        GL11.glColor3d(1, 1, 1)

        GL11.glTexCoord2d(0, 0)
        GL11.glVertex3d(0, 0, 0)

        GL11.glTexCoord2d(0, 1)
        GL11.glVertex3d(0, tex.h * tex.scale, 0)

        GL11.glTexCoord2d(1, 1)
        GL11.glVertex3d(tex.w * tex.scale, tex.h * tex.scale, 0)

        GL11.glTexCoord2d(1, 0)
        GL11.glVertex3d(tex.w * tex.scale, 0, 0)

        GL11.glEnd()
        GL11.glDisable(GL11.GL_BLEND)
        GL11.glDisable(GL11.GL_TEXTURE_2D)
        return new Vector2f((tex.w * tex.scale).toFloat, (tex.h * tex.scale).toFloat)
    }

    // The Vector2f is the size in pixels, the second v2f is the offset in pixels, the double is the scale relative to the original size.
    // (The second v2f can be ignored outside of here,
    // but if you *want* to draw your text with the offsets, then feel free to.)
    // To get the size in GL units, just multiply the first v2f by the scale.
    def sizeSystemLine(str: String, targetFont: Font): (Vector2f, Vector2f, Double) = {
        if (textSizes.contains(str))
            return textSizes(str)
        fontTestRender.setFont(targetFont)
        val fm = fontTestRender.getFontMetrics
        // Work out what we need
        val neededSize = fm.getStringBounds(str, fontTestRender)
        val scale = 9d / fm.getHeight
        val s = (new Vector2f(neededSize.getWidth.toFloat + 1, neededSize.getHeight.toFloat + 1), new Vector2f(neededSize.getX.toFloat, neededSize.getY.toFloat), scale)
        textSizes(str) = s
        s
    }

    /**
     * Fonts are lazy-loaded, causing HUGE amounts of lag for the poor user.
     * This triggers some functions to try and get the font to be loaded... on a different thread!
     */
    def scratchFont(f: Font) {
        fontTestRender.setFont(f)
        val fm = fontTestRender.getFontMetrics()
        fm.getStringBounds("ATTEMPT TO CAUSE LAG ON A DIFFERENT THREAD", fontTestRender)
        fontTestRender.drawString("Carried away by a moonlight shadow...", 0, 0)
    }

    private class TextTexture {
        var tex, w, h: Int = _
        var scale: Double = _ // scale needed to adjust w/h into normal units
    }

}


text:
Revision History

| **Date** | **Version** | **Description** | **Author** |
| --- | --- | --- | --- |
| 29.11.2017| 1.0.0 | Initial Version | Nikolas Traut |
|   |   |   |   |
|   |   |   |   |
|   |   |   |   |

Table of Contents

| 1.        Attack Obstacle    |
| --- |
|         Brief Description        |
| 2.        Flow of Events        |
|         Basic Flow        |
|         Alternative Flows        |
| 2.2.1        Player does not destroy obstacle       |
| 3.        Special Requirements        |
| 4.        Preconditions        |
| 4.4.1     Player must be near obstacle |
| 4.4.2 Player must be able to attack |
| 5.        Postconditions        |
| 6.        Extension Points        |

[The following template is provided for a Use-Case Specification, which contains the textual properties of the use case. This document is used with a requirements management tool, such as Rational RequisitePro, for specifying and marking the requirements within the use-case properties.

The use-case diagrams can be developed in a visual modeling tool, such as Rational Rose. A use-case report, with all properties, may be generated with Rational SoDA. For more information, see the tool mentors in the Rational Unified Process.]

## 1. Attack Obstacle

### 1.1 Brief Description

This use case describes how the game handles a attack on an obstacle.

(Before Attack)

(After Attack)

The damage depends on the weapon used. In this case, the basic attack dealt 1 damage to the obstacle

## 2. Flow of Events
### 2.1 Basic Flow

### 2.2 Alternative Flows
#### 2.2.1 Player does not destroy obstacle

The player attacks the obstacle not enough times to reduce its HP to 0. In this case, the obstacle is not destroyed.
The damage the obstacle has taken is saved.

## 3. Special Requirements

n/a

## 4. Preconditions

### 4.1 Player must be near obstacle

The player must be near the obstacle they are trying to attack. The obstacle has to be in the range of the weapon or the spell
the player is using to attack the obstacle.

### 4.2 Player is able to attack

In Order to attack an obstacle, the player needs to have a way of attacking. This can be a weapon or a damaging spell.

## 5. Postconditions

n/a

## 6. Extension Points

n/a


text:
export interface IVpcResource {
  created_at: string;
  name: string;
  urn: string;
}


text:
layout: page
title: Resume
---

Education

 Interactive Telecommunications Program, New York University, New York, New York, 2016

Master of Professional Studies, Interactive Technology & Design

Skidmore College, Saratoga Springs, New York, 2012

Bachelor of Science, Computer Science & Studio Art

Experience

Model Maker & Production Technician, Normal, New York, New York, August 2014 - Present

Original team member, worked on design and manufacturing of 3D-printed, custom-fit earphones.

Optimized logistics for mass production, including part-tracking and shipping.

Refined manufacturing processes and produced measurable improvements in production time.

Junior UI/UX Designer, LightSail Education, New York, New York, April 2014 - June 2014

Created digital assets and designed UI/UX for an interactive, tablet-based literacy education platform for grades K-12, providing continuous data on student reading habits and comprehension.

LightSail software is presently used by tens of thousands of students and has been recognized by the Bill & Melinda Gates Foundation.

QA Engineering Intern, Fuzz Productions, New York, New York, March 2014 - April 2014

Creating test strategies, developing and implementing automated test scripts, and manually testing multiple apps and websites in an Agile environment.

Client projects included Android and iOS apps for the New York Post and WeightTraining.com.

Editorial Assistant, McMurry/TMG, New York, New York, May 2012 - Sept. 2013

Creative team support member, reporting to VP of Content.

Versatile responsibilities across content division, including editorial, design, and administrative roles.

Copywriting, copy editing and InDesign composition of print and digital materials for national brands.

Managed invoicing and contracting with external vendors and talent.

Editor-in-Chief, Artistic Director, Webmaster, The Skidmore News, Sept. 2008 - May 2012

Consistently met weekly and daily deadlines while publishing print and digital content.

Managed staff of approximately 20, and interfaced with senior college leadership.

Over four years, trained and mentored more than 30 students in journalism, editing and design.

Rebranded entire publication including visual design of print and web editions.

Master Carpenter, Skidmore College Theater Department, Dec. 2008 - May 2012

Trained and supervised student volunteers in tool usage and shop procedure.

Managed projects and crews for four large scale productions each year.

Communication Design Teaching Assistant, Skidmore College Art Department, Sept. 2011 - May 2012

Tutored students in principles of design, composition and typography.

Trained students to use Adobe Creative Suite and Extensis Suitcase Fusion.

Sports Copy Editor, The Saratogian, Saratoga Springs, New York, Summer 2010, 2011

Copy edited and composed up to four pages during production of daily newspaper.

Contributed to coverage of national sporting events including the Travers Stakes.

Carpenter, Opera Saratoga, Saratoga Springs, New York, Summer 2009, 2010

Junior Carpenter, Asher Nichols and Craftsmen, Chestnut Hill, Massachusetts, Summer 2009

Counselor, French Woods Festival of the Performing Arts, Hancock, New York, Summer 2007, 2008

Skills

Programming Languages: Java // Processing // HTML5 // CSS3 // Arduino // JavaScript // Python

Software: Adobe Photoshop, InDesign, Illustrator, Premier // Autodesk Maya, Mudbox, AutoCAD // Rhinoceros // SketchUp // EagleCAD // Microsoft Office // Git

Fabrication: Additive Manufacting 3D Printing // Laser Cutting // CNC Milling // Woodworking // Metalworking & Foundry // Circuit Design & Prototyping // Welding // Mold Making

Editorial: Typography // Print & Digital Publishing // Copy Editing

Awards

Red Burns Scholarship, Tisch School of the Arts, July 2015

SGA Student Leadership Award, Skidmore College, May 2012

Student Opportunity Project Fund, Skidmore College, Feb. 2012

Creative Thought Matters Photography Contest, 1st Place, Skidmore College, Nov. 2011

Jeffrey and Cynthia Treuhaft Fund For Art Technology, Skidmore College, Nov. 2011


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

/// <summary>
/// 只有多个canvas的排序
/// 如果设置Canvas的Sort Order属性,只能设置int值
/// </summary>
public class SortInMuiltCanvas : MonoBehaviour
{
    public Button BtnSort;
    public Canvas CanvasWhite;
    public Canvas CanvasRed;
    public Canvas CanvasBlue;

    //http://blog.csdn.net/akailee/article/details/51798288 会增加Canvas
    //http://forum.china.unity3d.com/thread-1572-1-1.html 修改SortLayer

    // Use this for initialization
    void Start()
    {
        BtnSort.onClick.AddListener(OnSort);
    }

    void OnSort()
    {
        CanvasBlue.sortingOrder = -1;
    }
}


text:
/* exported error_explanations */

var error_explanations = {
  'E009': 'http://jslinterrors.com/option-validthis-cant-be-used-in-a-global-scope/',
  'E010': 'http://jslinterrors.com/with-is-not-allowed-in-strict-mode/',
  'E011': 'http://jslinterrors.com/const-a-has-already-been-declared/',
  'E013': 'http://jslinterrors.com/attempting-to-override-a-which-is-a-constant/',
  'E014': 'http://jslinterrors.com/a-regular-expression-literal-can-be-confused-with/',
  'E015': 'http://jslinterrors.com/unclosed-regular-expression/',
  'E017': 'http://jslinterrors.com/unclosed-comment/',
  'E029': 'http://jslinterrors.com/unclosed-string/',
  'E039': 'http://jslinterrors.com/function-statements-are-not-invocable/',
  'E042': 'http://jslinterrors.com/stopping/',
  'I003': 'http://jslinterrors.com/es5-option-is-now-set-per-default/',
  'W008': 'http://jslinterrors.com/a-leading-decimal-point-can-be-confused-with-a-dot-a/',
  'W009': 'http://jslinterrors.com/the-array-literal-notation-is-preferrable/',
  'W010': 'http://jslinterrors.com/the-object-literal-notation-is-preferrable/',
  'W019': 'http://jslinterrors.com/use-the-isnan-function-to-compare-with-nan/',
  'W020': 'http://jslinterrors.com/read-only/',
  'W022': 'http://jslinterrors.com/do-not-assign-to-the-exception-parameter/',
  'W024': 'http://jslinterrors.com/expected-an-identifier-and-instead-saw-a-a-reserved-word/',
  'W025': 'http://jslinterrors.com/missing-name-in-function-statement/',
  'W031': 'http://jslinterrors.com/do-not-use-new-for-side-effects/',
  'W032': 'http://jslinterrors.com/unnecessary-semicolon/',
  'W037': 'http://jslinterrors.com/a-is-a-statement-label/',
  'W051': 'http://jslinterrors.com/only-properties-should-be-deleted/',
  'W053': 'http://jslinterrors.com/do-not-use-a-as-a-constructor/',
  'W054': 'http://jslinterrors.com/the-function-constructor-is-eval/',
  'W055': 'http://jslinterrors.com/a-constructor-name-should-start-with-an-uppercase-letter/',
  'W058': 'http://jslinterrors.com/missing-invoking-a-constructor/',
  'W061': 'http://jslinterrors.com/eval-is-evil/',
  'W062': 'http://jslinterrors.com/wrap-an-immediate-function-invocation-in-parentheses/',
  'W063': 'http://jslinterrors.com/a-is-not-a-function/',
  'W065': 'http://jslinterrors.com/missing-radix-parameter/',
  'W066': 'http://jslinterrors.com/implied-eval-is-evil-pass-a-function-instead-of-a-string/',
  'W068': 'http://jslinterrors.com/do-not-wrap-function-literals-in-parens/',
  'W069': 'http://jslinterrors.com/a-is-better-written-in-dot-notation/',
  'W070': 'http://jslinterrors.com/extra-comma/',
  'W072': 'http://jslinterrors.com/this-function-has-too-many-parameters/',
  'W075': 'http://jslinterrors.com/duplicate-key-a/',
  'W076': 'http://jslinterrors.com/unexpected-parameter-a-in-get-b-function/',
  'W079': 'http://jslinterrors.com/redefinition-of-a/',
  'W080': 'http://jslinterrors.com/it-is-not-necessary-to-initialize-a-to-undefined/',
  'W082': 'http://jslinterrors.com/function-statements-should-not-be-placed-in-blocks/',
  'W083': 'http://jslinterrors.com/dont-make-functions-within-a-loop/',
  'W084': 'http://jslinterrors.com/unexpected-assignment-expression/',
  'W085': 'http://jslinterrors.com/unexpected-with/',
  'W087': 'http://jslinterrors.com/all-debugger-statements-should-be-removed/',
  'W089': 'http://jslinterrors.com/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement/',
  'W090': 'http://jslinterrors.com/a-is-not-a-label/',
  'W093': 'http://jslinterrors.com/did-you-mean-to-return-a-conditional/',
  'W098': 'http://jslinterrors.com/unused-a/',
  'W105': 'http://jslinterrors.com/unexpected-dangling-_-in-a/',
  'W108': 'http://jslinterrors.com/strings-must-use-singlequote/',
  'W109': 'http://jslinterrors.com/strings-must-use-singlequote/',
  'W110': 'http://jslinterrors.com/mixed-double-and-single-quotes/',
  'W115': 'http://jslinterrors.com/dont-use-octal-a-use-instead/',
  'W117': 'http://jslinterrors.com/a-was-used-before-it-was-defined/',
  'W120': 'http://jslinterrors.com/variable-a-was-not-declared-correctly/'
};


text:
import env from './config/environment';
import TotemEngines from 'totem-engines/engines';

export default new TotemEngines(env).get_app();


text:
Web Tools

Generate thumbnails

Processed images:

<?php
	foreach($processedItems as $item)
	{
		echo $item;
		echo "
";
	}

	echo "
Total # of items: ".sizeof($processedItems);
	echo "
Benchmark time: ".$benchmark_time;
	echo "
Memory usage: ".$this->benchmark->memory_usage();
	echo "
memory_get_usage: ".memory_get_usage();

?>


text:
var EffectsLayer = require('../EffectsLayer');

AdditionalLayerInfo.EffectsLayer['isdw'] =
AdditionalLayerInfo.EffectsLayer['dsdw'];


text:
package me.vilsol.nmswrapper.wraps.unparsed;

import me.vilsol.nmswrapper.reflections.ReflectiveClass;
import me.vilsol.nmswrapper.wraps.NMSWrap;

// TODO Implement
@ReflectiveClass(name = "EnumFlowerType")
public class NMSEnumFlowerType extends NMSWrap {
    public NMSEnumFlowerType(Object nmsObject) {
        super(nmsObject);
    }

    public NMSEnumFlowerType(String nmsName, Object[] paramTypes, Object[] params) {
        super(nmsName, paramTypes, params);
    }
}


text:
package com.bq.corbel.lib.ws.api.error;

import com.bq.corbel.lib.ws.model.Error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

public class ErrorResponseFactory {

	private static final Logger LOG = LoggerFactory.getLogger(ErrorResponseFactory.class);
	private static final int METHOD_NOT_ALLOWED_STATUS = 405;
	private static final int INVALID_ENTITY = 422;
	private static final int RESOURCE_LOCKED = 423;
	private static final int BAD_GATEWAY = 502;

	private static final com.bq.corbel.lib.ws.model.Error DEFAULT_FORBIDDEN_ERROR = new Error("forbidden", ErrorMessage.FORBIDDEN.getMessage());
	private static final Error DEFAULT_UNAUTHORIZED_ERROR = new Error("unauthorized",
			ErrorMessage.UNAUTHORIZE.getMessage());
	private static final Error DEFAULT_METHOD_NOT_ALLOWED_ERROR = new Error("method_not_allowed",
			ErrorMessage.NOT_ALLOWED.getMessage());
	private static final Error DEFAULT_CONFLICT_ERROR = new Error("conflict", ErrorMessage.CONFLICT.getMessage());
	private static final Error DEFAULT_NOT_FOUND_ERROR = new Error("not_found", ErrorMessage.NOT_FOUND.getMessage());
	private static final Error DEFAULT_BAD_REQUEST_ERROR = new Error("bad_request",
			ErrorMessage.BAD_REQUEST.getMessage());
	private static final Error GATEWAY_TIMEOUT_ERROR = new Error("gateway_timeout",
			ErrorMessage.GATEWAY_TIMEOUT.getMessage());
	private static final Error DEFAULT_BAD_GATEWAY = new Error("bad_gateway", ErrorMessage.BAD_GATEWAY.getMessage());
	private static ErrorResponseFactory instance;

	public static ErrorResponseFactory getInstance() {
		if (instance == null) {
			LOG.debug("Creating instance of {}", ErrorResponseFactory.class);
			instance = new ErrorResponseFactory();
		}
		return instance;
	}

	protected ErrorResponseFactory() {
	}

	public Response badRequest(ApiRequestException e) {
		return badRequest(e.getError());
	}

	public Response serverError(Throwable exception) {
		return serverError(new Error("internal_server_error", exception.getMessage()));
	}

	public Response badGateway() {
		return badGateway(DEFAULT_BAD_GATEWAY);
	}

	public Response badRequest() {
		return badRequest(DEFAULT_BAD_REQUEST_ERROR);
	}

	public Response gatewayTimeout() {
		return gatewayTimeout(GATEWAY_TIMEOUT_ERROR);
	}

	public Response notFound() {
		return notfound(DEFAULT_NOT_FOUND_ERROR);
	}

	public Response conflict() {
		return conflict(DEFAULT_CONFLICT_ERROR);
	}

    public Response conflict(String message) {
        return conflict(new Error("conflict", message));
    }

	public Response invalidEntity(String description) {
		return invalidEntity(new Error("invalid_entity", ErrorMessage.INVALID_ENTITY.getMessage(description)));
	}

	public Response methodNotAllowed() {
		return methodNotAllowed(DEFAULT_METHOD_NOT_ALLOWED_ERROR);
	}

	public Response unauthorized() {
		return unauthorized(DEFAULT_UNAUTHORIZED_ERROR);
	}

	public Response unauthorized(String message) {
		return unauthorized(new Error("unauthorized", message));
	}

    public Response unauthorized(String error, String errorDescription){
        return unauthorized(new Error(error, errorDescription));
    }

	public Response preconditionFailed(String description) {
		return jsonResponse(new Error("precondition_failed", ErrorMessage.PRECONDITION_FAILED.getMessage(description)),
                Status.PRECONDITION_FAILED);
	}

	public Response forbidden() {
		return forbidden(DEFAULT_FORBIDDEN_ERROR);
	}

	public Response badRequest(Error error) {
		return jsonResponse(error, Status.BAD_REQUEST);
	}

	public Response gatewayTimeout(Error error) {
		return jsonResponse(error, Status.GATEWAY_TIMEOUT);
	}

	public Response notfound(Error error) {
		return jsonResponse(error, Status.NOT_FOUND);
	}

	public Response conflict(Error error) {
		return jsonResponse(error, Status.CONFLICT);
	}

	public Response invalidEntity(Error error) {
		return jsonResponse(error, INVALID_ENTITY);
	}

	public Response methodNotAllowed(Error error) {
		return jsonResponse(error, METHOD_NOT_ALLOWED_STATUS);
	}

	public Response missingParameter(String parameter) {
		return badRequest(new Error("missing_parameter", parameter));
	}

	public Response unauthorized(Error error) {
		return jsonResponse(error, Status.UNAUTHORIZED);
	}

	public Response forbidden(Error error) {
		return jsonResponse(error, Status.FORBIDDEN);
	}

	public Response resourceLocked(Error error) {
		return jsonResponse(error, RESOURCE_LOCKED);
	}

	public Response serverError(Error error) {
		return jsonResponse(error, Status.INTERNAL_SERVER_ERROR);
	}

	public Response badGateway(Error error) {
		return jsonResponse(error, BAD_GATEWAY);
	}

	private Response jsonResponse(Error error, Status status) {
		return jsonResponse(error, status.getStatusCode());
	}

	private Response jsonResponse(Error error, int status) {
		return Response.status(status).entity(error).type(MediaType.APPLICATION_JSON_TYPE).build();
	}

}


text:
pymatgen.analysis package
=========================

Subpackages
-----------

.. toctree::

    pymatgen.analysis.chemenv
    pymatgen.analysis.cost
    pymatgen.analysis.defects
    pymatgen.analysis.diffraction
    pymatgen.analysis.elasticity
    pymatgen.analysis.hhi
    pymatgen.analysis.magnetism
    pymatgen.analysis.pourbaix
    pymatgen.analysis.structure_prediction

Submodules
----------

.. toctree::

   pymatgen.analysis.adsorption
   pymatgen.analysis.bond_valence
   pymatgen.analysis.diffusion_analyzer
   pymatgen.analysis.energy_models
   pymatgen.analysis.eos
   pymatgen.analysis.ewald
   pymatgen.analysis.graphs
   pymatgen.analysis.interface_reactions
   pymatgen.analysis.local_env
   pymatgen.analysis.molecule_matcher
   pymatgen.analysis.molecule_structure_comparator
   pymatgen.analysis.nmr
   pymatgen.analysis.path_finder
   pymatgen.analysis.phase_diagram
   pymatgen.analysis.piezo
   pymatgen.analysis.quasiharmonic
   pymatgen.analysis.reaction_calculator
   pymatgen.analysis.structure_analyzer
   pymatgen.analysis.structure_matcher
   pymatgen.analysis.substrate_analyzer
   pymatgen.analysis.surface_analysis
   pymatgen.analysis.thermochemistry
   pymatgen.analysis.transition_state
   pymatgen.analysis.wulff

Module contents
---------------

.. automodule:: pymatgen.analysis
    :members:
    :undoc-members:
    :show-inheritance:


text:
"""Tests for tensorflow.python.training.saver.py."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import contextlib
import os
import shutil
import tempfile

from google.protobuf import text_format

from tensorflow.core.protobuf import saver_pb2
from tensorflow.python.framework import ops as ops_lib
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import saver as saver_module
from tensorflow.python.training.checkpoint_state_pb2 import CheckpointState

class LatestCheckpointWithRelativePaths(test.TestCase):

  @staticmethod
  @contextlib.contextmanager
  def tempWorkingDir(temppath):
    cwd = os.getcwd()
    os.chdir(temppath)
    try:
      yield
    finally:
      os.chdir(cwd)

  @staticmethod
  @contextlib.contextmanager
  def tempDir():
    tempdir = tempfile.mkdtemp()
    try:
      yield tempdir
    finally:
      shutil.rmtree(tempdir)

  def testNameCollision(self):
    # Make sure we have a clean directory to work in.
    with self.tempDir() as tempdir:
      # Jump to that directory until this test is done.
      with self.tempWorkingDir(tempdir):
        # Save training snapshots to a relative path.
        traindir = "train/"
        os.mkdir(traindir)
        # Collides with the default name of the checkpoint state file.
        filepath = os.path.join(traindir, "checkpoint")

        with self.test_session() as sess:
          unused_a = variables.Variable(0.0)  # So that Saver saves something.
          variables.global_variables_initializer().run()

          # Should fail.
          saver = saver_module.Saver(sharded=False)
          with self.assertRaisesRegexp(ValueError, "collides with"):
            saver.save(sess, filepath)

          # Succeeds: the file will be named "checkpoint-<step>".
          saver.save(sess, filepath, global_step=1)
          self.assertIsNotNone(
              checkpoint_management.latest_checkpoint(traindir))

          # Succeeds: the file will be named "checkpoint-<i>-of-<n>".
          saver = saver_module.Saver(sharded=True)
          saver.save(sess, filepath)
          self.assertIsNotNone(
              checkpoint_management.latest_checkpoint(traindir))

          # Succeeds: the file will be named "checkpoint-<step>-<i>-of-<n>".
          saver = saver_module.Saver(sharded=True)
          saver.save(sess, filepath, global_step=1)
          self.assertIsNotNone(
              checkpoint_management.latest_checkpoint(traindir))

  def testRelativePath(self):
    # Make sure we have a clean directory to work in.
    with self.tempDir() as tempdir:

      # Jump to that directory until this test is done.
      with self.tempWorkingDir(tempdir):

        # Save training snapshots to a relative path.
        traindir = "train/"
        os.mkdir(traindir)

        filename = "snapshot"
        filepath = os.path.join(traindir, filename)

        with self.test_session() as sess:
          # Build a simple graph.
          v0 = variables.Variable(0.0)
          inc = v0.assign_add(1.0)

          save = saver_module.Saver({"v0": v0})

          # Record a short training history.
          variables.global_variables_initializer().run()
          save.save(sess, filepath, global_step=0)
          inc.eval()
          save.save(sess, filepath, global_step=1)
          inc.eval()
          save.save(sess, filepath, global_step=2)

        with self.test_session() as sess:
          # Build a new graph with different initialization.
          v0 = variables.Variable(-1.0)

          # Create a new saver.
          save = saver_module.Saver({"v0": v0})
          variables.global_variables_initializer().run()

          # Get the most recent checkpoint name from the training history file.
          name = checkpoint_management.latest_checkpoint(traindir)
          self.assertIsNotNone(name)

          # Restore "v0" from that checkpoint.
          save.restore(sess, name)
          self.assertEqual(v0.eval(), 2.0)

class CheckpointStateTest(test.TestCase):

  def _get_test_dir(self, dirname):
    test_dir = os.path.join(self.get_temp_dir(), dirname)
    gfile.MakeDirs(test_dir)
    return test_dir

  def testAbsPath(self):
    save_dir = self._get_test_dir("abs_paths")
    abs_path = os.path.join(save_dir, "model-0")
    ckpt = checkpoint_management.generate_checkpoint_state_proto(
        save_dir, abs_path)
    self.assertEqual(ckpt.model_checkpoint_path, abs_path)
    self.assertTrue(os.path.isabs(ckpt.model_checkpoint_path))
    self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1)
    self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path)

  def testRelPath(self):
    train_dir = "train"
    model = os.path.join(train_dir, "model-0")
    # model_checkpoint_path should have no "train" directory part.
    new_rel_path = "model-0"
    ckpt = checkpoint_management.generate_checkpoint_state_proto(
        train_dir, model)
    self.assertEqual(ckpt.model_checkpoint_path, new_rel_path)
    self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1)
    self.assertEqual(ckpt.all_model_checkpoint_paths[-1], new_rel_path)

  def testAllModelCheckpointPaths(self):
    save_dir = self._get_test_dir("all_models_test")
    abs_path = os.path.join(save_dir, "model-0")
    for paths in [None, [], ["model-2"]]:
      ckpt = checkpoint_management.generate_checkpoint_state_proto(
          save_dir, abs_path, all_model_checkpoint_paths=paths)
      self.assertEqual(ckpt.model_checkpoint_path, abs_path)
      self.assertTrue(os.path.isabs(ckpt.model_checkpoint_path))
      self.assertEqual(
          len(ckpt.all_model_checkpoint_paths), len(paths) if paths else 1)
      self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path)

  def testUpdateCheckpointState(self):
    save_dir = self._get_test_dir("update_checkpoint_state")
    os.chdir(save_dir)
    # Make a temporary train directory.
    train_dir = "train"
    os.mkdir(train_dir)
    abs_path = os.path.join(save_dir, "model-0")
    rel_path = os.path.join("train", "model-2")
    checkpoint_management.update_checkpoint_state(
        train_dir, rel_path, all_model_checkpoint_paths=[abs_path, rel_path])
    ckpt = checkpoint_management.get_checkpoint_state(train_dir)
    self.assertEqual(ckpt.model_checkpoint_path, rel_path)
    self.assertEqual(len(ckpt.all_model_checkpoint_paths), 2)
    self.assertEqual(ckpt.all_model_checkpoint_paths[-1], rel_path)
    self.assertEqual(ckpt.all_model_checkpoint_paths[0], abs_path)

  def testUpdateCheckpointStateSaveRelativePaths(self):
    save_dir = self._get_test_dir("update_checkpoint_state")
    os.chdir(save_dir)
    abs_path2 = os.path.join(save_dir, "model-2")
    rel_path2 = "model-2"
    abs_path0 = os.path.join(save_dir, "model-0")
    rel_path0 = "model-0"
    checkpoint_management.update_checkpoint_state_internal(
        save_dir=save_dir,
        model_checkpoint_path=abs_path2,
        all_model_checkpoint_paths=[rel_path0, abs_path2],
        save_relative_paths=True)

    # File should contain relative paths.
    file_content = file_io.read_file_to_string(
        os.path.join(save_dir, "checkpoint"))
    ckpt = CheckpointState()
    text_format.Merge(file_content, ckpt)
    self.assertEqual(ckpt.model_checkpoint_path, rel_path2)
    self.assertEqual(len(ckpt.all_model_checkpoint_paths), 2)
    self.assertEqual(ckpt.all_model_checkpoint_paths[-1], rel_path2)
    self.assertEqual(ckpt.all_model_checkpoint_paths[0], rel_path0)

    # get_checkpoint_state should return absolute paths.
    ckpt = checkpoint_management.get_checkpoint_state(save_dir)
    self.assertEqual(ckpt.model_checkpoint_path, abs_path2)
    self.assertEqual(len(ckpt.all_model_checkpoint_paths), 2)
    self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path2)
    self.assertEqual(ckpt.all_model_checkpoint_paths[0], abs_path0)

  def testCheckPointStateFailsWhenIncomplete(self):
    save_dir = self._get_test_dir("checkpoint_state_fails_when_incomplete")
    os.chdir(save_dir)
    ckpt_path = os.path.join(save_dir, "checkpoint")
    ckpt_file = open(ckpt_path, "w")
    ckpt_file.write("")
    ckpt_file.close()
    with self.assertRaises(ValueError):
      checkpoint_management.get_checkpoint_state(save_dir)

  def testCheckPointCompletesRelativePaths(self):
    save_dir = self._get_test_dir("checkpoint_completes_relative_paths")
    os.chdir(save_dir)
    ckpt_path = os.path.join(save_dir, "checkpoint")
    ckpt_file = open(ckpt_path, "w")
    ckpt_file.write("""
        model_checkpoint_path: "./model.ckpt-687529"
        all_model_checkpoint_paths: "./model.ckpt-687500"
        all_model_checkpoint_paths: "./model.ckpt-687529"
        """)
    ckpt_file.close()
    ckpt = checkpoint_management.get_checkpoint_state(save_dir)
    self.assertEqual(ckpt.model_checkpoint_path,
                     os.path.join(save_dir, "./model.ckpt-687529"))
    self.assertEqual(ckpt.all_model_checkpoint_paths[0],
                     os.path.join(save_dir, "./model.ckpt-687500"))
    self.assertEqual(ckpt.all_model_checkpoint_paths[1],
                     os.path.join(save_dir, "./model.ckpt-687529"))

class SaverUtilsTest(test.TestCase):

  def setUp(self):
    self._base_dir = os.path.join(self.get_temp_dir(), "saver_utils_test")
    gfile.MakeDirs(self._base_dir)

  def tearDown(self):
    gfile.DeleteRecursively(self._base_dir)

  def testCheckpointExists(self):
    for sharded in (False, True):
      for version in (saver_pb2.SaverDef.V2, saver_pb2.SaverDef.V1):
        with self.test_session(graph=ops_lib.Graph()) as sess:
          unused_v = variables.Variable(1.0, name="v")
          variables.global_variables_initializer().run()
          saver = saver_module.Saver(sharded=sharded, write_version=version)

          path = os.path.join(self._base_dir, "%s-%s" % (sharded, version))
          self.assertFalse(
              checkpoint_management.checkpoint_exists(path))  # Not saved yet.

          ckpt_prefix = saver.save(sess, path)
          self.assertTrue(checkpoint_management.checkpoint_exists(ckpt_prefix))

          ckpt_prefix = checkpoint_management.latest_checkpoint(self._base_dir)
          self.assertTrue(checkpoint_management.checkpoint_exists(ckpt_prefix))

  def testGetCheckpointMtimes(self):
    prefixes = []
    for version in (saver_pb2.SaverDef.V2, saver_pb2.SaverDef.V1):
      with self.test_session(graph=ops_lib.Graph()) as sess:
        unused_v = variables.Variable(1.0, name="v")
        variables.global_variables_initializer().run()
        saver = saver_module.Saver(write_version=version)
        prefixes.append(
            saver.save(sess, os.path.join(self._base_dir, str(version))))

    mtimes = checkpoint_management.get_checkpoint_mtimes(prefixes)
    self.assertEqual(2, len(mtimes))
    self.assertTrue(mtimes[1] >= mtimes[0])

  def testRemoveCheckpoint(self):
    for sharded in (False, True):
      for version in (saver_pb2.SaverDef.V2, saver_pb2.SaverDef.V1):
        with self.test_session(graph=ops_lib.Graph()) as sess:
          unused_v = variables.Variable(1.0, name="v")
          variables.global_variables_initializer().run()
          saver = saver_module.Saver(sharded=sharded, write_version=version)

          path = os.path.join(self._base_dir, "%s-%s" % (sharded, version))
          ckpt_prefix = saver.save(sess, path)
          self.assertTrue(checkpoint_management.checkpoint_exists(ckpt_prefix))
          checkpoint_management.remove_checkpoint(ckpt_prefix, version)
          self.assertFalse(checkpoint_management.checkpoint_exists(ckpt_prefix))

if __name__ == "__main__":
  test.main()