text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="breakdown2020_init_line_exited">Initiation Line Exited</string>
    <string name="breakdown2020_auto_power_cells">Auto Power Cells</string>
    <string name="breakdown2020_auto_power_cell_points">Auto Power Cell Points</string>
    <string name="breakdown2020_teleop_power_cells">Teleop Power Cells</string>
    <string name="breakdown2020_teleop_power_cell_points">Teleop Power Cell Points</string>
    <string name="breakdown2020_control_panel_points">Control Panel Points</string>
    <string name="breakdown2020_shield_generator_level">Shield Generator Level</string>
    <string name="breakdown2020_endgame_points">Endgame Points</string>
    <string name="breakdown2020_stage_activations">Stage Activations</string>
    <string name="breakdown2020_shield_generator_operational">Shield Generator Operational</string>

    <string name="breakdown2020_avg_init_line_auto">Average Auto Initiation Line Points</string>
    <string name="breakdown2020_avg_cell_points_auto">Average Auto Cell Points</string>
    <string name="breakdown2020_avg_cell_points_teleop">Average Teleop Cell Points</string>
    <string name="breakdown2020_avg_controL_panel_points">Average Control Panel Points</string>
    <string name="breakdown2020_avg_num_hang">Average Number of Robots Hanging</string>
    <string name="breakdown2020_avg_endgame_score">Average Endgame Score</string>

    <string name="breakdown2020_exit_init_line">Initiation Line Exited</string>
    <string name="breakdown2020_stage1_achieved">Stage 1 Achieved</string>
    <string name="breakdown2020_stage2_achieved">Stage 2 Achieved</string>
    <string name="breakdown2020_stage3_achieved">Stage 3 Achieved</string>
    <string name="breakdown2020_robots_parking">Robots Parking</string>
    <string name="breakdown2020_robots_hanging">Robots Hanging</string>
    <string name="breakdown2020_generator_level">Generator Level + Hang</string>
    <string name="breakdown2020_operational_rp">Generator Operational RP Achieved</string>
    <string name="breakdown2020_energized_rp">Generator Energized RP Achieved</string>
</resources>


text:
package com.github.thomasfischl.rayden.api;

public class RaydenExpressionLocator {

  private final String orgLocator;
  private final String evalLocator;

  public RaydenExpressionLocator(String orgLocator, String evalLocator) {
    this.orgLocator = orgLocator;
    this.evalLocator = evalLocator;
  }

  public String getOrgLocator() {
    return orgLocator;
  }

  public String getEvalLocator() {
    return evalLocator;
  }

  @Override
  public String toString() {
    if (evalLocator != null) {
      return orgLocator + "[" + evalLocator + "]";
    } else {
      return orgLocator;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
It is easy to send Zulips on SVN commits, by configuring a
post-commit hook. To do this:

{!create-stream.md!}

Then:

1. {!download-python-bindings.md!}

2. Install `pysvn`. On Linux, you can install the `python-svn`
   package. On other platforms, you can install a binary or from
   source by following the [instructions on the pysvn website][1].

[1]: http://pysvn.tigris.org/project_downloads.html

3. {!change-zulip-config-file.md!}

4. Copy `integrations/svn/zulip_svn_config.py` and
   `integrations/svn/post-commit` from the API bindings directory
   to the `hooks` subdirectory of your SVN repository.

The default stream used by this post-commit hook is `commits`; if
you'd prefer a different stream, change it now in
`zulip_svn_config.py`. Make sure that everyone interested in getting
these post-commit Zulips is subscribed to that stream!

{!congrats.md!}

![SVN commit bot message](/static/images/integrations/svn/001.png)


text:
import { fireEvent, waitFor } from '@testing-library/dom';

import { Address } from '@proton/shared/lib/interfaces';
import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';

import { addApiMock } from '../../../helpers/test/api';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import { addKeysToUserKeysCache } from '../../../helpers/test/crypto';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import { contactID, receiver, sender, setupContactsForPinKeys } from '../../../helpers/test/pinKeys';
import { render, tick } from '../../../helpers/test/render';
import ContactResignModal from './ContactResignModal';

const contacts = [{ contactID: contactID }];
const title = 'Contact Resign Modal title';
const children = 'Contact Resign Modal children';

describe('Contact resign modal', () => {
    beforeAll(async () => {
        await setupCryptoProxyForTesting();
    });

    afterAll(async () => {
        await releaseCryptoProxy();
    });

    const setup = async (hasFingerprint: boolean) => {
        minimalCache();
        addToCache('Addresses', [{ Email: receiver.Address } as Address]);

        const { receiverKeys, senderKeys } = await setupContactsForPinKeys(hasFingerprint);

        addApiMock('keys', () => ({ Keys: [senderKeys] }));
        addApiMock(
            'contacts/v4/contacts/emails',
            () => ({
                ContactEmails: [{ Email: sender.Address, ContactID: contactID } as ContactEmail] as ContactEmail[],
            }),
            'get'
        );

        const updateSpy = jest.fn();
        addApiMock(`contacts/v4/contacts/${contactID}`, updateSpy, 'put');

        addKeysToUserKeysCache(receiverKeys);

        const onResignSpy = jest.fn();

        const container = await render(
            <ContactResignModal title={title} contacts={contacts} onResign={onResignSpy} open>
                {children}
            </ContactResignModal>,
            false
        );

        return { container, senderKeys, updateSpy, onResignSpy };
    };

    it('should resign the contact and render email rows', async () => {
        const {
            container: { getByText, getByTestId },
            senderKeys,
            updateSpy,
            onResignSpy,
        } = await setup(true);

        // Modal and content are displayed
        getByText(title);
        getByText(children);

        // Email rows are rendered (Email + fingerprints)
        await waitFor(() => getByText(`${sender.Address}:`));
        const expectedFingerPrint = senderKeys.publicKeys[0].getFingerprint();
        getByText(expectedFingerPrint);

        // Click on Re-sign button
        const resignButton = getByTestId('resign-contact');
        fireEvent.click(resignButton);
        await tick();

        // Contact update is called
        expect(updateSpy).toHaveBeenCalled();

        // Optional on Resign action is called
        expect(onResignSpy).toHaveBeenCalled();
    });

    it('should resign the contact not render email rows', async () => {
        const {
            container: { getByText, queryByText, getByTestId },
            updateSpy,
            onResignSpy,
        } = await setup(false);

        // Modal and content are displayed
        getByText(title);
        getByText(children);

        // Email rows are not rendered
        const emailRow = queryByText(`${sender.Address}:`);
        expect(emailRow).toBeNull();

        // Click on Re-sign button
        const resignButton = getByTestId('resign-contact');
        fireEvent.click(resignButton);
        await tick();

        // Contact update is called
        expect(updateSpy).toHaveBeenCalled();

        // Optional on Resign action is called
        expect(onResignSpy).toHaveBeenCalled();
    });
});


text:
package org.appng.core.service;

public class SiteLoadingException extends RuntimeException {

	public SiteLoadingException(String message, Throwable cause) {
		super(message, cause);
	}

}


text:
layout: model
title: French CamembertForTokenClassification Cased model (from Jean-Baptiste)
author: John Snow Labs
name: camembert_classifier_ner_with_dates
date: 2022-09-25
tags: [camembert, ner, open_source, fr]
task: Named Entity Recognition
language: fr
edition: Spark NLP 4.2.0
spark_version: 3.0
supported: true
annotator: CamemBertForTokenClassification
article_header:
  type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Pretrained CamembertForTokenClassification model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP. `camembert-ner-with-dates` is a French model originally trained by `Jean-Baptiste`.

## Predicted Entities

`DATE`, `LOC`, `ORG`, `PER`, `MISC`

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/camembert_classifier_ner_with_dates_fr_4.2.0_3.0_1664084178555.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
documentAssembler = DocumentAssembler() \
        .setInputCol("text") \
        .setOutputCol("document")

sentenceDetector = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")\
.setInputCols(["document"])\
.setOutputCol("sentence")

tokenizer = Tokenizer() \
    .setInputCols("sentence") \
    .setOutputCol("token")

sequenceClassifier_loaded = CamemBertForTokenClassification.pretrained("camembert_classifier_ner_with_dates","fr") \
    .setInputCols(["sentence", "token"]) \
    .setOutputCol("ner")

pipeline = Pipeline(stages=[documentAssembler,sentenceDetector,tokenizer,sequenceClassifier_loaded])

data = spark.createDataFrame([["J'adore Spark NLP"]]).toDF("text")

result = pipeline.fit(data).transform(data)
```
```scala
val documentAssembler = new DocumentAssembler()
          .setInputCol("text")
          .setOutputCol("document")

val sentenceDetector = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")
       .setInputCols(Array("document"))
       .setOutputCol("sentence")

val tokenizer = new Tokenizer()
    .setInputCols(Array("sentence"))
    .setOutputCol("token")

val sequenceClassifier_loaded = CamemBertForTokenClassification.pretrained("camembert_classifier_ner_with_dates","fr")
    .setInputCols(Array("sentence", "token"))
    .setOutputCol("ner")

val pipeline = new Pipeline().setStages(Array(documentAssembler,sentenceDetector,tokenizer,sequenceClassifier_loaded))

val data = Seq("J'adore Spark NLP").toDF("text")

val result = pipeline.fit(data).transform(data)
```
</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|camembert_classifier_ner_with_dates|
|Compatibility:|Spark NLP 4.2.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[document, token]|
|Output Labels:|[class]|
|Language:|fr|
|Size:|411.4 MB|
|Case sensitive:|true|
|Max sentence length:|256|

## References

- https://huggingface.co/Jean-Baptiste/camembert-ner-with-dates
- https://dateparser.readthedocs.io/en/latest/


text:
package lib.driver.inward.driver_class.prescription;

import java.util.List;

import lib.SessionFactoryUtil;
import lib.classes.CasttingMethods.CastList;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import core.classes.inward.prescription.PrescriptionTerms;
import core.classes.inward.prescription.TempPrescribe;
import core.classes.pharmacy.MstDrugsNew;

public class TempPrescribeDBDrive {
	Session session = SessionFactoryUtil.getSessionFactory().openSession();

	public boolean addNewPrescrptionItem(TempPrescribe term,int drug_id, int term_id) {

		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			MstDrugsNew Drug = (MstDrugsNew) session.get(MstDrugsNew.class, drug_id);
			term.setDrug_id(Drug);

			PrescriptionTerms ter=(PrescriptionTerms) session.get(PrescriptionTerms.class, term_id);
			term.setTerm_id(ter);

			session.save(term);
			tx.commit();
			return true;
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return false;
		}

	}

	public boolean UpdatePrescrptionItem( int auto_id,int dose,String frequency) {
		Transaction tx=null;

				try{
					System.out.println("AGAIN "+auto_id+","+dose+","+frequency);
					tx=session.beginTransaction();

					TempPrescribe adm=new TempPrescribe();
					adm=(TempPrescribe) session.get(TempPrescribe.class,auto_id);

					adm.setDose(dose);
					adm.setFrequency(frequency);
					session.update(adm);

					tx.commit();
					return true;
				}

				catch (RuntimeException ex) {
					if(tx != null && tx.isActive()){
						try{
							tx.rollback();
						}catch(HibernateException he){
							System.err.println("Error rolling back transaction");
						}
						throw ex;
					}
					return false;
				}
			}

	public List<TempPrescribe> getPrescrptionItemsByTermID(int term_id) {
		Transaction tx = null;

		try{
			tx = session.beginTransaction();
			Query query =  session.createQuery("select i from TempPrescribe as i where i.term_id.term_id=:term_id");
			query.setParameter("term_id", term_id);
			List<TempPrescribe> list =CastList.castList(TempPrescribe.class, query.list());
			tx.commit();
			return list;

		}
		catch(RuntimeException ex){
			if(tx != null && tx.isActive())
			{
				try{
					tx.rollback();
				}catch(HibernateException he){
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return null;
		}
	}

	public boolean deleteTempPrescription(TempPrescribe temp)
	{
		Transaction tx=null;

	try {

			tx=session.beginTransaction();
			session.delete(temp);
			tx.commit();
			return true;
		}

	catch (RuntimeException ex) {
		if(tx != null && tx.isActive()){
			try{
				tx.rollback();
			}catch(HibernateException he){
				System.err.println("Error rolling back transaction");
			}
			throw ex;
		}
		return false;
	}

	}

}


text:
namespace aura {
class Window;
}

namespace ash {

class LockScreenActionBackgroundObserver;

// Base class for managing lock screen action background. The implementation
// should provide methods for showing and hiding background when requested.
// The base class keeps track of the background state, and notifies observers
// when the state changes.
class ASH_EXPORT LockScreenActionBackgroundController {
 public:
  // Creates a LockScreenActionBackgroundController instance.
  static std::unique_ptr<LockScreenActionBackgroundController> Create();

  // Method that can be used in tests to change the controller returned by
  // |Create| in tests.
  // Note: this has to be called before root window controller is initialized
  // to have any effect.
  using FactoryCallback = base::RepeatingCallback<
      std::unique_ptr<LockScreenActionBackgroundController>()>;
  static void SetFactoryCallbackForTesting(
      FactoryCallback* testing_factory_callback);

  LockScreenActionBackgroundController();

  LockScreenActionBackgroundController(
      const LockScreenActionBackgroundController&) = delete;
  LockScreenActionBackgroundController& operator=(
      const LockScreenActionBackgroundController&) = delete;

  virtual ~LockScreenActionBackgroundController();

  // Sets the window the background widget should use as its parent.
  void SetParentWindow(aura::Window* parent_window);

  void AddObserver(LockScreenActionBackgroundObserver* observer);
  void RemoveObserver(LockScreenActionBackgroundObserver* observer);

  LockScreenActionBackgroundState state() const { return state_; }

  // Returns whether |window| is a background widget window.
  virtual bool IsBackgroundWindow(aura::Window* window) const = 0;

  // Starts showing background.
  //
  // Returns whether the background state has changed. On success, the state is
  // expected to change to either kShowing, or kShown.
  virtual bool ShowBackground() = 0;

  // Hides background without an animation.
  //
  // Returns whether the background state has changed. On success the state is
  // expected to change to kHidden.
  virtual bool HideBackgroundImmediately() = 0;

  // Starts hiding the background. Unlike |HideBackgroundImediatelly|, hiding
  // the background may be accompanied with an animation, in which case state
  // should be changed to kHiding.
  //
  // Returns whether the background state has changed. On success, the state is
  // expected to change to either kHiding or kHidden.
  virtual bool HideBackground() = 0;

 protected:
  // Method the implementations should use to update the current background
  // state and notify observers of background state changes.
  void UpdateState(LockScreenActionBackgroundState state);

  aura::Window* parent_window_ = nullptr;

 private:
  LockScreenActionBackgroundState state_ =
      LockScreenActionBackgroundState::kHidden;

  base::ObserverList<LockScreenActionBackgroundObserver>::Unchecked observers_;
};

}  // namespace ash

#endif  // ASH_LOCK_SCREEN_ACTION_LOCK_SCREEN_ACTION_BACKGROUND_CONTROLLER_H_


text:
class Farm :
	public Building
{
public:
	Farm ( int, int, std::string );
	virtual ~Farm ();

	int getID () override;
	void effect () override;
	void repair () override;
	void level_up() override;
	std::string getInfo () override;
	std::string getString () override;
	std::pair<int, int> getCoord () override;
	void setCoord ( int, int ) override;
private:
	int n_coins_;
};


text:
package com.gleenn;

import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;

public class AllSumsTest {

    private static final int[] values = new int[]{1, 2, 3, 4, 5, 6, 7, 8};

    @Test
    public void getSums_returnsSumBetweenIndices() {
        AllSums allSums = new AllSums(values);
        Counter counter = new Counter();
        testSums(allSums, counter);
        assertThat(counter.getCount()).isEqualTo(values.length - 1);
    }

    @Test
    public void getSums_returnsSumBetweenIndices_forQuickToo() {
        AllSums allSums = new QuickAllSums(values);
        Counter counter = new Counter();
        testSums(allSums, counter);
        assertThat(counter.getCount()).isEqualTo(7);
    }

    private void testSums(AllSums allSums, Counter counter) {
        assertThat(allSums.getSums(counter)).isEqualTo(new int[]{1, 3, 6, 10, 15, 21, 28, 36});
    }
}


text:
<?php

namespace noFlash\TorrentGhost\Command;

use noFlash\TorrentGhost\Console\ConsoleApplication;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;

/**
 * Abstract command used by all other commands inside application
 */
abstract class AppCommand extends Command
{
    /**
     * POSIX exit code returned when everything went well
     *
     * @see {http://tldp.org/LDP/abs/html/exitcodes.html}
     */
    const POSIX_EXIT_OK = 0;

    /**
     * POSIX exit code returned for general error
     *
     * @see {http://tldp.org/LDP/abs/html/exitcodes.html}
     */
    const POSIX_EXIT_ERROR = 1;

    protected function configure()
    {
        $this->addOption(
            'config',
            'c',
            InputOption::VALUE_REQUIRED,
            'Configuration file location',
            ConsoleApplication::DEFAULT_CONFIG_FILE
        );

        $this->addOption(
            'log',
            'l',
            InputOption::VALUE_REQUIRED,
            'Log file location. By defaults app logs to stdout.',
            ConsoleApplication::DEFAULT_LOG_FILE
        );

    }
}


text:
require "devise/hooks/lockable"

module Devise
  module Models
    # Handles blocking a user access after a certain number of attempts.
    # Lockable accepts two different strategies to unlock a user after it's
    # blocked: email and time. The former will send an email to the user when
    # the lock happens, containing a link to unlock its account. The second
    # will unlock the user automatically after some configured time (ie 2.hours).
    # It's also possible to setup lockable to use both email and time strategies.
    #
    # == Options
    #
    # Lockable adds the following options to +devise+:
    #
    #   * +maximum_attempts+: how many attempts should be accepted before blocking the user.
    #   * +lock_strategy+: lock the user account by :failed_attempts or :none.
    #   * +unlock_strategy+: unlock the user account by :time, :email, :both or :none.
    #   * +unlock_in+: the time you want to lock the user after to lock happens. Only available when unlock_strategy is :time or :both.
    #   * +unlock_keys+: the keys you want to use when locking and unlocking an account
    #
    module Lockable
      extend  ActiveSupport::Concern

      delegate :lock_strategy_enabled?, :unlock_strategy_enabled?, to: "self.class"

      def self.required_fields(klass)
        attributes = []
        attributes << :failed_attempts if klass.lock_strategy_enabled?(:failed_attempts)
        attributes << :locked_at if klass.unlock_strategy_enabled?(:time)
        attributes << :unlock_token if klass.unlock_strategy_enabled?(:email)

        attributes
      end

      # Lock a user setting its locked_at to actual time.
      # * +opts+: Hash options if you don't want to send email
      #   when you lock access, you could pass the next hash
      #   `{ send_instructions: false } as option`.
      def lock_access!(opts = { })
        self.locked_at = Time.now.utc

        if unlock_strategy_enabled?(:email) && opts.fetch(:send_instructions, true)
          send_unlock_instructions
        else
          save(validate: false)
        end
      end

      # Unlock a user by cleaning locked_at and failed_attempts.
      def unlock_access!
        self.locked_at = nil
        self.failed_attempts = 0 if respond_to?(:failed_attempts=)
        self.unlock_token = nil  if respond_to?(:unlock_token=)
        save(validate: false)
      end

      # Verifies whether a user is locked or not.
      def access_locked?
        !!locked_at && !lock_expired?
      end

      # Send unlock instructions by email
      def send_unlock_instructions
        raw, enc = Devise.token_generator.generate(self.class, :unlock_token)
        self.unlock_token = enc
        self.save(validate: false)
        send_devise_notification(:unlock_instructions, raw, {})
        raw
      end

      # Resend the unlock instructions if the user is locked.
      def resend_unlock_instructions
        if_access_locked { send_unlock_instructions }
      end

      # Overwrites active_for_authentication? from Devise::Models::Activatable for locking purposes
      # by verifying whether a user is active to sign in or not based on locked?
      def active_for_authentication?
        super && !access_locked?
      end

      # Overwrites invalid_message from Devise::Models::Authenticatable to define
      # the correct reason for blocking the sign in.
      def inactive_message
        access_locked? ? :locked : super
      end

      # Overwrites valid_for_authentication? from Devise::Models::Authenticatable
      # for verifying whether a user is allowed to sign in or not. If the user
      # is locked, it should never be allowed.
      def valid_for_authentication?
        return super unless persisted? && lock_strategy_enabled?(:failed_attempts)

        # Unlock the user if the lock is expired, no matter
        # if the user can login or not (wrong password, etc)
        unlock_access! if lock_expired?

        if super && !access_locked?
          true
        else
          self.failed_attempts ||= 0
          self.failed_attempts += 1
          if attempts_exceeded?
            lock_access! unless access_locked?
          else
            save(validate: false)
          end
          false
        end
      end

      def unauthenticated_message
        # If set to paranoid mode, do not show the locked message because it
        # leaks the existence of an account.
        if Devise.paranoid
          super
        elsif access_locked? || (lock_strategy_enabled?(:failed_attempts) && attempts_exceeded?)
          :locked
        elsif lock_strategy_enabled?(:failed_attempts) && last_attempt?
          :last_attempt
        else
          super
        end
      end

      protected

        def attempts_exceeded?
          self.failed_attempts >= self.class.maximum_attempts
        end

        def last_attempt?
          self.failed_attempts == self.class.maximum_attempts - 1
        end

        # Tells if the lock is expired if :time unlock strategy is active
        def lock_expired?
          if unlock_strategy_enabled?(:time)
            locked_at && locked_at < self.class.unlock_in.ago
          else
            false
          end
        end

        # Checks whether the record is locked or not, yielding to the block
        # if it's locked, otherwise adds an error to email.
        def if_access_locked
          if access_locked?
            yield
          else
            self.errors.add(Devise.unlock_keys.first, :not_locked)
            false
          end
        end

      module ClassMethods
        # Attempt to find a user by its unlock keys. If a record is found, send new
        # unlock instructions to it. If not user is found, returns a new user
        # with an email not found error.
        # Options must contain the user's unlock keys
        def send_unlock_instructions(attributes={})
          lockable = find_or_initialize_with_errors(unlock_keys, attributes, :not_found)
          lockable.resend_unlock_instructions if lockable.persisted?
          lockable
        end

        # Find a user by its unlock token and try to unlock it.
        # If no user is found, returns a new user with an error.
        # If the user is not locked, creates an error for the user
        # Options must have the unlock_token
        def unlock_access_by_token(unlock_token)
          original_token = unlock_token
          unlock_token   = Devise.token_generator.digest(self, :unlock_token, unlock_token)

          lockable = find_or_initialize_with_error_by(:unlock_token, unlock_token)
          lockable.unlock_access! if lockable.persisted?
          lockable.unlock_token = original_token
          lockable
        end

        # Is the unlock enabled for the given unlock strategy?
        def unlock_strategy_enabled?(strategy)
          [:both, strategy].include?(self.unlock_strategy)
        end

        # Is the lock enabled for the given lock strategy?
        def lock_strategy_enabled?(strategy)
          self.lock_strategy == strategy
        end

        Devise::Models.config(self, :maximum_attempts, :lock_strategy, :unlock_strategy, :unlock_in, :unlock_keys)
      end
    end
  end
end


text:
The common problem with ssh is to enter your password every time you log in. To automatize this, you can generate a pair of keys and copy the public one to the remote server. This way you can log in without typing password every time.

### Generate keys on your local machine

Generate a new pair of keys and save it under /home/user/.ssh/id_rsa. Do not enter any passphrase if you do not want to type it every time you log in.

	# generate keys with name rsa
	ssh-keygen -t rsa

	# so now we have two keys
	/home/user/.ssh/id_rsa # private
	/home/user/.ssh/id_rsa.pub # public

### Make sure the .ssh folder exists on the remote server

You can create it easily by this command:

	ssh user@remote mkdir -p .ssh

### Add the public key to the remote server

In order to be recognized by the remote server we must append the contents of our public key into the .ssh/authorized_keys file.

	cat .ssh/id_rsa.pub | ssh user@remote 'cat >> .ssh/authorized_keys'


text:
"""Tests for tpu_test_wrapper.py."""

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

from absl.testing import flagsaver

from tensorflow.python.platform import flags
from tensorflow.python.platform import test
from tensorflow.python.tpu import tpu_test_wrapper

class TPUTestWrapperTest(test.TestCase):

  @flagsaver.flagsaver()
  def test_flags_undefined(self):
    tpu_test_wrapper.maybe_define_flags()

    self.assertIn('tpu', flags.FLAGS)
    self.assertIn('zone', flags.FLAGS)
    self.assertIn('project', flags.FLAGS)
    self.assertIn('model_dir', flags.FLAGS)

  @flagsaver.flagsaver()
  def test_flags_already_defined_not_overridden(self):
    flags.DEFINE_string('tpu', 'tpuname', 'helpstring')
    tpu_test_wrapper.maybe_define_flags()

    self.assertIn('tpu', flags.FLAGS)
    self.assertIn('zone', flags.FLAGS)
    self.assertIn('project', flags.FLAGS)
    self.assertIn('model_dir', flags.FLAGS)
    self.assertEqual(flags.FLAGS.tpu, 'tpuname')

  @flagsaver.flagsaver(bazel_repo_root='tensorflow/python')
  def test_parent_path(self):
    filepath = '/filesystem/path/tensorflow/python/tpu/example_test.runfiles/tensorflow/python/tpu/example_test'  # pylint: disable=line-too-long
    self.assertEqual(
        tpu_test_wrapper.calculate_parent_python_path(filepath),
        'tensorflow.python.tpu')

  @flagsaver.flagsaver(bazel_repo_root='tensorflow/python')
  def test_parent_path_raises(self):
    filepath = '/bad/path'
    with self.assertRaisesWithLiteralMatch(
        ValueError,
        'Filepath "/bad/path" does not contain repo root "tensorflow/python"'):
      tpu_test_wrapper.calculate_parent_python_path(filepath)

  def test_is_test_class_positive(self):

    class A(test.TestCase):
      pass

    self.assertTrue(tpu_test_wrapper._is_test_class(A))

  def test_is_test_class_negative(self):

    class A(object):
      pass

    self.assertFalse(tpu_test_wrapper._is_test_class(A))

  @flagsaver.flagsaver(wrapped_tpu_test_module_relative='.tpu_test_wrapper_test'
                      )
  def test_move_test_classes_into_scope(self):
    # Test the class importer by having the wrapper module import this test
    # into itself.
    with test.mock.patch.object(
        tpu_test_wrapper, 'calculate_parent_python_path') as mock_parent_path:
      mock_parent_path.return_value = (
          tpu_test_wrapper.__name__.rpartition('.')[0])

      tpu_test_wrapper.move_test_classes_into_scope()

    self.assertEqual(
        tpu_test_wrapper.tpu_test_imported_TPUTestWrapperTest.__name__,
        self.__class__.__name__)

  @flagsaver.flagsaver(test_dir_base='gs://example-bucket/tempfiles')
  def test_set_random_test_dir(self):
    tpu_test_wrapper.maybe_define_flags()
    tpu_test_wrapper.set_random_test_dir()

    self.assertStartsWith(flags.FLAGS.model_dir,
                          'gs://example-bucket/tempfiles/')
    self.assertGreater(
        len(flags.FLAGS.model_dir), len('gs://example-bucket/tempfiles/'))

  @flagsaver.flagsaver(test_dir_base='gs://example-bucket/tempfiles')
  def test_set_random_test_dir_repeatable(self):
    tpu_test_wrapper.maybe_define_flags()
    tpu_test_wrapper.set_random_test_dir()
    first = flags.FLAGS.model_dir
    tpu_test_wrapper.set_random_test_dir()
    second = flags.FLAGS.model_dir

    self.assertNotEqual(first, second)

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


text:
package mojolly.inflector

private[inflector] object Util {
  def ucase(str: String): String = str.toUpperCase()
  def lcase(str: String): String = str.toLowerCase()
}


text:
"""
    UrlResolver site plugin
    Copyright (C) 2018 gujal

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import re
from lib import helpers
from urlresolver import common
from urlresolver.resolver import UrlResolver, ResolverError

class KhatriResolver(UrlResolver):
    name = "khatriuploads"
    domains = ["khatriuploads.com"]
    pattern = '(?://|\.)(khatriuploads\.com)/([0-9a-f]+)'

    def __init__(self):
        self.net = common.Net()
        self.user_agent = common.EDGE_USER_AGENT
        self.headers = {'User-Agent': self.user_agent}

    def get_media_url(self, host, media_id):
        web_url = self.get_url(host, media_id)
        headers = self.headers
        response = self.net.http_GET(web_url, headers=headers)
        response_headers = response.get_headers(as_dict=True)
        cookies = response_headers.get('Set-Cookie')

        cookie = ''
        for ck in cookies.split('Only, '):
            cookie += ck.split(';')[0] + '; '
        headers.update({'Cookie': cookie[:-2],
                        'Referer': 'https://{}/'.format(host)})

        html = response.content
        data = helpers.get_hidden(html, index=1)
        _html = self.net.http_POST(web_url, headers=headers, form_data=data).content
        url = re.search('"link_button"\s*href="([^"]+)',_html)
        if url:
            response = self.net.http_GET(url.group(1), headers=headers)
            strurl = re.search('"link_button"\s*href="([^"]+)',response.content)
            if strurl:
                return strurl.group(1)  + helpers.append_headers(headers)

        raise ResolverError('File not found')

    def get_url(self, host, media_id):
        return self._default_get_url(host, media_id, template='https://{host}/{media_id}')


text:
use std::fmt;

use itertools::Itertools;
use exec;

use config::{ConfigDefinition, Tunnel, State};

pub struct Execution {
    definition: ConfigDefinition,
    command_parts: Vec<Vec<String>>,
}

impl From<ConfigDefinition> for Execution {
    fn from(definition: ConfigDefinition) -> Self {
        let definition = normalize_definition(definition);
        Execution { definition, command_parts: Vec::new(), }
    }
}

impl Execution {
    pub fn prepare(&mut self) {
        let mut parts = Vec::new();

        for jump in &self.definition.chain {
            let mut cmd = vec!["ssh".into()];

            if jump.verbose {
                cmd.push("-v".into());
            }

            if let State::Enabled(_) = jump.agent_passthrough {
                cmd.push("-A".into());
            }

            if let Some(port) = jump.port {
                cmd.push("-p".into());
                cmd.push(port.to_string());
            }

            if let Some(ref key) = jump.key {
                cmd.push("-i".into());
                cmd.push(key.clone());
            }

            if let State::Enabled(ref tunnel) = jump.tunnel {
                cmd.push("-L".into());
                cmd.push(SshArg(tunnel).to_string());
            }

            if let Some(ref user) = jump.user {
                cmd.push(format!("{}@{}", user, jump.host));
            } else {
                cmd.push(jump.host.clone());
            }

            if let State::Enabled(_) = jump.no_command {
                cmd.push("-N".into());
            }

            parts.push(cmd);
        }

        self.command_parts = parts;
    }

    pub fn command_line(&mut self) -> String {
        if self.command_parts.is_empty() {
            self.prepare();
        }

        self.command_parts.iter()
            .map(|part| part.iter().join(" "))
            .join(" -t \\\n  ")
    }

    pub fn run(mut self) {
        if self.command_parts.is_empty() {
            self.prepare();
        }

        let args: Vec<_> = self.command_parts.into_iter()
            .intersperse(vec!["-t".into()])
            .flatten()
            .collect();

        println!("{}", args.join(" "));

        let command = args[0].clone();
        let error = exec::execvp(command, args);

        eprintln!("Failed to run SSH: {}", error);
        ::std::process::exit(1);
    }
}

/// Expands the absent pieces in the configuration.
///
/// In particular, does the following things:
/// * Expands tunnelspecs, e.g. 12345 -> ":12345|localhost:12345"
/// * Propagates tunnelspecs down the chains
/// * Adds flags responsible for -A and -N where appropriate
fn normalize_definition(mut definition: ConfigDefinition) -> ConfigDefinition {
    let mut last_tunnel: Option<Tunnel> = None;
    let chain_len = definition.chain.len();
    for (i, jump) in definition.chain.iter_mut().enumerate() {
        // Fix the tunnelspec if it is present:
        //   1. Propagate local or remote port to its missing counterpart
        //   2. Add the default "localhost" value if the remote host is absent
        if let State::Enabled(ref mut tunnel) = jump.tunnel {
            if tunnel.remote_host.is_none() {
                tunnel.remote_host = Some("localhost".into());
            }

            if tunnel.local_port.is_none() {
                tunnel.local_port = tunnel.remote_port;
            }

            if tunnel.remote_port.is_none() {
                tunnel.remote_port = tunnel.local_port;
            }
        }

        // Inject the previous tunnel if it is absent in this jump, unless it is explicitly disabled
        if let State::Unset = jump.tunnel {
            if let Some(ref last_tunnel) = last_tunnel {
                jump.tunnel = State::Enabled(last_tunnel.clone());
            }
        }

        // If the tunnel is configured
        if let State::Enabled(ref tunnel) = jump.tunnel {
            // Add the `-A` argument if this is not the last jump and if it is not disabled explicitly
            if i < chain_len - 1 {
                if let State::Unset = jump.agent_passthrough {
                    jump.agent_passthrough = State::Enabled(());
                }
            }

            // Add the `-N` argument if this is the last jump and if it is not disabled explicitly
            if i == chain_len - 1 {
                if let State::Unset = jump.no_command {
                    jump.no_command = State::Enabled(());
                }
            }

            // Save the tunnel configuration for further use
            last_tunnel = Some(tunnel.clone());

        } else {
            // Remove the last tunnel if it is not configured/disabled in this jump
            last_tunnel = None;
        }
    }

    definition
}

struct SshArg<'a>(&'a Tunnel);

impl<'a> fmt::Display for SshArg<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let Tunnel { ref local_host, local_port, ref remote_host, remote_port } = *self.0;

        if let Some(host) = local_host.as_ref() {
            write!(f, "{}:", host)?;
        }

        if let Some(port) = local_port {
            write!(f, "{}:", port)?;
        }

        if let Some(host) = remote_host.as_ref() {
            f.write_str(host)?;
        }

        f.write_str(":")?;

        if let Some(port) = remote_port.as_ref() {
            write!(f, "{}", port)?;
        }

        Ok(())
    }
}


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace WebApplication2
{
	/// <summary>
	/// Summary description for frmResourcesInfo.
	/// </summary>
	public partial class frmStaffActionsProc: System.Web.UI.Page
	{
		/*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+
			"uid=tauheed;pwd=tauheed;");*/
		private static string strURL =
			System.Configuration.ConfigurationSettings.AppSettings["local_url"];
		private static string strDB =
			System.Configuration.ConfigurationSettings.AppSettings["local_db"];
		public SqlConnection epsDbConn=new SqlConnection(strDB);
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			loadForm();
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);

		}
		#endregion
		private void loadForm()
		{
			if (Session["SA"].ToString() =="frmOrgLocMgrs")
			{
				DataGrid1.Columns[5].Visible=false;
				btnCancel.Text="OK";
			}
			else
			{
				DataGrid1.Columns[9].Visible=false;
			}

			if (!IsPostBack)
			{
				lblOrg.Text=Session["OrgName"].ToString();
				loadData();
			}
		}
		private void loadData()
		{
			SqlCommand cmd=new SqlCommand();
			cmd.CommandType=CommandType.StoredProcedure;
			cmd.Connection=this.epsDbConn;
			cmd.CommandText="hrs_RetrieveStaffActionsProc";
			cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
			cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
			cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
			cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
			cmd.Parameters.Add ("@LicenseId",SqlDbType.Int);
			cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString();
			cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
			cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
			DataSet ds=new DataSet();
			SqlDataAdapter da=new SqlDataAdapter(cmd);
			da.Fill(ds,"StaffActions");
			if (ds.Tables["StaffActions"].Rows.Count == 0)
			{
				DataGrid1.Visible=false;
				lblContents1.Text="There are no individuals who are identified"
					+ " as being part of your organization."
					+ " Click on 'Add' to identify such individuals.";
			}
			else
			{
				lblContents1.Text="Listed below are staff or consultant appointments to which"
					+ " you may assign this task by clicking on 'Select'."
					+ " The column 'Appointing Organizations' indicates the organization that is "
					+ " managing the contract or agreement.  'Appointment Type'"
					+ " indicates the type of contract between the individual and the organization.  Note that"
					+ " you may find an individual identified more than once in the list below.  This"
					+ " would indicate that there is more than one contract under which the individual"
					+ " works, and you should thus make sure you are assigning the individual under the "
					+ " right contract.  If the individual you"
					+ " need to add is not in the list below, then that individual needs to be"
					+ " appointed before you can proceed.";

				Session["ds"] = ds;
				DataGrid1.DataSource=ds;
				DataGrid1.DataBind();
			}
			Session["ds"] = ds;
			DataGrid1.DataSource=ds;
			DataGrid1.DataBind();
			if (Session["SA"].ToString() == "frmOrgLocMgrs")
			{
				refreshGrid();
			}
		}
		private void refreshGrid()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
				CheckBox cb = (CheckBox)(i.Cells[9].FindControl("cbxSel"));
				SqlCommand cmd=new SqlCommand();
				cmd.Connection=this.epsDbConn;
				cmd.CommandType=CommandType.Text;
				cmd.CommandText="Select Id from OrgLocMgrs"
					+ " Where OrgLocId = " + Session["OrgLocId"].ToString()
					+ " and StaffActionsId = " + i.Cells[0].Text;
				cmd.Connection.Open();
				if (cmd.ExecuteScalar() != null)
				{
					cb.Checked = true;
					cb.Enabled = false;
				}
				cmd.Connection.Close();
			}
		}

		private void Exit()
		{
			Session["btnAction1"] = null;
			Response.Redirect (strURL + Session["SA"].ToString() + ".aspx?");
		}
		protected void btnCancel_Click(object sender, System.EventArgs e)
		{
			if (Session["SA"].ToString() =="frmOrgLocMgrs")
			{
				updateGrid();
			}
			else
			{
				Session["StaffActionProc"] = "Cancel";
			}
			Exit();

		}
		private void updateGrid()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
				CheckBox cb = (CheckBox)(i.Cells[9].FindControl("cbxSel"));
				if ((cb.Checked) & (cb.Enabled))
				{
					SqlCommand cmd=new SqlCommand();
					cmd.CommandType=CommandType.StoredProcedure;
					cmd.CommandText="wms_UpdateOrgLocMgrs";
					cmd.Connection=this.epsDbConn;
					cmd.Parameters.Add("@OrgLocId", SqlDbType.Int);
					cmd.Parameters ["@OrgLocId"].Value=Session["OrgLocId"].ToString();
					cmd.Parameters.Add("@StaffActionsId", SqlDbType.Int);
					cmd.Parameters ["@StaffActionsId"].Value=i.Cells[0].Text;
					cmd.Connection.Open();
					cmd.ExecuteNonQuery();
					cmd.Connection.Close();
				}
			}
		}

		private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if (e.CommandName == "Select")
			{
				Session["StaffActionId"] = e.Item.Cells[0].Text;
				Session["TypeIdSA"] = e.Item.Cells[10].Text;

				Exit();
			}

			else if (e.CommandName == "Update")
			{
				Session["CSA"]="frmStaffActionsproc";
				Session["btnAction1"]="Update";
				Session["OrgIdSA"]=e.Item.Cells[7].Text;
				Session["Id"]=e.Item.Cells[0].Text;
				Response.Redirect (strURL + "frmUpdStaffAction.aspx?");
			}
			else if (e.CommandName == "Delete")
			{
				SqlCommand cmd=new SqlCommand();
				cmd.CommandType=CommandType.StoredProcedure;
				cmd.Connection=this.epsDbConn;
				cmd.CommandText="hrs_DeleteStaffAction";
				cmd.Parameters.Add ("@Id",SqlDbType.Int);
				cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text;
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();
				loadData();
			}
		}
	}
}


text:
package api

import (
	cfclient "github.com/cloudfoundry-community/go-cfclient"
	"os"
	"log"
	"strconv"
	"strings"
	"app-metrics-nozzle/domain"
)

var logger = log.New(os.Stdout, "", 0)
var client *cfclient.Client

func init(){

	skipSsl, _ := strconv.ParseBool(os.Getenv("SKIP_SSL_VALIDATION"))
	c := cfclient.Config{
		ApiAddress:        os.Getenv("API_ENDPOINT"),
		Username:          os.Getenv("FIREHOSE_USER"),
		Password:          os.Getenv("FIREHOSE_PASSWORD"),
		SkipSslValidation: skipSsl,
	}

	logger.Println("Processing Cloud Controller call to " + os.Getenv("API_ENDPOINT"))
	client, _ = cfclient.NewClient(&c)
}

func AnnotateWithCloudControllerData(app *domain.App) {

	ccAppDetails, _ := client.AppByGuid(app.GUID)

	instances, _ := client.GetAppInstances(app.GUID)
	runnintCount := 0
	instanceUp := "RUNNING"

	space, _ := ccAppDetails.Space()
	org, _ := space.Org()

	app.Diego = ccAppDetails.Diego
	app.Buildpack = ccAppDetails.Buildpack
	app.Instances = make([]domain.Instances, int64(len(instances)))

	for idx, eachInstance := range instances {
		if strings.Compare(instanceUp, eachInstance.State) == 0 {
			runnintCount++;
		}
		i, _ := strconv.ParseInt(idx, 10, 32)
		app.Instances[i].InstanceIndex = i
		app.Instances[i].State = eachInstance.State
		app.Instances[i].Since = eachInstance.Since
		app.Instances[i].Uptime = eachInstance.Uptime
	}

	if len(app.Buildpack) == 0 { app.Buildpack = ccAppDetails.DetectedBP }

	app.Environment = ccAppDetails.Environment

	app.Organization.ID = org.Guid
	app.Organization.Name = org.Name

	app.Space.ID = space.Guid
	app.Space.Name = space.Name

	app.InstanceCount.Configured = len(instances)
	app.InstanceCount.Running = runnintCount

	app.EnvironmentSummary.TotalDiskConfigured = ccAppDetails.DiskQuota * 1024 * 1024
	app.EnvironmentSummary.TotalMemoryConfigured = ccAppDetails.MemQuota * 1024 * 1024

	app.EnvironmentSummary.TotalDiskProvisioned = ccAppDetails.DiskQuota * 1024 * 1024 * int32(len(instances))
	app.EnvironmentSummary.TotalMemoryProvisioned = ccAppDetails.MemQuota * 1024 * 1024 * int32(len(instances))

	if 0 < len(ccAppDetails.RouteData) {
		app.Routes = make([]string, len(ccAppDetails.RouteData))
		for i := 0; i < len(ccAppDetails.RouteData); i++ {
			app.Routes[i] = ccAppDetails.RouteData[i].Entity.Host + "." + ccAppDetails.RouteData[i].Entity.DomainData.Entity.Name
		}
	}

	app.State = ccAppDetails.State
}

func UsersForSpace(guid string) (Users []cfclient.User) {
	users, _ := client.UsersBy(guid, "spaces")
	return users
}

func UsersForOrganization(guid string) (Users []cfclient.User) {
	users, _ := client.UsersBy(guid, "organizations")
	return users
}

func SpacesDetailsFromCloudController()  (Spaces []cfclient.Space){
	spaces, _ := client.ListSpaces()
	return spaces
}

func OrgsDetailsFromCloudController()  (Orgs []cfclient.Org){
	orgs, _ := client.ListOrgs()
	return orgs
}


text:
% Yiying Li for CV Spring 2015
% Does computation of the filter bank and dictionary, and saves
% it in dictionary.mat

load('../data/images/traintest.mat');
% give the absolute path
to_process = strcat(['../data/images/'],train_imagenames);
[filterBank,dictionary] = getFilterBankAndDictionary(to_process);
save('dictionary.mat','filterBank','dictionary');
clear to_process


text:
// @flow

import { ASYNC_ITERATOR } from 'orio-utils'

import { AsAsyncIterator, AsIterator } from '../as-iterator'

const AsyncTarget = AsAsyncIterator(
  class {
    /*:: @@asyncIterator: () => $AsyncIterator<*, void, void> */

    next(): Promise<IteratorResult<*, void>> {
      return Promise.resolve({
        done: false,
        value: this,
      })
    }
  },
)

const SyncTarget = AsIterator(
  class {
    /*:: @@iterator: () => Iterator<*> */

    next(): IteratorResult<*, void> {
      return {
        done: false,
        value: this,
      }
    }
  },
)

test('@AsAsyncIterator', () => {
  const subj = new AsyncTarget()

  // $ExpectError
  AsAsyncIterator(class {})
  // $FlowIgnore
  expect(subj[ASYNC_ITERATOR]()).toBe(subj)
})

test('@AsIterator', () => {
  const subj = new SyncTarget()

  // $ExpectError
  AsIterator(class {})
  // $FlowIgnore
  expect(subj[Symbol.iterator]()).toBe(subj)
})


text:
package net.java.sip.communicator.plugin.propertieseditor;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;

import net.java.sip.communicator.plugin.desktoputil.*;

import org.jitsi.service.configuration.*;
import org.jitsi.service.resources.*;

/**
 *
 * @author Marin Dzhigarov
 */
public class NewPropertyDialog
    extends SIPCommDialog
    implements ActionListener
{

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

    private ConfigurationService confService = PropertiesEditorActivator
        .getConfigurationService();

    private ResourceManagementService resourceManagementService =
        PropertiesEditorActivator.getResourceManagementService();

    /**
     * The ok button.
     */
    private JButton okButton = new JButton(
        resourceManagementService.getI18NString("service.gui.OK"));

    /**
     * The cancel button.
     */
    private JButton cancelButton = new JButton(
        resourceManagementService.getI18NString("service.gui.CANCEL"));

    /**
     * The property name text field.
     */
    private JTextField propertyNameTextField = new JTextField();

    /**
     * The property value text field.
     */
    private JTextField propertyValueTextField = new JTextField();

    /**
     * The property name label.
     */
    private JLabel propertyNameLabel = new JLabel(
        resourceManagementService.getI18NString("service.gui.NAME") + ": ");

    /**
     * The property value label.
     */
    private JLabel propertyValueLabel = new JLabel(
        resourceManagementService.getI18NString("service.gui.VALUE") + ": ");

    /**
     * The panel containing all buttons.
     */
    private JPanel buttonsPanel = new TransparentPanel(new FlowLayout(
        FlowLayout.CENTER));

    /**
     * The panel containing the property value and name panels.
     */
    private JPanel dataPanel = new TransparentPanel(new GridBagLayout());

    /**
     * Creates an instance of <tt>NewPropertyDialog</tt>.
     */
    public NewPropertyDialog()
    {
        setTitle(resourceManagementService
            .getI18NString("plugin.propertieseditor.NEW_PROPERTY_TITLE"));
        JPanel fields = new TransparentPanel(new BorderLayout());
        fields.setPreferredSize(new Dimension(450, 150));

        this.getContentPane().add(fields);

        fields.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
        fields.add(dataPanel, BorderLayout.NORTH);
        fields.add(buttonsPanel, BorderLayout.SOUTH);

        this.buttonsPanel.add(okButton);
        this.buttonsPanel.add(cancelButton);
        okButton.setEnabled(false);

        this.okButton.addActionListener(this);
        this.cancelButton.addActionListener(this);

        GridBagConstraints first = new GridBagConstraints();
        first.gridx = 0;
        first.gridy = 0;
        first.weightx = 0;
        first.anchor = GridBagConstraints.LINE_START;
        first.gridwidth = 1;
        first.insets = new Insets(2, 4, 2, 4);
        first.fill = GridBagConstraints.HORIZONTAL;

        GridBagConstraints second = new GridBagConstraints();
        second.gridx = 1;
        second.gridy = 0;
        second.weightx = 2;
        second.anchor = GridBagConstraints.LINE_START;
        second.gridwidth = 1; // GridBagConstraints.REMAINDER;
        second.insets = first.insets;
        second.fill = GridBagConstraints.HORIZONTAL;

        dataPanel.add(propertyNameLabel, first);
        dataPanel.add(propertyNameTextField, second);

        first.gridy = ++second.gridy;

        dataPanel.add(propertyValueLabel, first);
        dataPanel.add(propertyValueTextField, second);

        propertyNameTextField.getDocument().addDocumentListener(
            new DocumentListener()
            {
                public void insertUpdate(DocumentEvent e)
                {
                    okButton.setEnabled(true);
                }

                public void removeUpdate(DocumentEvent e)
                {
                    if (propertyNameTextField.getText().length() == 0)
                        okButton.setEnabled(false);
                }

                public void changedUpdate(DocumentEvent e)
                {
                }
            });
    }

    /**
     * Performs corresponding actions, when a button is pressed.
     *
     * @param e the <tt>ActionEvent</tt> that notified us
     */
    public void actionPerformed(ActionEvent e)
    {
        JButton sourceButton = (JButton) e.getSource();

        if (sourceButton.equals(okButton))
        {
            confService.setProperty(propertyNameTextField.getText(),
                propertyValueTextField.getText());
        }
        dispose();
    }

    /**
     * Presses programmatically the cancel button, when Esc key is pressed.
     *
     * @param isEscaped indicates if the Esc button was pressed on close
     */
    protected void close(boolean isEscaped)
    {
        cancelButton.doClick();
    }

}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace AssetMatrixConsoleApp.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AssetMatrixConsoleApp.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to <settings>
        ///	<url>https://cdn.labster.com/content/simulations/release/4.1.27s160/Simulations/</url>
        ///	<simulations>
        ///		<simulation>Engine__ModularLab_Empty.xml</simulation>
        ///		<simulation>Engine__SafetyLab_Empty.xml</simulation>
        ///		<simulation>Engine_ABL_Antibodies.xml</simulation>
        ///		<simulation>Engine_ACB_AcidBases.xml</simulation>
        ///		<simulation>Engine_ANG_AnimalGenetics.xml</simulation>
        ///		<simulation>Engine_BCL_BiologicalCircuit.xml</simulation>
        ///		<simulation>Engine_BIL_BacteriaIsolation.xml</simulati [rest of string was truncated]";.
        /// </summary>
        internal static string settings {
            get {
                return ResourceManager.GetString("settings", resourceCulture);
            }
        }
    }
}


text:
module Daemonizer
  class Option
    class OptionError < StandardError; end

    def initialize(option, value, auto_eval = false)
      @option = option
      @value = value
      @auto_eval = auto_eval
      if @auto_eval && !@value.is_a?(Proc)
        raise OptionError, "auto_apply can be used only with callable option"
      end
    end

    def value(handler = nil)
      if @auto_eval && @value.is_a?(Proc)
        if handler && handler.worker_id && handler.workers_count
          if @value.arity == 0 || @value.arity == -1
            return @value.call
          elsif @value.arity == 2
            return @value.call(handler.worker_id, handler.workers_count)
          else
            raise OptionError, "option lambda should accept 0 or 2 parameters"
          end
        else
          raise OptionError, "value called before handler initialized"
        end
      else
        @value
      end
    end

  end
end


text:
<?php
session_start();

require_once dirname(__FILE__) . '/lib/limonade/lib/limonade.php';
require_once dirname(__FILE__) . '/lib/twitteroauth/twitteroauth/twitteroauth.php';

define('CONSUMER_KEY',    'xxxxxxxxx');
define('CONSUMER_SECRET', 'xxxxxxxxx');
define('CALLBACK_URI',    '/oauth/twitter/callback');

option('views_dir', dirname(__FILE__) . '/views');

dispatch('/', function() {
    if (isset($_SESSION['screen_name'])) {
        return redirect('/home');
    } else {
        return render('index.html.php');
    }
});

dispatch('/oauth/twitter', function() {
    $oa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
    $request_token = $oa->getRequestToken(CALLBACK_URI);
    $_SESSION['request_token'] = $request_token['oauth_token'];
    $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];

    return redirect($oa->getAuthorizeURL($_SESSION['request_token']));
});

dispatch('/oauth/twitter/callback', function() {
    $oa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['request_token'], $_SESSION['request_token_secret']);
    $access_token = $oa->getAccessToken();
    $_SESSION['screen_name'] = $access_token['screen_name'];
    $_SESSION['access_token'] = $access_token['oauth_token'];
    $_SESSION['access_token_secret'] = $access_token['oauth_token_secret'];
    return redirect('/home/');
});

dispatch('/home', function() {
    if (isset($_SESSION['screen_name'])) {
        $oa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['access_token'], $_SESSION['access_token_secret']);
        $timeline = $oa->OAuthRequest('http://api.twitter.com/1/statuses/home_timeline.xml', 'GET', array('count' => 30));
        $timeline = simplexml_load_string($timeline);
        set('timeline', $timeline);
        return render('home.html.php');
    } else {
        return redirect('/');
    }
});

dispatch('/signout', function() {
    session_destroy();
    return redirect('/');
});

run();
?>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <meta name=viewport content="width=device-width, initial-scale=0.3333334">
  <meta name="google-site-verification" content="_bMOCDpkx9ZAzBwb2kF3PRHbfUUdFj2uO8Jd1AXArz4"/>
  <title>ImageMagick: Command-line Tools: Compare</title>
  <meta http-equiv="content-language" content="en-US"/>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <meta http-equiv="reply-to" content="magick-users@imagemagick.org"/>
  <meta name="application-name" content="ImageMagick"/>
  <meta name="description" content="ImageMagick® is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats (over 200) including PNG, JPEG, JPEG-2000, GIF, WebP, Postscript, PDF, and SVG. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves."/>
  <meta name="application-url" content="http://www.imagemagick.org"/>
  <meta name="generator" content="PHP"/>
  <meta name="keywords" content="command-line, tools:, compare, ImageMagick, PerlMagick, image processing, image, photo, software, Magick++, OpenMP, convert"/>
  <meta name="rating" content="GENERAL"/>
  <meta name="robots" content="INDEX, FOLLOW"/>
  <meta name="generator" content="ImageMagick Studio LLC"/>
  <meta name="author" content="ImageMagick Studio LLC"/>
  <meta name="revisit-after" content="2 DAYS"/>
  <meta name="resource-type" content="document"/>
  <meta name="copyright" content="Copyright (c) 1999-2012 ImageMagick Studio LLC"/>
  <meta name="distribution" content="Global"/>
  <meta name="magick-serial" content="P131-S030410-R485315270133-P82224-A6668-G1245-1"/>
  <link rel="icon" href="../images/wand.png"/>
  <link rel="shortcut icon" href="../images/wand.ico" type="images/x-icon"/>
  <link rel="canonical" href="../index.html" />
  <link rel="meta" type="application/rdf+xml" title="ICI" href="http://imagemagick.org/ici.rdf"/>

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" />

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />

  About ImageMagick

  Binary Releases

    Unix

    Mac OS X

    iOS

    Windows

  Command-line Tools

    Processing

    Options

    Usage

  Program Interfaces

    MagickWand

    MagickCore

    PerlMagick

    Magick++

   Install from Source

    Unix

    Windows

  Resources

  Architecture

  Download

  Search

  Site Map

  Links

  Support ImageMagick Development

ImageMagick Compare Command-line Tool

[Example Usage • Option Summary]

Use the compare program to mathematically and visually annotate the difference between an image and its reconstruction.  See Command Line Processing for advice on how to structure your compare command or see below for example usages of the command.

Example Usage

We list a few examples of the compare command here to illustrate its usefulness and ease of use. To get started, lets compare an image to one thats been sharpened:

 $ convert rose.jpg -sharpen 0x1 reconstruct.jpg $ compare rose.jpg reconstruct.jpg difference.png $ compare -compose src rose.jpg reconstruct.jpg difference.png

  " />

The red areas of the difference image emphasizes (highlight) pixels that are affected by the image sharpening, whereas white de-emphasizes (lowlight) pixels that are untouched by the sharpening process.

In addition to the visual interpretation of the difference in an image and its reconstruction, we report a mathematical measure of the difference:

 $ compare -verbose -metric mae rose.jpg reconstruct.jpg difference.pngImage: rose.jpg

    Channel distortion: MAE

      red: 2282.91 (0.034835)

      green: 1853.99 (0.0282901)

      blue: 2008.67 (0.0306503)

      all: 1536.39 (0.0234439)

Or, if you just want the red channel distortion, use this command:

 $ compare -channel red -metric PSNR rose.jpg reconstruct.jpg difference.png19.63

Or, if you just want the overall image distortion, use this command:

 $ compare -metric PSNR rose.jpg reconstruct.jpg difference.png28.31

If the reconstructed image is a subimage of the image, the compare program returns the best match offset.  In addition, it returns a similarity image such that an exact match location is completely white and if none of the pixels match, black, otherwise some gray level in-between:

 $ compare -metric RMSE -subimage-search logo.png wizard.jpg similarity.gif85.05 (0.00129778) @ 353,157

You can find additional examples of using compare in Graphics from the Command Line.  Further discussion is available in More Graphics from the Command Line and Examples of ImageMagick Usage.

The compare program returns 2 on error otherwise 0 if the images are similar or 1 if they are dissimilar.

Option Summary

The compare command recognizes these options.  Click on an option to get more details about how that option works.

    Option
    Description

    -alpha
    on, activate, off, deactivate, set, opaque, copy",
transparent, extract, background, or shape the alpha channel

    -authenticate value
    decrypt image with this password

    -channel type
    apply option to select image channels

    -colorspace type
    set image colorspace

    -compose operator
    set image composite operator

    -decipher filename
    convert cipher pixels to plain

    -debug events
    display copious debugging information

    -define format:option
    define one or more image format options

    -density geometry
    horizontal and vertical density of the image

    -depth value
    image depth

    -dissimilarity-threshold value
    maximum distortion for (sub)image match (default 0.2)

    -encipher filename
    convert plain pixels to cipher pixels

    -extract geometry
    extract area from image

    -fuzz distance
    colors within this distance are considered equal

    -help
    print program options

    -highlight-color color
    emphasize pixel differences with this color

    -identify
    identify the format and characteristics of the image

    -interlace type
    type of image interlacing scheme

    -limit type value
    pixel cache resource limit

    -log format
    format of debugging information

    -lowlight-color color
    de-emphasize pixel differences with this color

    -metric type
    measure differences between images with this metric

    -profile filename
    add, delete, or apply an image profile

    -quality value
    JPEG/MIFF/PNG compression level

    -quantize colorspace
    reduce image colors in this colorspace

    -quiet
    suppress all warning messages

    -regard-warnings
    pay attention to warning messages.

    -respect-parentheses
    settings remain in effect until parenthesis boundary.

    -sampling-factor geometry
    horizontal and vertical sampling factor

    -seed value
    seed a new sequence of pseudo-random numbers

    -set attribute value
    set an image attribute

    -similarity-threshold value
    minimum distortion for (sub)image match (default 0.0)

    -size geometry
    width and height of image

    -subimage-search
    search for subimage

    -synchronize
    synchronize image to storage device

    -taint
    mark the image as modified

    -transparent-color color
    transparent color

    -verbose
    print detailed information about the image

    -version
    print version information

    -virtual-pixel method
    access method for pixels outside the boundaries of the image

      Discourse Server •
      Public Key •
      Studio •
      JqMagick

  ©  1999-2015 ImageMagick Studio LLC
   Contact the Wizards


text:
/***********************************************************************************************
 *
 * NAME: 		YuJin Kim
 *
 * HOMEWORK: 	Group Project
 *
 * CLASS: 		ICS 211
 *
 * INSTRUCTOR: 	Scott Robertson
 *
 * DATE: 		May 4, 2016
 *
 * FILE:		HighScore.java
 *
 * DESCRIPTION:	This file contains the HighScore class for the Group Project. In this class,
 * 				the previous top scores are displayed in a table. The user can choose to return
 * 				to the main menu.
 *
 **********************************************************************************************/

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JTextArea;

public class HighScore implements ActionListener{
	private int height = 600;
	private int width = 1100;
	JFrame frame = new JFrame("Minesweeper");
	JButton mainmenu = new JButton("Back to Main Menu");

	/********************************************************************************************************
	 *
	 * Method:		HighScore
	 *
	 * Description:	Constructor; creates a new frame in which a table of the best previous scores are displayed.
	 * 				The table is organized by level and best time.
	 * 				Includes a button that when clicked will return the user to the main menu.
	 *
	 * @param		None
	 *
	 * @return		None
	 *
	 ********************************************************************************************************/
	public HighScore(){
		frame.setSize(width, height);									//frame l
		frame.setLayout(new BorderLayout());
		frame.add(mainmenu, BorderLayout.SOUTH);
		mainmenu.addActionListener(this);

		try{
			Scanner scanner = new Scanner(new File("Scores.txt"));		//places all previous scores into an ArrayList depending on
			ArrayList<Integer> statsL1 = new ArrayList<Integer>();		//the level at which it was scored
			ArrayList<Integer> statsL2 = new ArrayList<Integer>();		//i.e. scores achieved at level 3 are placed in statsL3
			ArrayList<Integer> statsL3 = new ArrayList<Integer>();

			while(scanner.hasNextInt()){
				switch(scanner.nextInt()){
				case 1:
					statsL1.add(scanner.nextInt());
					break;
				case 2:
					statsL2.add(scanner.nextInt());
					break;
				case 3:
					statsL3.add(scanner.nextInt());
					break;
				}
			}scanner.close();

			//LEVEL ONE
			for(int i=0; i<statsL1.size(); i++) {						//organizes Level 1 scores from best to worst
				for(int j=0; j<=(statsL1.size()-2); j++){
					if(statsL1.get(j)>statsL1.get(j+1)){
						int tempInt = statsL1.get(j);
						statsL1.set(j, statsL1.get(j+1));
						statsL1.set(j+1, tempInt);
					}
				}
			}

			while(statsL1.size()>10){									//places best 10 scores in a String array
				statsL1.remove(10);
			}
			String[] L1 = new String[10];
			for(int i=0; i<10; i++){
				if(i>=statsL1.size()){
					L1[i] = "";
				}else{
					L1[i] = String.valueOf(statsL1.get(i));
				}
			}

			//L2
			for(int i=0; i<statsL2.size(); i++) {						//organizes Level 2 scores from best to worst
				for(int j=0; j<=(statsL2.size()-2); j++){
					if(statsL2.get(j)>statsL2.get(j+1)){
						int tempInt = statsL2.get(j);
						statsL2.set(j, statsL2.get(j+1));
						statsL2.set(j+1, tempInt);
					}
				}
			}

			while(statsL2.size()>10){									//places best 10 scores in a String array
				statsL2.remove(10);
			}
			String[] L2 = new String[10];
			for(int i=0; i<10; i++){
				if(i>=statsL2.size()){
					L2[i] = "";
				}else{
					L2[i] = String.valueOf(statsL2.get(i));
				}
			}

			//L3
			for(int i=0; i<statsL3.size(); i++) {						//organizes Level 3 scores from best to worst
				for(int j=0; j<=(statsL3.size()-2); j++){
					if(statsL3.get(j)>statsL3.get(j+1)){
						int tempInt = statsL3.get(j);
						statsL3.set(j, statsL3.get(j+1));
						statsL3.set(j+1, tempInt);
					}
				}
			}

			while(statsL3.size()>10){									//places best 10 scores in a String array
				statsL3.remove(10);
			}
			String[] L3 = new String[10];
			for(int i=0; i<10; i++){
				if(i>=statsL3.size()){
					L3[i] = "";
				}else{
					L3[i] = String.valueOf(statsL3.get(i));
				}
			}

			//creates a table at the top of the frame, based on the string arrays of best scores
			String[] colnames = {"Rank", "Level 1 (seconds)", "Level 2 (seconds)", "Level 3 (seconds)"};
			Object[][] data = {
					{1, L1[0], L2[0], L3[0]}, {2, L1[1], L2[1], L3[1]}, {3, L1[2], L2[2], L3[2]}, {4, L1[3], L2[3], L3[3]}, {5, L1[4], L2[4], L3[4]},
					{6, L1[5], L2[5], L3[5]}, {7, L1[6], L2[6], L3[6]}, {8, L1[7], L2[7], L3[7]}, {9, L1[8], L2[8], L3[8]}, {10, L1[9], L2[9], L3[9]}
			};

			JTable leaderboard = new JTable(data, colnames);
			frame.add(leaderboard.getTableHeader(), BorderLayout.PAGE_START);
			frame.add(leaderboard, BorderLayout.CENTER);

		}catch(FileNotFoundException f){		//in case Scores.txt does not yet exist (no high scores yet made)
			JTextArea message = new JTextArea("The previous scores could not be loaded. \n Try setting some high scores first!");
			frame.add(message, BorderLayout.CENTER);
		}

		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	/********************************************************************************************************
	 *
	 * Method:		actionPerformed
	 *
	 * Description:	Activates when the main menu button is clicked. Returns the user to the main menu.
	 *
	 * @param		e: a click on the main menu button
	 *
	 * @return		None
	 *
	 ********************************************************************************************************/
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == mainmenu){
			new MainMenu();
			frame.setVisible(false);
		}
	}
}


text:
<?php

namespace eatndrink;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    const CREATED_AT = 'date';

    protected $fillable = [
        'name', 'date', 'price', 'latitude', 'longitude', 'description', 'vegan', 'vegetarian', 'glutenfree', 'visible', 'user_uid_token'
    ];

    protected $hidden = [];

    public function user() {
        return $this->belongsTo(\eatndrink\User::class, 'user_uid_token', 'uid_token');
    }

    public function attendees() {
        return $this->hasMany(\eatndrink\Attendee::class);
    }
}


text:
<?php

namespace Tests\ConsoleHelpers\SVNBuddy\Repository\Connector;

use ConsoleHelpers\SVNBuddy\Exception\RepositoryCommandException;
use ConsoleHelpers\SVNBuddy\Repository\Connector\CommandFactory;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\Prophecy\ObjectProphecy;

class CommandFactoryTest extends TestCase
{

	/**
	 * Config editor.
	 *
	 * @var ObjectProphecy
	 */
	private $_configEditor;

	/**
	 * Console IO.
	 *
	 * @var ObjectProphecy
	 */
	private $_io;

	/**
	 * Process factory.
	 *
	 * @var ObjectProphecy
	 */
	private $_processFactory;

	/**
	 * Cache manager.
	 *
	 * @var ObjectProphecy
	 */
	private $_cacheManager;

	/**
	 * Command factory.
	 *
	 * @var CommandFactory
	 */
	private $_commandFactory;

	protected function setUp()
	{
		parent::setUp();

		$this->_configEditor = $this->prophesize('ConsoleHelpers\\ConsoleKit\\Config\\ConfigEditor');
		$this->_io = $this->prophesize('ConsoleHelpers\\ConsoleKit\\ConsoleIO');
		$this->_processFactory = $this->prophesize('ConsoleHelpers\\SVNBuddy\\Process\\IProcessFactory');
		$this->_cacheManager = $this->prophesize('ConsoleHelpers\\SVNBuddy\\Cache\\CacheManager');

		// To get nice exception back when unexpected command is executed.
		$this->_processFactory
			->createProcess(Argument::any(), 1200)
			->will(function (array $args) {
				throw new \LogicException('The createProcess("' . $args[0] . '", 1200) call wasn\'t expected.');
			});

		$this->_commandFactory = $this->_createCommandFactory('', '');
	}

	/**
	 * @dataProvider baseCommandBuildingDataProvider
	 */
	public function testBaseCommandBuilding($username, $password, $expected_command)
	{
		$repository_connector = $this->_createCommandFactory($username, $password);

		$this->_expectCommand($expected_command, 'OK');
		$this->assertEquals('OK', $repository_connector->getCommand('', '--version')->run());
	}

	public function baseCommandBuildingDataProvider()
	{
		return array(
			'no username, no password' => array('', '', 'svn --non-interactive --version'),
			'username, no password' => array('user', '', 'svn --non-interactive --username user --version'),
			'no username, password' => array('', 'pass', 'svn --non-interactive --password pass --version'),
			'username, password' => array(
				'user',
				'pass',
				'svn --non-interactive --username user --password pass --version',
			),
		);
	}

	public function testCommandWithoutSubCommand()
	{
		$this->_expectCommand('svn --non-interactive --version', 'OK');
		$this->assertEquals('OK', $this->_commandFactory->getCommand('', '--version')->run());
	}

	public function testCommandWithoutParams()
	{
		$this->_expectCommand('svn --non-interactive log', 'OK');
		$this->assertEquals('OK', $this->_commandFactory->getCommand('log')->run());
	}

	/**
	 * @expectedException \InvalidArgumentException
	 * @expectedExceptionMessage The "log -r 5" sub-command contains spaces.
	 */
	public function testSubCommandWithSpace()
	{
		$this->_commandFactory->getCommand('log -r 5')->run();
	}

	/**
	 * @dataProvider commandWithParamsDataProvider
	 */
	public function testCommandWithParams($params, $expected_command)
	{
		$this->_expectCommand($expected_command, 'OK');
		$this->assertEquals('OK', $this->_commandFactory->getCommand('log', $params)->run());
	}

	public function commandWithParamsDataProvider()
	{
		return array(
			'regular param' => array('-r 12', 'svn --non-interactive log -r 12'),
			'path param' => array('{path/to/folder}', "svn --non-interactive log 'path/to/folder'"),
			'regular and path param' => array(
				'-r 12 {path/to/folder}',
				"svn --non-interactive log -r 12 'path/to/folder'",
			),
		);
	}

	/**
	 * Sets expectation for specific command.
	 *
	 * @param string       $command    Command.
	 * @param string       $output     Output.
	 * @param string|null  $error_msg  Error msg.
	 * @param integer $error_code Error code.
	 */
	private function _expectCommand($command, $output, $error_msg = null, $error_code = 0)
	{
		$process = $this->prophesize('Symfony\\Component\\Process\\Process');

		$expectation = $process
			->mustRun(strpos($command, 'upgrade') !== false ? Argument::type('callable') : null)
			->shouldBeCalled();

		if ( isset($error_code) && isset($error_msg) ) {
			$expectation->willThrow(
				new RepositoryCommandException($command, 'svn: E' . $error_code . ': ' . $error_msg)
			);
		}
		else {
			$expectation->willReturn(null);
			$process->getOutput()->willReturn($output)->shouldBeCalled();
		}

		$this->_io->isVerbose()->willReturn(false);
		$this->_io->isDebug()->willReturn(false);

		$this->_processFactory->createProcess($command, 1200)->willReturn($process)->shouldBeCalled();
	}

	/**
	 * Creates command factory.
	 *
	 * @param string $username Username.
	 * @param string $password Password.
	 *
	 * @return CommandFactory
	 */
	private function _createCommandFactory($username, $password)
	{
		$this->_configEditor->get('repository-connector.username')->willReturn($username)->shouldBeCalled();
		$this->_configEditor->get('repository-connector.password')->willReturn($password)->shouldBeCalled();

		return new CommandFactory(
			$this->_configEditor->reveal(),
			$this->_processFactory->reveal(),
			$this->_io->reveal(),
			$this->_cacheManager->reveal()
		);
	}

}


text:
example-background-contourse fuses several of the ofxCv examples.

To get it working quickly, drag the project into the ofxCv examples folder.

Alterntaively, regenerate the project files for this location.


text:
//**************************************************************************************************
//
//     OSSIM Open Source Geospatial Data Processing Library
//     See top level LICENSE.txt file for license information
//
//**************************************************************************************************

#ifndef ossimAtpToolFactory_HEADER
#define ossimAtpToolFactory_HEADER 1

#include <ossim/plugin/ossimPluginConstants.h>
#include <ossim/util/ossimToolFactoryBase.h>

class ossimString;
class ossimFilename;
class ossimKeywordlist;

namespace ATP {

class OSSIM_PLUGINS_DLL ossimAtpToolFactory: public ossimToolFactoryBase
{
public:
   static ossimAtpToolFactory* instance();

   virtual ~ossimAtpToolFactory();
   virtual ossimTool* createTool(const std::string& typeName) const;
   virtual void getTypeNameList(std::vector<ossimString>& typeList) const;
   virtual void getCapabilities(std::map<std::string, std::string>& capabilities) const;
   virtual std::map<std::string, std::string> getCapabilities() const;

protected:
   ossimAtpToolFactory();
   ossimAtpToolFactory(const ossimAtpToolFactory&);
   void operator=(const ossimAtpToolFactory&);

   /** static instance of this class */
   static ossimAtpToolFactory* s_instance;

};
}
#endif /* end of #ifndef ossimAtpToolFactory_HEADER */


text:
namespace AngleSharp.Dom.Css
{
    using AngleSharp.Css;
    using AngleSharp.Extensions;
    using static AngleSharp.Css.Converters;

    /// <summary>
    /// More information available at:
    /// https://developer.mozilla.org/en-US/docs/CSS/transition
    /// </summary>
    sealed class CssTransitionProperty : CssShorthandProperty
    {
        #region Fields

        internal static readonly IValueConverter ListConverter = WithAny(
            AnimatableConverter.Option().For(PropertyNames.TransitionProperty),
            TimeConverter.Option().For(PropertyNames.TransitionDuration),
            TransitionConverter.Option().For(PropertyNames.TransitionTimingFunction),
            TimeConverter.Option().For(PropertyNames.TransitionDelay)).FromList().OrDefault();

        #endregion

        #region ctor

        internal CssTransitionProperty()
            : base(PropertyNames.Transition)
        {
        }

        #endregion

        #region Properties

        internal override IValueConverter Converter
        {
            get { return ListConverter; }
        }

        #endregion
    }
}


text:
<component name="libraryTable">
  <library name="SBT: org.springframework:spring-core:4.0.3.RELEASE">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.springframework/spring-core/jars/spring-core-4.0.3.RELEASE.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
TODO 24

                <input type="text" class="form-control list-name-input" ng-change="saveData()" ng-model="listValue.name">

                <button class="btn remove-list-button" ng-click="deleteList(listKey)">X</button>

                    <input type="text" class="form-control" ng-change="saveData()" ng-model="value.task">

                    <input type="checkbox" class="form-control" ng-change="saveData()" ng-model="value.done">

                    <button class="btn" ng-click="deleteElement(key,listKey)">X</button>

        <button class="btn add-element-button" ng-click="addElement(listKey)">Add element</button>

		<button class="btn " ng-click="addNewList()">ADD NEW LIST</button>

Open source AngularJS application by jlewek.pl.


text:
DELETE FROM abc;
PRAGMA wal_checkpoint;


text:
Replicate an existing security group rule to generate a new rule. When replicating a security group rule, you can make changes so that it is not a perfect copy.

## Procedure

1.  Log in to the management console.
2.  Click  ![](figures/icon-region.png)  in the upper left corner and select the desired region and project.
3.  On the console homepage, under  **Network**, click  **Virtual Private Cloud**.
4.  In the navigation pane on the left, choose  **Access Control**  \>  **Security Groups**.
5.  On the  **Security Groups**  page, click the security group name.
6.  On the displayed page, locate the row that contains the security group rule to be replicated, and click  **Replicate**  in the  **Operation**  column.

    You can modify the security group rule as required to quickly generate a new rule.

7.  Click  **OK**.


text:
[![Build Status](https://travis-ci.org/noentiger/react-portfolio.svg?branch=master)](https://travis-ci.org/noentiger/react-portfolio)  [![Dependency Status](https://david-dm.org/noentiger/react-portfolio.svg)](https://david-dm.org/noentiger/react-portfolio)  [![devDependency Status](https://david-dm.org/noentiger/react-portfolio/dev-status.svg)](https://david-dm.org/noentiger/react-portfolio#info=devDependencies)  [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)  [![Join the chat at https://gitter.im/noentiger/react-portfolio](https://badges.gitter.im/noentiger/react-portfolio.svg)](https://gitter.im/noentiger/react-portfolio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

### Getting started
```bash
git clone https://github.com/noentiger/react-portfolio && cd $_
yarn
yarn start

# Open localhost:5000
```

#### Under the Hood
 - [Node.js](https://nodejs.org/en/)
 - [Express](https://github.com/expressjs/express)
 - [React](https://github.com/facebook/react)
 - [Redux](https://github.com/reactjs/redux)
 - [React Router](https://github.com/reactjs/react-router) 2.0
 - [Aphrodite](https://github.com/Khan/aphrodite) for CSS by Khan Academy
 - [React Helmet](https://github.com/nfl/react-helmet) for meta tags by the NFL
 - [Redial](https://github.com/markdalgleish/redial) for data fetching by [@markdalgleish](https://twitter.com/markdalgleish)
 - [Babel 6](https://github.com/babel/babel)
 - [Webpack](https://github.com/webpack/webpack) with vanilla Hot Module Replacement

Based on [react-production-starter](https://github.com/jaredpalmer/react-production-starter)


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.awa.tech</groupId>
    <artifactId>learn-all</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>
  <groupId>org.awa.tech</groupId>
  <artifactId>learn-javase</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <name>learn-javase</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
package com.jetbrains.python.psi;

import org.jetbrains.annotations.Nullable;

/**
 * @author yole
 */
public interface PyContinueStatement extends PyStatement {
  @Nullable
  PyLoopStatement getLoopStatement();
}


text:
package http

import (
	"html/template"
	h "net/http"
	"strconv"

	"github.com/Jay-AHR/qpid_em"
	"github.com/gorilla/mux"
)

// Server is an HTTP server that controls
// the cook
type Server struct {
	controller qpid.CookController
	alerter    qpid.AlertSink
	notifier   qpid.NotificationSink
	metricer   qpid.MetricSink
	router     *mux.Router
}

// NewServer returns an initialized Server
func NewServer(c qpid.CookController,
	a qpid.AlertSink,
	n qpid.NotificationSink,
	m qpid.MetricSink) *Server {
	r := mux.NewRouter()
	s := &Server{
		controller: c,
		alerter:    a,
		notifier:   n,
		metricer:   m,
		router:     r,
	}
	return s
}

// ListenAndServe starts an HTTP listener at address `addr`,
// blocking until it's stopped
func (s *Server) ListenAndServe(addr string) error {

	s.router.HandleFunc("/", s.Index).Methods("GET")
	s.router.HandleFunc("/run", s.Run).Methods("POST")
	s.router.HandleFunc("/status", s.Status).Methods("GET")
	err := h.ListenAndServe(addr, s.router)
	return err

}

// Index serves the / route
func (s *Server) Index(w h.ResponseWriter, r *h.Request) {
	t, err := template.New("index").Parse(indexT)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	t.Execute(w, nil)
}

// Run starts a cook
func (s *Server) Run(w h.ResponseWriter, r *h.Request) {
	t := r.PostFormValue("temp")
	if t == "" {
		w.WriteHeader(400)
		w.Write([]byte("Temperature not provided"))
		return
	}
	tf, err := strconv.Atoi(t)
	if err != nil {
		w.WriteHeader(400)
		w.Write([]byte("Can't parse temperature as a number"))
		return
	}
	temp := qpid.TempFromF(tf)
	s.controller.GrillMonitor().Target(temp) //ignoring return temp and error TODO

	// start that cook!

	s.controller.GrillMonitor().Target(temp)

	// TODO done channel on all listeners and runner
	go s.notifier.Listen(s.controller.Notifications())

	go s.metricer.Listen(s.controller.Metrics())

	go s.alerter.Listen(s.controller.GrillMonitor().Alerts())
	go s.controller.Run()

	h.Redirect(w, r, "/status", h.StatusSeeOther)
	return
}

// Status serves the /status route
func (s *Server) Status(w h.ResponseWriter, r *h.Request) {
	t, err := template.New("status").Parse(statusT)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	status, err := s.controller.Status()
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	t.Execute(w, status)
}


text:
package org.usfirst.frc.team1736.lib.WebServer;

import javax.servlet.annotation.WebServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

@SuppressWarnings("serial")
@WebServlet(name = "Casserole Real-time Plotting Data Streamer Servlet", urlPatterns = {"/rtplot"})
class CasseroleRTPlotStreamerServlet extends WebSocketServlet {

    @Override
    public void configure(WebSocketServletFactory factory) {
        factory.getPolicy().setIdleTimeout(999999999); // I really don't want a timeout, and dont
                                                       // care if it stays open indefinitely...
        factory.register(CasseroleRTPlotStreamerSocket.class);
    }
}


text:
package com.amazonaws.services.mgn.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.mgn.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * VcenterClient JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class VcenterClientJsonUnmarshaller implements Unmarshaller<VcenterClient, JsonUnmarshallerContext> {

    public VcenterClient unmarshall(JsonUnmarshallerContext context) throws Exception {
        VcenterClient vcenterClient = new VcenterClient();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("arn", targetDepth)) {
                    context.nextToken();
                    vcenterClient.setArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("datacenterName", targetDepth)) {
                    context.nextToken();
                    vcenterClient.setDatacenterName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("hostname", targetDepth)) {
                    context.nextToken();
                    vcenterClient.setHostname(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("lastSeenDatetime", targetDepth)) {
                    context.nextToken();
                    vcenterClient.setLastSeenDatetime(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("sourceServerTags", targetDepth)) {
                    context.nextToken();
                    vcenterClient.setSourceServerTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
                            .getUnmarshaller(String.class)).unmarshall(context));
                }
                if (context.testExpression("tags", targetDepth)) {
                    context.nextToken();
                    vcenterClient.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context.getUnmarshaller(String.class))
                            .unmarshall(context));
                }
                if (context.testExpression("vcenterClientID", targetDepth)) {
                    context.nextToken();
                    vcenterClient.setVcenterClientID(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("vcenterUUID", targetDepth)) {
                    context.nextToken();
                    vcenterClient.setVcenterUUID(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return vcenterClient;
    }

    private static VcenterClientJsonUnmarshaller instance;

    public static VcenterClientJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new VcenterClientJsonUnmarshaller();
        return instance;
    }
}


text:
from __future__ import print_function

import os, sys
from enum import Enum

try:
    import ConfigParser
except ImportError:
    import configparser as ConfigParser

class LfTest:
    NETWORK_NAME = '<NETWORK-NAME>'
    NETWORK_KEY = '<NETWORK-KEY>'
    SITE_ID = '<SITE-ID>'
    SITE_KEY = '<SITE-KEY>'
    COLLECTION_ID = '<COLLECTION-ID>'
    USER_ID = '<USER-ID>'
    ARTICLE_ID = '<ARTICLE-ID>'
    TITLE = 'PythonTest'
    URL = 'http://answers.livefyre.com/PYTHON'

    def setUp(self):
        self.set_prop_values(LfEnvironments.PROD)

    def set_prop_values(self, env):
        config = ConfigParser.RawConfigParser()
        #try loading from file first
        try:
            config.read('test.ini')

            self.NETWORK_NAME = config.get(env.value, 'NETWORK_NAME')
            self.NETWORK_KEY = config.get(env.value, 'NETWORK_KEY')
            self.SITE_ID = config.get(env.value, 'SITE_ID')
            self.SITE_KEY = config.get(env.value, 'SITE_KEY')
            self.COLLECTION_ID = config.get(env.value, 'COLLECTION_ID')
            self.USER_ID = config.get(env.value, 'USER_ID')
            self.ARTICLE_ID = config.get(env.value, 'ARTICLE_ID')
            return
        except:
            pass

        #next try loading circle ci defaults
        try:
            self.NETWORK_NAME = os.environ.get('NETWORK_NAME')
            self.NETWORK_KEY = os.environ.get('NETWORK_KEY')
            self.SITE_ID = os.environ.get('SITE_ID')
            self.SITE_KEY = os.environ.get('SITE_KEY')
            self.COLLECTION_ID = os.environ.get('COLLECTION_ID')
            self.USER_ID = os.environ.get('USER_ID')
            self.ARTICLE_ID = os.environ.get('ARTICLE_ID')
        except:
            print('no set values have been found!', file=sys.stderr)

class LfEnvironments(Enum):
    QA = 'qa'
    UAT = 'uat'
    PROD = 'prod'


text:
<!DOCTYPE html>

  <title>PACER Court software versions</title>
  <link rel="stylesheet" type="text/css" href="/static/style.css"/>

PACER court software versions

    This is a list of reported software versions for the electronic filing
    (PACER) systems of various US courts.

    The records are
    scraped daily.
    There is also a JSON feed of the data available.

    The scraper and the source for this website was written by
    Travis Briggs in Python and is
    available on
    GitHub. Pull requests welcome!

  {% for name, group in all_courts.items() %}

      {{ name }}

        Court
        Software version
        Software Go Live Date

      {% for court in group['courts'] %}

              {{ court['court'] }}

            {% if court['software_version'] %}

              {{ court['software_version'] }}

            {% else %}
            --
            {% endif %}

            {% if court['software_go_live'] %}

              {{ court['software_go_live'] }}

            {% else %}
            --
            {% endif %}

      {% endfor %}

  {% endfor %}


text:
_lcl_component(Main,            "main",             "Main")
_lcl_component(MainComponent1,  "main.component1",  "Main/Component1")
_lcl_component(MainComponent2,  "main.component2",  "Main/Component2")

_lcl_component(Main2,           "main2",            "Main2")

_lcl_component(Main3,           "main3",            "Main3")