text:
namespace chromeos {

namespace sync_wifi {

namespace {

std::unique_ptr<syncer::EntityData> GenerateWifiEntityData(
    const sync_pb::WifiConfigurationSpecifics& proto) {
  auto entity_data = std::make_unique<syncer::EntityData>();
  entity_data->specifics.mutable_wifi_configuration()->CopyFrom(proto);
  entity_data->name = NetworkIdentifier::FromProto(proto).SerializeToString();
  return entity_data;
}

// Delay before attempting to save a newly configured network to sync.  This
// is to give time for an initial connection attempt to fail in case of a bad
// password, which will prevent syncing.
constexpr base::TimeDelta kSyncAfterCreatedTimeout = base::Seconds(20);

}  // namespace

WifiConfigurationBridge::WifiConfigurationBridge(
    SyncedNetworkUpdater* synced_network_updater,
    LocalNetworkCollector* local_network_collector,
    NetworkConfigurationHandler* network_configuration_handler,
    SyncedNetworkMetricsLogger* metrics_recorder,
    TimerFactory* timer_factory,
    PrefService* pref_service,
    std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor,
    syncer::OnceModelTypeStoreFactory create_store_callback)
    : ModelTypeSyncBridge(std::move(change_processor)),
      synced_network_updater_(synced_network_updater),
      local_network_collector_(local_network_collector),
      network_configuration_handler_(network_configuration_handler),
      metrics_recorder_(metrics_recorder),
      timer_factory_(timer_factory),
      pref_service_(pref_service),
      network_metadata_store_(nullptr) {
  std::move(create_store_callback)
      .Run(syncer::WIFI_CONFIGURATIONS,
           base::BindOnce(&WifiConfigurationBridge::OnStoreCreated,
                          weak_ptr_factory_.GetWeakPtr()));
  if (network_configuration_handler_) {
    network_configuration_handler_->AddObserver(this);
  }
}

WifiConfigurationBridge::~WifiConfigurationBridge() {
  OnShuttingDown();
}

// static
void WifiConfigurationBridge::RegisterPrefs(PrefRegistrySimple* registry) {
  registry->RegisterBooleanPref(kIsFirstRun, true);
  registry->RegisterBooleanPref(kHasFixedAutoconnect, false);
}

void WifiConfigurationBridge::OnShuttingDown() {
  if (network_metadata_store_) {
    network_metadata_store_->RemoveObserver(this);
    network_metadata_store_ = nullptr;
  }
  if (network_configuration_handler_) {
    network_configuration_handler_->RemoveObserver(this);
    network_configuration_handler_ = nullptr;
  }
}

std::unique_ptr<syncer::MetadataChangeList>
WifiConfigurationBridge::CreateMetadataChangeList() {
  return syncer::ModelTypeStore::WriteBatch::CreateMetadataChangeList();
}

absl::optional<syncer::ModelError> WifiConfigurationBridge::MergeSyncData(
    std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
    syncer::EntityChangeList change_list) {
  DCHECK(entries_.empty());
  DCHECK(local_network_collector_);

  local_network_collector_->GetAllSyncableNetworks(
      base::BindOnce(&WifiConfigurationBridge::OnGetAllSyncableNetworksResult,
                     weak_ptr_factory_.GetWeakPtr(),
                     std::move(metadata_change_list), std::move(change_list)));

  return absl::nullopt;
}

void WifiConfigurationBridge::OnGetAllSyncableNetworksResult(
    std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
    syncer::EntityChangeList change_list,
    std::vector<sync_pb::WifiConfigurationSpecifics> local_network_list) {
  // To merge local and synced networks we add all local networks that don't
  // exist in sync to the server and all synced networks that don't exist
  // locally to Shill.  For networks which exist on both lists, we compare the
  // last connected timestamp and take the newer configuration.

  NET_LOG(EVENT) << "Merging " << local_network_list.size() << " local and "
                 << change_list.size() << " synced networks.";
  base::flat_map<NetworkIdentifier, sync_pb::WifiConfigurationSpecifics>
      sync_networks;
  base::flat_map<NetworkIdentifier, sync_pb::WifiConfigurationSpecifics>
      local_networks;

  // Iterate through incoming changes from sync and populate the sync_networks
  // map.
  for (std::unique_ptr<syncer::EntityChange>& change : change_list) {
    if (change->type() == syncer::EntityChange::ACTION_DELETE) {
      // Don't delete any local networks during the initial merge when sync is
      // first enabled.
      continue;
    }

    const sync_pb::WifiConfigurationSpecifics& proto =
        change->data().specifics.wifi_configuration();
    NetworkIdentifier id = NetworkIdentifier::FromProto(proto);
    if (sync_networks.contains(id) &&
        sync_networks[id].last_connected_timestamp() >
            proto.last_connected_timestamp()) {
      continue;
    }
    sync_networks[id] = proto;
  }

  // Iterate through local networks and add to sync where appropriate.
  for (sync_pb::WifiConfigurationSpecifics& proto : local_network_list) {
    NetworkIdentifier id = NetworkIdentifier::FromProto(proto);
    if (sync_networks.contains(id) &&
        sync_networks[id].last_connected_timestamp() >
            proto.last_connected_timestamp()) {
      continue;
    }

    local_networks[id] = proto;
    std::unique_ptr<syncer::EntityData> entity_data =
        GenerateWifiEntityData(proto);
    std::string storage_key = GetStorageKey(*entity_data);

    // Upload the local network configuration to sync.  This could be a new
    // configuration or an update to an existing one.
    change_processor()->Put(storage_key, std::move(entity_data),
                            metadata_change_list.get());
    entries_[storage_key] = proto;
  }

  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> batch =
      store_->CreateWriteBatch();
  // Iterate through synced networks and update local stack where appropriate.
  for (auto& kv : sync_networks) {
    NetworkIdentifier& id = kv.first;
    sync_pb::WifiConfigurationSpecifics& proto = kv.second;

    if (local_networks.contains(id) &&
        local_networks[id].last_connected_timestamp() >
            proto.last_connected_timestamp()) {
      continue;
    }

    // Update the local network stack to have the synced network configuration.
    synced_network_updater_->AddOrUpdateNetwork(proto);

    // Save the proto to the sync data store to keep track of all synced
    // networks on device.  This gets loaded into |entries_| next time the
    // bridge is initialized.
    batch->WriteData(id.SerializeToString(), proto.SerializeAsString());
    entries_[id.SerializeToString()] = proto;
  }

  // Mark the changes as processed.
  batch->TakeMetadataChangesFrom(std::move(metadata_change_list));
  Commit(std::move(batch));
  metrics_recorder_->RecordTotalCount(entries_.size());
  // If zero networks are synced log the reason.
  if (entries_.size() == 0) {
    local_network_collector_->RecordZeroNetworksEligibleForSync();
  }
}

absl::optional<syncer::ModelError> WifiConfigurationBridge::ApplySyncChanges(
    std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
    syncer::EntityChangeList entity_changes) {
  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> batch =
      store_->CreateWriteBatch();

  NET_LOG(EVENT) << "Applying  " << entity_changes.size()
                 << " pending changes.";

  // TODO(jonmann) Don't override synced network configurations that are newer
  // than the local configurations.
  for (std::unique_ptr<syncer::EntityChange>& change : entity_changes) {
    if (change->type() == syncer::EntityChange::ACTION_DELETE) {
      auto it = entries_.find(change->storage_key());
      if (it != entries_.end()) {
        entries_.erase(it);
        batch->DeleteData(change->storage_key());
        if (!base::FeatureList::IsEnabled(features::kWifiSyncApplyDeletes)) {
          // Don't apply deletes to the local device.
          NET_LOG(EVENT) << "Ignoring delete request from sync server.";
          continue;
        }
        synced_network_updater_->RemoveNetwork(
            NetworkIdentifier::DeserializeFromString(change->storage_key()));
      } else {
        NET_LOG(EVENT) << "Received delete request for network which is not "
                          "tracked by sync.";
      }
      continue;
    }

    auto& specifics = change->data().specifics.wifi_configuration();
    synced_network_updater_->AddOrUpdateNetwork(specifics);

    batch->WriteData(change->storage_key(), specifics.SerializeAsString());
    entries_[change->storage_key()] = std::move(specifics);
  }

  batch->TakeMetadataChangesFrom(std::move(metadata_change_list));
  Commit(std::move(batch));
  metrics_recorder_->RecordTotalCount(entries_.size());
  // If zero networks are synced log the reason.
  if (entries_.size() == 0) {
    local_network_collector_->RecordZeroNetworksEligibleForSync();
  }

  return absl::nullopt;
}

void WifiConfigurationBridge::GetData(StorageKeyList storage_keys,
                                      DataCallback callback) {
  auto batch = std::make_unique<syncer::MutableDataBatch>();

  for (const std::string& id : storage_keys) {
    auto it = entries_.find(id);
    if (it == entries_.end()) {
      continue;
    }
    batch->Put(id, GenerateWifiEntityData(it->second));
  }
  std::move(callback).Run(std::move(batch));
}

void WifiConfigurationBridge::GetAllDataForDebugging(DataCallback callback) {
  auto batch = std::make_unique<syncer::MutableDataBatch>();
  for (const auto& entry : entries_) {
    batch->Put(entry.first, GenerateWifiEntityData(entry.second));
  }
  std::move(callback).Run(std::move(batch));
}

std::string WifiConfigurationBridge::GetClientTag(
    const syncer::EntityData& entity_data) {
  return GetStorageKey(entity_data);
}

std::string WifiConfigurationBridge::GetStorageKey(
    const syncer::EntityData& entity_data) {
  return NetworkIdentifier::FromProto(
             entity_data.specifics.wifi_configuration())
      .SerializeToString();
}

void WifiConfigurationBridge::OnStoreCreated(
    const absl::optional<syncer::ModelError>& error,
    std::unique_ptr<syncer::ModelTypeStore> store) {
  if (error) {
    change_processor()->ReportError(*error);
    return;
  }

  store_ = std::move(store);
  store_->ReadAllData(base::BindOnce(&WifiConfigurationBridge::OnReadAllData,
                                     weak_ptr_factory_.GetWeakPtr()));
}

void WifiConfigurationBridge::OnReadAllData(
    const absl::optional<syncer::ModelError>& error,
    std::unique_ptr<syncer::ModelTypeStore::RecordList> records) {
  if (error) {
    change_processor()->ReportError(*error);
    return;
  }

  for (syncer::ModelTypeStore::Record& record : *records) {
    sync_pb::WifiConfigurationSpecifics data;
    if (record.id.empty() || !data.ParseFromString(record.value)) {
      NET_LOG(EVENT) << "Unable to parse proto for entry with key: "
                     << record.id;
      continue;
    }
    entries_[record.id] = std::move(data);
  }
  store_->ReadAllMetadata(
      base::BindOnce(&WifiConfigurationBridge::OnReadAllMetadata,
                     weak_ptr_factory_.GetWeakPtr()));

  // Temporary fix for networks which accidentally had autoconnect disabled.
  if (!pref_service_->GetBoolean(kHasFixedAutoconnect)) {
    local_network_collector_->ExecuteAfterNetworksLoaded(
        base::BindOnce(&WifiConfigurationBridge::FixAutoconnect,
                       weak_ptr_factory_.GetWeakPtr()));
  }

  int entries_size = entries_.size();
  // Do not log the total network count during OOBE. It returns 0 even if there
  // are networks synced since MergeSyncData has not executed yet.
  if (pref_service_->GetBoolean(kIsFirstRun)) {
    pref_service_->SetBoolean(kIsFirstRun, false);
    // This is only meant to filter out 0's that are logged during OOBE. If the
    // entries_size is greater than zero it should be logged.
    if (entries_size == 0) {
      return;
    }
  }
  metrics_recorder_->RecordTotalCount(entries_size);
  // If zero networks are synced log the reason.
  if (entries_size == 0) {
    local_network_collector_->RecordZeroNetworksEligibleForSync();
  }
}

void WifiConfigurationBridge::FixAutoconnect() {
  // Temporary fix for networks which accidentally had autoconnect disabled.
  if (!pref_service_->GetBoolean(kHasFixedAutoconnect)) {
    std::vector<sync_pb::WifiConfigurationSpecifics> protos;
    for (const auto& entry : entries_) {
      protos.push_back(entry.second);
    }
    local_network_collector_->FixAutoconnect(
        protos,
        base::BindOnce(&WifiConfigurationBridge::OnFixAutoconnectComplete,
                       weak_ptr_factory_.GetWeakPtr()));
  }
}

void WifiConfigurationBridge::OnFixAutoconnectComplete() {
  pref_service_->SetBoolean(kHasFixedAutoconnect, true);
}

void WifiConfigurationBridge::OnReadAllMetadata(
    const absl::optional<syncer::ModelError>& error,
    std::unique_ptr<syncer::MetadataBatch> metadata_batch) {
  if (error) {
    change_processor()->ReportError(*error);
    return;
  }
  change_processor()->ModelReadyToSync(std::move(metadata_batch));

  // Make a copy in case the map is modified while iterating over the pending
  // updates.  This could happen if sync is disabled while iterating.
  base::flat_map<std::string,
                 absl::optional<sync_pb::WifiConfigurationSpecifics>>
      updates = networks_to_sync_when_ready_;
  for (auto const& it : updates) {
    if (it.second) {
      SaveNetworkToSync(it.second);
      continue;
    }
    RemoveNetworkFromSync(it.first);
  }
  networks_to_sync_when_ready_.clear();
}

void WifiConfigurationBridge::OnCommit(
    const absl::optional<syncer::ModelError>& error) {
  if (error)
    change_processor()->ReportError(*error);
}

void WifiConfigurationBridge::Commit(
    std::unique_ptr<syncer::ModelTypeStore::WriteBatch> batch) {
  store_->CommitWriteBatch(std::move(batch),
                           base::BindOnce(&WifiConfigurationBridge::OnCommit,
                                          weak_ptr_factory_.GetWeakPtr()));
}

std::vector<NetworkIdentifier> WifiConfigurationBridge::GetAllIdsForTesting() {
  std::vector<NetworkIdentifier> ids;
  for (const auto& entry : entries_)
    ids.push_back(NetworkIdentifier::FromProto(entry.second));

  return ids;
}

void WifiConfigurationBridge::OnFirstConnectionToNetwork(
    const std::string& guid) {
  if (network_guid_to_timer_map_.contains(guid)) {
    network_guid_to_timer_map_.erase(guid);
  }

  if (network_metadata_store_->GetIsConfiguredBySync(guid)) {
    // Don't have to upload a configuration that came from sync.
    NET_LOG(EVENT) << "Not uploading network on first connect: "
                   << NetworkGuidId(guid) << " was added by sync.";
    return;
  }

  NET_LOG(EVENT) << "Syncing network after first connect: "
                 << NetworkGuidId(guid);
  local_network_collector_->GetSyncableNetwork(
      guid, base::BindOnce(&WifiConfigurationBridge::SaveNetworkToSync,
                           weak_ptr_factory_.GetWeakPtr()));
}

void WifiConfigurationBridge::OnNetworkUpdate(
    const std::string& guid,
    const base::Value* set_properties) {
  if (!set_properties)
    return;

  if (synced_network_updater_->IsUpdateInProgress(guid) ||
      network_metadata_store_->GetIsConfiguredBySync(guid)) {
    // Don't have to upload a configuration that came from sync.
    NET_LOG(EVENT) << "Not uploading change to " << NetworkGuidId(guid)
                   << ", modified network was configured "
                      "by sync.";
    return;
  }

  if (!set_properties->FindKey(shill::kAutoConnectProperty) &&
      !set_properties->FindKey(shill::kPriorityProperty) &&
      !set_properties->FindKey(shill::kProxyConfigProperty) &&
      !set_properties->FindKey(shill::kMeteredProperty) &&
      !set_properties->FindPath(
          base::StringPrintf("%s.%s", shill::kStaticIPConfigProperty,
                             shill::kNameServersProperty))) {
    NET_LOG(EVENT) << "Not uploading change to " << NetworkGuidId(guid)
                   << ", modified network field(s) are not synced.";
    return;
  }

  NET_LOG(EVENT) << "Updating sync with changes to " << NetworkGuidId(guid);
  local_network_collector_->GetSyncableNetwork(
      guid, base::BindOnce(&WifiConfigurationBridge::SaveNetworkToSync,
                           weak_ptr_factory_.GetWeakPtr()));
}

void WifiConfigurationBridge::SaveNetworkToSync(
    absl::optional<sync_pb::WifiConfigurationSpecifics> proto) {
  if (!proto) {
    return;
  }

  // If the sync backend hasn't finished initializing the bridge, then store
  // this update to be processed later.
  if (!store_ || !change_processor()->IsTrackingMetadata()) {
    networks_to_sync_when_ready_.insert_or_assign(
        NetworkIdentifier::FromProto(*proto).SerializeToString(), proto);
    return;
  }

  std::unique_ptr<syncer::EntityData> entity_data =
      GenerateWifiEntityData(*proto);
  auto id = NetworkIdentifier::FromProto(*proto);
  std::string storage_key = GetStorageKey(*entity_data);

  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> batch =
      store_->CreateWriteBatch();
  batch->WriteData(storage_key, proto->SerializeAsString());
  change_processor()->Put(storage_key, std::move(entity_data),
                          batch->GetMetadataChangeList());
  entries_[storage_key] = *proto;
  Commit(std::move(batch));
  NET_LOG(EVENT) << "Saved network "
                 << NetworkId(NetworkStateFromNetworkIdentifier(id))
                 << " to sync.";
  metrics_recorder_->RecordTotalCount(entries_.size());
  // If zero networks are synced log the reason.
  if (entries_.size() == 0) {
    local_network_collector_->RecordZeroNetworksEligibleForSync();
  }
}

void WifiConfigurationBridge::OnNetworkCreated(const std::string& guid) {
  network_guid_to_timer_map_[guid] = timer_factory_->CreateOneShotTimer();
  network_guid_to_timer_map_[guid]->Start(
      FROM_HERE, kSyncAfterCreatedTimeout,
      base::BindOnce(&WifiConfigurationBridge::OnNetworkConfiguredDelayComplete,
                     weak_ptr_factory_.GetWeakPtr(), guid));
}

void WifiConfigurationBridge::OnNetworkConfiguredDelayComplete(
    const std::string& network_guid) {
  if (network_guid_to_timer_map_.contains(network_guid)) {
    network_guid_to_timer_map_.erase(network_guid);
  }

  // This check to prevent uploading networks that were added by sync happens
  // after the delay because the metadata isn't available in OnNetworkCreated.
  if (network_metadata_store_->GetIsConfiguredBySync(network_guid)) {
    NET_LOG(EVENT) << "Not uploading newly configured network "
                   << NetworkGuidId(network_guid) << ", it was added by sync.";
    return;
  }

  NET_LOG(EVENT) << "Attempting to sync new network after delay.";
  local_network_collector_->GetSyncableNetwork(
      network_guid, base::BindOnce(&WifiConfigurationBridge::SaveNetworkToSync,
                                   weak_ptr_factory_.GetWeakPtr()));
}

void WifiConfigurationBridge::OnBeforeConfigurationRemoved(
    const std::string& service_path,
    const std::string& guid) {
  if (!base::FeatureList::IsEnabled(features::kWifiSyncAllowDeletes)) {
    return;
  }

  absl::optional<NetworkIdentifier> id =
      local_network_collector_->GetNetworkIdentifierFromGuid(guid);
  if (!id) {
    return;
  }

  NET_LOG(EVENT) << "Storing metadata for " << NetworkPathId(service_path)
                 << " in preparation for removal.";
  pending_deletes_[guid] = id->SerializeToString();
}

void WifiConfigurationBridge::OnConfigurationRemoved(
    const std::string& service_path,
    const std::string& network_guid) {
  if (!base::FeatureList::IsEnabled(features::kWifiSyncAllowDeletes)) {
    return;
  }

  if (!pending_deletes_.contains(network_guid)) {
    NET_LOG(EVENT) << "Configuration " << network_guid
                   << " removed with no matching saved metadata.";
    return;
  }

  const std::string& storage_key = pending_deletes_[network_guid];
  if (!store_ || !change_processor()->IsTrackingMetadata()) {
    networks_to_sync_when_ready_.insert_or_assign(storage_key, absl::nullopt);
    return;
  }

  RemoveNetworkFromSync(storage_key);
}

void WifiConfigurationBridge::RemoveNetworkFromSync(
    const std::string& storage_key) {
  if (!base::FeatureList::IsEnabled(features::kWifiSyncAllowDeletes)) {
    return;
  }
  if (!entries_.contains(storage_key)) {
    return;  // Network is not synced.
  }

  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> batch =
      store_->CreateWriteBatch();
  batch->DeleteData(storage_key);
  change_processor()->Delete(storage_key, batch->GetMetadataChangeList());
  entries_.erase(storage_key);
  Commit(std::move(batch));
  NET_LOG(EVENT) << "Removed network from sync.";
}

void WifiConfigurationBridge::SetNetworkMetadataStore(
    base::WeakPtr<NetworkMetadataStore> network_metadata_store) {
  if (network_metadata_store_) {
    network_metadata_store->RemoveObserver(this);
  }
  network_metadata_store_ = network_metadata_store;
  network_metadata_store->AddObserver(this);
}

}  // namespace sync_wifi

}  // namespace chromeos


text:
var hasProp = Object.prototype.hasOwnProperty

module.exports = has

function has(obj, key) {
    return hasProp.apply(obj, key)
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Rep. Tottori Mycol. Inst. 10: 221 (1973)

#### Original name
Cronartium aleanum Syd. & P. Syd.

### Remarks
null


text:
package org.elasticsearch.join.aggregations;

public abstract class JoinAggregationBuilders {
    /**
     * Create a new {@link Children} aggregation with the given name.
     */
    public static ChildrenAggregationBuilder children(String name, String childType) {
        return new ChildrenAggregationBuilder(name, childType);
    }

    /**
     * Create a new {@link Parent} aggregation with the given name.
     */
    public static ParentAggregationBuilder parent(String name, String childType) {
        return new ParentAggregationBuilder(name, childType);
    }
}


text:
CREATE TABLE `activity_log` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `_last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `date` datetime DEFAULT NULL,
  `type` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq1` (`date`,`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;


text:
package com.fincatto.documentofiscal.cte300.classes.nota;

import com.fincatto.documentofiscal.DFBase;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;

import java.util.List;

/**
 * @author Caio
 * @info Informações do Serviço Vinculado a Multimodal
 */

@Root(name = "infServVinc")
@Namespace(reference = "http://www.portalfiscal.inf.br/cte")
public class CTeNotaInfoCTeNormalInfoServicoVinculado extends DFBase {
    private static final long serialVersionUID = -2130925317280973601L;

    @ElementList(name = "infCTeMultimodal", inline = true)
    private List<CTeNotaInfoCTeNormalInfoServicoVinculadoInfoCTeMultiModal> infoCTeMultiModal;

    public CTeNotaInfoCTeNormalInfoServicoVinculado() {
        this.infoCTeMultiModal = null;
    }

    public List<CTeNotaInfoCTeNormalInfoServicoVinculadoInfoCTeMultiModal> getInfoCTeMultiModal() {
        return this.infoCTeMultiModal;
    }

    /**
     * informações do CT-e multimodal vinculado
     */
    public void setInfoCTeMultiModal(final List<CTeNotaInfoCTeNormalInfoServicoVinculadoInfoCTeMultiModal> infoCTeMultiModal) {
        this.infoCTeMultiModal = infoCTeMultiModal;
    }
}


text:
package com.androidformenhancer.validator;

import com.androidformenhancer.R;
import com.androidformenhancer.annotation.Katakana;

/**
 * Validates that the value of the field consists of Japanese katakana
 * characters or not.
 *
 * @author Soichiro Kashima
 */
public class KatakanaValidator extends AbstractRegexValidator<Katakana> {

    private static final String REGEX = "^[アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンャュョッァィゥェォヵヶガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポヴー、。]+$";

    @Override
    public Class<Katakana> getAnnotationClass() {
        return Katakana.class;
    }

    @Override
    protected String getRegex(final Katakana annotation) {
        return REGEX;
    }

    @Override
    protected int getOverrideNameResourceId(final Katakana annotation) {
        return annotation.nameResId();
    }

    @Override
    protected int getErrorMessageResourceId() {
        return R.string.afe__msg_validation_katakana;
    }

    @Override
    protected int getNameStyleIndex() {
        return R.styleable.ValidatorMessages_afeErrorKatakana;
    }

}


text:
class B { def m: Int = 0 }
class C extends B { override def m = 4 }
trait T1 extends B { override def m = 1 }
trait T2 extends T1 { override def m = 2 }
trait T3 extends T1 { override def m = 3 }

trait T4 extends T1
class D extends B {
  def f() = println(super[B].m)
}

object Test extends C with T2 with T3 with T4 {
  def main(args: Array[String]): Unit = {
    println(m)
    println(super[T2].m)
    println(super[T3].m)
    println(super[T4].m)
    new D().f()
  }
}


text:
import sys
import json
import KrakenConnector
from CredentialMgr import Credential_Mgr
from RequestMgr import Request_Mgr
from PublicApiRequests import *
from PrivateApiRequests import *

def main(argv):
    public_request()
    private_request()
    return

##################################################################
### Short example of how to use the api for a private request ####
##################################################################

def private_request():
    cre_mgr = Credential_Mgr()
    try:
        if not cre_mgr.encrypt_keys(in_file="KrakenKey.txt", pwd="Test"):
            print "Encryption failed"
            return
    except Exception as e:
        print e
        return

    if cre_mgr.load_credentials(tbk_file="KrakenKey.tbk", pwd="Test"):
        print 'Loading keys successfull'
    else:
        print 'Loading keys failed'
        return

    req_mgr = Request_Mgr(3)
    req_mgr.set_keys(cre_mgr)
    req = Request_Balance()

    if not req_mgr.send_request(req):
        if req.has_errors:
            print req.errors
    else:
        print req.raw_response

#################################################################
### Short example of how to use the api for a public request ####
#################################################################

def public_request():
    req_mgr = Request_Mgr(3)
    req = Request_Time()
    if not req_mgr.send_request(req):
       if req.has_errors:
            print req.errors
    else:
        print req.raw_response

if __name__ == "__main__":
    main(sys.argv)


text:
function main(kayn) {
    kayn.Match.get(2877485196).callback(function(err, match) {
        const bans = match.teams
            .map(function(m) {
                return m.bans
            })
            .reduce(function(t, c) {
                return t.concat(c)
            }, [])
        const ids = bans.map(function(b) {
            return b.championId
        })
        kayn.DDragon.Champion.listDataByIdWithParentAsId().callback(function(
            err,
            list,
        ) {
            const champions = []
            for (let i = 0; i < ids.length; ++i) {
                champions.push(list.data[ids[i]])
            }
            console.log(champions)
        })
    })
}

module.exports = main


text:
SegsOriginEditor::SegsOriginEditor(QWidget *parent) :
    EditorWidget(parent),
    ui(new Ui::SegsOriginEditor)
{
    ui->setupUi(this);
    auto origin_list = new QStringListModel(this);
    m_origins = origin_list;
    origin_list->setStringList({"Test","Test2"});

    ui->OriginPowerslistView->setModel(m_origins);
}

SegsOriginEditor::~SegsOriginEditor()
{
    delete ui;
}

void SegsOriginEditor::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void SegsOriginEditor::on_actionOpen_triggered()
{

}

void SegsOriginEditor::on_actionSave_triggered()
{

}

void SegsOriginEditor::on_OriginPowerslistView_activated(const QModelIndex &index)
{
    if(index.isValid()) {
        qDebug() << "Model entry selected" << m_origins->data(index).toString();
    }
}


text:
/*
 * @test
 * @bug 4979456
 * @summary NPE while compiling static import of inaccessible class member
 * @author gafter
 *
 * @compile/fail  ImportPrivate.java
 */

package importPrivate;

import static importPrivate.A.m;

class A {
    private static int m() {
        return 8;
    }
}

class MyTest {
    public static void main(String argv[]) {
        m();
    }
}


text:
#region Imports

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

using P3Net.Kraken.Data.Common;
using P3Net.Kraken.UnitTesting;
#endregion

namespace Tests.P3Net.Kraken.Data.Common
{
    [TestClass]
    public class DataParameterTests : UnitTest
    {
        #region Ctor

        [TestMethod]
        public void Ctor_WithName ()
        {
            //Act
            var target = new DataParameter("@p1", DbType.Int32);

            //Assert
            target.Name.Should().Be("@p1");
            target.DbType.Should().Be(DbType.Int32);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void Ctor_NameIsEmpty ()
        {
            //Act
            new DataParameter("", DbType.Int32);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Ctor_NameIsNull ()
        {
            //Act
            new DataParameter(null, DbType.Int32);
        }
        #endregion

        #region Name

        [TestMethod]
        public void Name_SetValid ()
        {
            var expected = "in3";

            //Act
            var target = new DataParameter("p1", DbType.Int32);
            target.Name = expected;

            //Assert
            target.Name.Should().Be(expected);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Name_SetNull ()
        {
            var target = new DataParameter("p1", DbType.Int32);
            target.Name = null;
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void Name_SetEmpty ()
        {
            var target = new DataParameter("p1", DbType.Int32);
            target.Name = "";
        }

        [TestMethod]
        public void Name_FormattingRemains ()
        {
            var expected = "@p1";

            //Act
            var target = new DataParameter(expected, DbType.String);

            //Assert
            target.Name.Should().Be(expected);
        }
        #endregion

        #region Precision

        [TestMethod]
        public void Precision_SetValidSingle ()
        {
            int expected = 12;

            //Act
            var target = new DataParameter("p1", DbType.Single);
            target.Precision = expected;

            //Assert
            target.HasPrecision.Should().BeTrue();
            target.Precision.Should().Be(expected);
        }

        [TestMethod]
        public void Precision_SetValidDouble ()
        {
            int expected = 40;

            //Act
            var target = new DataParameter("p1", DbType.Double);
            target.Precision = expected;

            //Assert
            target.HasPrecision.Should().BeTrue();
            target.Precision.Should().Be(expected);
        }

        [TestMethod]
        public void Precision_SetValidOther ()
        {
            int expected = 30;

            //Act
            var target = new DataParameter("p1", DbType.Int64);
            target.Precision = expected;

            //Assert
            target.HasPrecision.Should().BeTrue();
            target.Precision.Should().Be(expected);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Precision_SetSingleOutOfRange ()
        {
            int expected = 40;

            //Act
            var target = new DataParameter("p1", DbType.Single);
            target.Precision = expected;
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Precision_SetDoubleOutOfRange ()
        {
            int expected = 100;

            //Act
            var target = new DataParameter("p1", DbType.Double);
            target.Precision = expected;
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Precision_SetOtherOutOfRange ()
        {
            int expected = 40;

            //Act
            var target = new DataParameter("p1", DbType.Int64);
            target.Precision = expected;
        }

        [TestMethod]
        public void Precision_NotSet ()
        {
            var target = new DataParameter("p1", DbType.Int32);

            //Assert
            target.HasPrecision.Should().BeFalse();
            target.Precision.Should().Be(0);
        }
        #endregion

        #region Scale

        [TestMethod]
        public void Scale_SetValid ()
        {
            var expected = 10;

            //Act
            var target = new DataParameter("p1", DbType.Int32);
            target.Scale = expected;

            //Assert
            target.HasScale.Should().BeTrue();
            target.Scale.Should().Be(expected);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Scale_SetOutOfRange ()
        {
            //Act
            var target = new DataParameter("p1", DbType.Int32);
            target.Scale = -1;
        }

        [TestMethod]
        public void Scale_NotSet ()
        {
            var target = new DataParameter("p1", DbType.Int32);

            //Assert
            target.HasScale.Should().BeFalse();
            target.Scale.Should().Be(0);
        }
        #endregion

        #region Size

        [TestMethod]
        public void Size_SetValid ()
        {
            var expected = 100;

            //Act
            var target = new DataParameter("p1", DbType.String);
            target.Size = expected;

            //Assert
            target.HasSize.Should().BeTrue();
            target.Size.Should().Be(expected);
        }

        [TestMethod]
        public void Size_SetMaximum ()
        {
            var expected = -1;

            //Act
            var target = new DataParameter("p1", DbType.String);
            target.Size = expected;

            //Assert
            target.Size.Should().Be(expected);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Size_SetOutOfRange ()
        {
            //Act
            var target = new DataParameter("p1", DbType.String);
            target.Size = -2;
        }

        [TestMethod]
        public void Size_NotSet ()
        {
            var target = new DataParameter("p1", DbType.Int32);

            //Assert
            target.HasSize.Should().BeFalse();
            target.Size.Should().Be(-1);
        }
        #endregion

        #region SourceColumn

        [TestMethod]
        public void SourceColumn_IsValid ()
        {
            var expected = "command";

            //Act
            var target = new DataParameter("p1", DbType.Int32);
            target.SourceColumn = expected;

            //Assert
            target.SourceColumn.Should().Be(expected);
        }

        [TestMethod]
        public void SourceColumn_IsNull ()
        {
            //Act
            var target = new DataParameter("p1", DbType.Int32);
            target.SourceColumn = null;

            //Assert
            target.SourceColumn.Should().BeEmpty();
        }

        [TestMethod]
        public void SourceColumn_NotSet ()
        {
            //Act
            var target = new DataParameter("p1", DbType.Int32);

            //Assert
            target.SourceColumn.Should().BeEmpty();
        }
        #endregion

        #region ToString

        [TestMethod]
        public void ToString_IsValid ()
        {
            var expected = "@p1";

            //Act
            var target = new DataParameter(expected, DbType.Int32);
            var actual = target.ToString();

            //Assert
            actual.Should().Be(expected);
        }
        #endregion
    }
}


text:
from biicode.common.test.bii_test_case import BiiTestCase
from nose.core import run
from biicode.common.test import model_creator as mother
from biicode.common.edition.processors.parse_processor import ParseProcessor
from biicode.common.model.bii_type import CPP
from biicode.common.edition.processors.processor_changes import ProcessorChanges
from biicode.common.output_stream import OutputStream

class ParseProcessorTest(BiiTestCase):

    def test_has_main_and_dependency_declarations(self):
        processor = ParseProcessor()
        changes = ProcessorChanges()
        block_holder = mother.get_block_holder(['user/geom/main.cpp'], CPP)
        processor.do_process(block_holder, changes, OutputStream())
        main = block_holder['main.cpp'].cell
        self.assertTrue(main.hasMain, 'Main method not detected by parse processor')
        self.check_dependency_set(main.dependencies, unresolved=['iostream', 'sphere.h'])

        # now remove #include
        load = block_holder['main.cpp'].content.load
        load.replace('#include "sphere.h"', '')
        block_holder['main.cpp'].content.load = load

        processor.do_process(block_holder, changes, OutputStream())
        self.check_dependency_set(main.dependencies, unresolved=['iostream'])

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    run()


text:
package com.github.mikephil.charting.data.realm.implementation;

import android.graphics.Color;

import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.realm.base.RealmBarLineScatterCandleBubbleDataSet;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;

import io.realm.DynamicRealmObject;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.RealmResults;

/**
 * Created by Philipp Jahoda on 07/11/15.
 */
public class RealmBarDataSet<T extends RealmObject> extends RealmBarLineScatterCandleBubbleDataSet<T, BarEntry> implements IBarDataSet {

    private String mStackValueFieldName;

    /**
     * space indicator between the bars 0.1f == 10 %
     */
    private float mBarSpace = 0.15f;

    /**
     * the maximum number of bars that are stacked upon each other, this value
     * is calculated from the Entries that are added to the DataSet
     */
    private int mStackSize = 1;

    /**
     * the color used for drawing the bar shadows
     */
    private int mBarShadowColor = Color.rgb(215, 215, 215);

    /**
     * the alpha value used to draw the highlight indicator bar
     */
    private int mHighLightAlpha = 120;

    /**
     * array of labels used to describe the different values of the stacked bars
     */
    private String[] mStackLabels = new String[]{
            "Stack"
    };

    public RealmBarDataSet(RealmResults<T> results, String yValuesField, String xIndexField) {
        super(results, yValuesField, xIndexField);
        mHighLightColor = Color.rgb(0, 0, 0);

        build(this.results);
        calcMinMax(0, results.size());
    }

    /**
     * Constructor for supporting stacked values.
     *
     * @param results
     * @param yValuesField
     * @param xIndexField
     * @param stackValueFieldName
     */
    public RealmBarDataSet(RealmResults<T> results, String yValuesField, String xIndexField, String stackValueFieldName) {
        super(results, yValuesField, xIndexField);
        this.mStackValueFieldName = stackValueFieldName;
        mHighLightColor = Color.rgb(0, 0, 0);

        build(this.results);
        calcMinMax(0, results.size());
    }

    @Override
    public void build(RealmResults<T> results) {

        for (T realmObject : results) {

            DynamicRealmObject dynamicObject = new DynamicRealmObject(realmObject);

            try { // normal entry

                float value = dynamicObject.getFloat(mValuesField);
                mValues.add(new BarEntry(value, dynamicObject.getInt(mIndexField)));

            } catch (IllegalArgumentException e) { // stacked entry

                RealmList<DynamicRealmObject> list = dynamicObject.getList(mValuesField);
                float[] values = new float[list.size()];

                int i = 0;
                for (DynamicRealmObject o : list) {
                    values[i] = o.getFloat(mStackValueFieldName);
                    i++;
                }

                mValues.add(new BarEntry(values, dynamicObject.getInt(mIndexField)));
            }
        }

        calcStackSize();
    }

    @Override
    public void calcMinMax(int start, int end) {

        if (mValues == null)
            return;

        final int yValCount = mValues.size();

        if (yValCount == 0)
            return;

        int endValue;

        if (end == 0 || end >= yValCount)
            endValue = yValCount - 1;
        else
            endValue = end;

        mYMin = Float.MAX_VALUE;
        mYMax = -Float.MAX_VALUE;

        for (int i = start; i <= endValue; i++) {

            BarEntry e = mValues.get(i);

            if (e != null && !Float.isNaN(e.getVal())) {

                if (e.getVals() == null) {

                    if (e.getVal() < mYMin)
                        mYMin = e.getVal();

                    if (e.getVal() > mYMax)
                        mYMax = e.getVal();
                } else {

                    if (-e.getNegativeSum() < mYMin)
                        mYMin = -e.getNegativeSum();

                    if (e.getPositiveSum() > mYMax)
                        mYMax = e.getPositiveSum();
                }
            }
        }

        if (mYMin == Float.MAX_VALUE) {
            mYMin = 0.f;
            mYMax = 0.f;
        }
    }

    private void calcStackSize() {

        for (int i = 0; i < mValues.size(); i++) {

            float[] vals = mValues.get(i).getVals();

            if (vals != null && vals.length > mStackSize)
                mStackSize = vals.length;
        }
    }

    @Override
    public int getStackSize() {
        return mStackSize;
    }

    @Override
    public boolean isStacked() {
        return mStackSize > 1 ? true : false;
    }

    /**
     * returns the space between bars in percent of the whole width of one value
     *
     * @return
     */
    public float getBarSpacePercent() {
        return mBarSpace * 100f;
    }

    @Override
    public float getBarSpace() {
        return mBarSpace;
    }

    /**
     * sets the space between the bars in percent (0-100) of the total bar width
     *
     * @param percent
     */
    public void setBarSpacePercent(float percent) {
        mBarSpace = percent / 100f;
    }

    /**
     * Sets the color used for drawing the bar-shadows. The bar shadows is a
     * surface behind the bar that indicates the maximum value. Don't for get to
     * use getResources().getColor(...) to set this. Or Color.rgb(...).
     *
     * @param color
     */
    public void setBarShadowColor(int color) {
        mBarShadowColor = color;
    }

    @Override
    public int getBarShadowColor() {
        return mBarShadowColor;
    }

    /**
     * Set the alpha value (transparency) that is used for drawing the highlight
     * indicator bar. min = 0 (fully transparent), max = 255 (fully opaque)
     *
     * @param alpha
     */
    public void setHighLightAlpha(int alpha) {
        mHighLightAlpha = alpha;
    }

    @Override
    public int getHighLightAlpha() {
        return mHighLightAlpha;
    }

    /**
     * Sets labels for different values of bar-stacks, in case there are one.
     *
     * @param labels
     */
    public void setStackLabels(String[] labels) {
        mStackLabels = labels;
    }

    @Override
    public String[] getStackLabels() {
        return mStackLabels;
    }

}


text:
package gosnowth

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"path"
	"strconv"
	"time"
)

// TextValueResponse values represent text data responses.
type TextValueResponse []TextValue

// UnmarshalJSON decodes a JSON format byte slice into a TextValueResponse.
func (tvr *TextValueResponse) UnmarshalJSON(b []byte) error {
	*tvr = TextValueResponse{}
	values := [][]interface{}{}
	if err := json.Unmarshal(b, &values); err != nil {
		return fmt.Errorf("failed to decode JSON response: %w", err)
	}

	for _, entry := range values {
		var tv = TextValue{}
		if v, ok := entry[0].(float64); ok {
			tv.Time = time.Unix(int64(v), 0)
		}

		if v, ok := entry[1].(string); ok {
			tv.Value = new(string)
			*tv.Value = v
		}

		*tvr = append(*tvr, tv)
	}

	return nil
}

// TextValue values represent text data read from IRONdb.
type TextValue struct {
	Time  time.Time
	Value *string
}

// ReadTextValues reads text data values from an IRONdb node.
func (sc *SnowthClient) ReadTextValues(uuid, metric string,
	start, end time.Time, nodes ...*SnowthNode) ([]TextValue, error) {
	return sc.ReadTextValuesContext(context.Background(), uuid, metric,
		start, end, nodes...)
}

// ReadTextValuesContext is the context aware version of ReadTextValues.
func (sc *SnowthClient) ReadTextValuesContext(ctx context.Context,
	uuid, metric string, start, end time.Time,
	nodes ...*SnowthNode) ([]TextValue, error) {
	var node *SnowthNode
	if len(nodes) > 0 && nodes[0] != nil {
		node = nodes[0]
	} else {
		node = sc.GetActiveNode(sc.FindMetricNodeIDs(uuid, metric))
	}

	r := TextValueResponse{}
	body, _, err := sc.DoRequestContext(ctx, node, "GET", path.Join("/read",
		strconv.FormatInt(start.Unix(), 10),
		strconv.FormatInt(end.Unix(), 10), uuid, metric), nil, nil)
	if err != nil {
		return nil, err
	}

	if err := decodeJSON(body, &r); err != nil {
		return nil, fmt.Errorf("unable to decode IRONdb response: %w", err)
	}

	return r, nil
}

// TextData values represent text data to be written to IRONdb.
type TextData struct {
	Metric string `json:"metric"`
	ID     string `json:"id"`
	Offset string `json:"offset"`
	Value  string `json:"value"`
}

// WriteText writes text data to an IRONdb node.
func (sc *SnowthClient) WriteText(data []TextData, nodes ...*SnowthNode) error {
	return sc.WriteTextContext(context.Background(), data, nodes...)
}

// WriteTextContext is the context aware version of WriteText.
func (sc *SnowthClient) WriteTextContext(ctx context.Context,
	data []TextData, nodes ...*SnowthNode) error {
	var node *SnowthNode
	if len(nodes) > 0 && nodes[0] != nil {
		node = nodes[0]
	} else if len(data) > 0 {
		node = sc.GetActiveNode(sc.FindMetricNodeIDs(data[0].ID,
			data[0].Metric))
	}

	buf := new(bytes.Buffer)
	if err := json.NewEncoder(buf).Encode(data); err != nil {
		return fmt.Errorf("failed to encode TextData for write: %w", err)
	}

	_, _, err := sc.DoRequestContext(ctx, node, "POST", "/write/text", buf, nil)
	return err
}


text:
int main(int argc, char** argv) {
	lles::AtomTable at;
	std::string input;
	std::cout << "A test client for the AtomTable class" << std::endl;
	std::cout << "To exit, type .exit" << std::endl;
	int i;
	while (input != ".exit") {
		std::cin >> input;
		i = at.get(input.c_str());
		std::cout << "Index is " << i << std::endl;
		int res = std::strcmp(input.c_str(), at.get(i));
		if (res != 0) {
			std::cerr << "Error: index returned by AtomTable::get(const char*) does not return same string when used with AtomTable::get(int)" << std::endl;
			return 1;
		}
	}
	std::cout << "Test passed" << std::endl;
	return 0;
}


text:
describe("readGame", function(){
  var game;

  beforeEach(function(){
    game = readGame(createResponsiveCanvas());
  });

it("should create a canvas for letters", function(){
    expect(game).toEqual(game)
  });
});


text:
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use tempdir::TempDir;

use super::command::TestCommand;

pub fn project(name: &str) -> ProjectBuilder {
    ProjectBuilder::new(name)
}

pub struct ProjectBuilder {
    name: String,
    folders: Vec<String>,
}

impl ProjectBuilder {
    fn new(name: &str) -> Self {
        ProjectBuilder {
            name: name.into(),
            folders: Vec::new(),
        }
    }

    pub fn folder(mut self, name: &str) -> Self {
        self.folders.push(name.into());
        self
    }

    pub fn build(self) -> Project {
        let tempdir = TempDir::new(&self.name).unwrap();

        File::create(tempdir.path().join("Cargo.toml")).unwrap();

        for folder in self.folders {
            fs::create_dir(tempdir.path().join(folder))
                .unwrap();
        }

        Project {
            directory: tempdir,
            name: self.name,
        }
    }
}

pub struct Project {
    directory: TempDir,
    pub name: String,
}

impl Project {
    pub fn command(&self, name: &str) -> TestCommand {
        self.command_without_database_url(name)
            .env("DATABASE_URL", &self.database_url())
    }

    pub fn command_without_database_url(&self, name: &str) -> TestCommand {
        TestCommand::new(self.directory.path(), name)
    }

    pub fn migrations(&self) -> Vec<Migration> {
        self.directory.path().join("migrations")
            .read_dir().expect("Error reading directory")
            .map(|e| Migration {
                path: e.expect("error reading entry").path().into(),
            })
            .collect()
    }

    #[cfg(feature = "postgres")]
    pub fn database_url(&self) -> String {
        format!("postgres://localhost/{}", self.name)
    }

    #[cfg(feature = "sqlite")]
    pub fn database_url(&self) -> String {
        self.directory.path().join(&self.name)
            .into_os_string()
            .into_string().unwrap()
    }

    pub fn has_file(&self, path: &str) -> bool {
        self.directory.path().join(path).exists()
    }

    pub fn create_migration(&self, name: &str, up: &str, down: &str) {
        use std::io::Write;
        let migration_path = self.directory.path().join("migrations").join(name);
        fs::create_dir(&migration_path)
            .expect("Migrations folder must exist to create a migration");
        let mut up_file = fs::File::create(&migration_path.join("up.sql")).unwrap();
        up_file.write_all(up.as_bytes()).unwrap();

        let mut down_file = fs::File::create(&migration_path.join("down.sql")).unwrap();
        down_file.write_all(down.as_bytes()).unwrap();
    }
}

#[cfg(feature = "postgres")]
impl Drop for Project {
    fn drop(&mut self) {
        use std::io::{self, Write};
        use std::thread;

        let result = self.command("database").arg("drop").run();
        if !result.is_success() {
            if thread::panicking() {
                writeln!(io::stderr(), "Couldn't drop database: {:?}", result).unwrap();
            } else {
                panic!("Couldn't drop database: {:?}", result);
            }
        }
    }
}

pub struct Migration {
    path: PathBuf,
}

impl Migration {
    pub fn name(&self) -> &str {
        let name_start_index = self.file_name().find('_').unwrap() + 1;
        &self.file_name()[name_start_index..]
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    fn file_name(&self) -> &str {
        self.path.file_name().expect("migration should have a file name")
            .to_str().expect("Directory was not valid UTF-8")
    }
}


text:
Dummy::Application.routes.draw do
  resources :articles, only: [:create]
  resources :widgets, only: [:create, :update, :destroy]
end


text:
const Decoder = require('../../../decoder')
const { parse: parseV0 } = require('../v0/response')

/**
 * v2 (supported in 0.10.0 or later)
 * ProduceResponse => [TopicName [Partition ErrorCode Offset Timestamp]] ThrottleTime
 *   TopicName => string
 *   Partition => int32
 *   ErrorCode => int16
 *   Offset => int64
 *   Timestamp => int64
 *   ThrottleTime => int32
 */

const partition = decoder => ({
  partition: decoder.readInt32(),
  errorCode: decoder.readInt16(),
  offset: decoder.readInt64().toString(),
  timestamp: decoder.readInt64().toString(),
})

const decode = async rawData => {
  const decoder = new Decoder(rawData)
  const topics = decoder.readArray(decoder => ({
    topicName: decoder.readString(),
    partitions: decoder.readArray(partition),
  }))

  const throttleTime = decoder.readInt32()

  return {
    topics,
    throttleTime,
  }
}

module.exports = {
  decode,
  parse: parseV0,
}


text:
package edu.usc.softarch.disco.util;

// JDK imports
import java.io.File;
import java.util.Map;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @author mattmann
 * @version $Revision$
 *
 * <p>
 * Reads a value range for all attributes defined in a valRange.xml
 * file.
 * </p>.
 */
public final class ValRangeReader {

	private ValRangeReader() throws InstantiationException {
		throw new InstantiationException("Don't construct readers!");
	}

	public static Map readValRangeFile(File file) {
		Document docRoot = XMLUtils.getDocumentRoot(file.getAbsolutePath());
		Element docElement = docRoot.getDocumentElement();
		return XmlStructFactory.getValRange(docElement);
	}

}


text:
static svn_error_t * ssl_trust_prompt_func(svn_auth_cred_ssl_server_trust_t **cred_p, void *baton, const char *realm, apr_uint32_t failures, const svn_auth_ssl_server_cert_info_t *cert_info, svn_boolean_t may_save, apr_pool_t *pool);

static svn_error_t * simple_prompt_func(svn_auth_cred_simple_t **cred, void *baton, const char *realm, const char *username, svn_boolean_t may_save, apr_pool_t *pool);

static svn_error_t * username_prompt_func(svn_auth_cred_username_t **cred, void *baton, const char *realm, svn_boolean_t may_save, apr_pool_t *pool);

@implementation SVNAuthenticationProvider

-(id)init {
    self = [super init];
    if (self) {
        _providers = apr_array_make(self.pool, 4, sizeof(svn_auth_provider_object_t *));

        svn_auth_provider_object_t *provider;
        svn_error_t *err;

        svn_auth_get_ssl_server_trust_prompt_provider(&provider, ssl_trust_prompt_func, (__bridge void *)(self), self.pool);
        APR_ARRAY_PUSH(_providers, svn_auth_provider_object_t *) = provider;

        if ((err = svn_auth_get_platform_specific_provider(&provider, "keychain", "simple", self.pool))) {
            svn_error_clear(err);
            return nil;
        }
        APR_ARRAY_PUSH(_providers, svn_auth_provider_object_t *) = provider;

        svn_auth_get_simple_prompt_provider(&provider, simple_prompt_func, (__bridge void *)(self), 2, self.pool);
        APR_ARRAY_PUSH(_providers, svn_auth_provider_object_t *) = provider;

        svn_auth_get_username_prompt_provider(&provider, username_prompt_func, (__bridge void *)(self), 2, self.pool);
        APR_ARRAY_PUSH(_providers, svn_auth_provider_object_t *) = provider;
    }
    return self;
}

@end

static svn_error_t * simple_prompt_func(svn_auth_cred_simple_t **cred, void *baton, const char *realm, const char *username, svn_boolean_t may_save, apr_pool_t *pool) {
    SVNAuthenticationProvider *provider = (__bridge SVNAuthenticationProvider *)(baton);

    SVNAuthenticationCredentials *creds = [SVNAuthenticationCredentials new];

    if (realm) {
        creds.realm = [NSString stringWithUTF8String:realm];
    }

    if (username) {
        creds.username = [NSString stringWithUTF8String:username];
    }

    if (![provider.dataSource respondsToSelector:@selector(SVNAuthenticationProvider:simpleCredential:)]) {
        return SVN_NO_ERROR;
    }

    if ([provider.dataSource SVNAuthenticationProvider:provider simpleCredential:creds]) {
        svn_auth_cred_simple_t *credRet = apr_pcalloc(pool, sizeof(*credRet));
        if (creds.username.length) {
            credRet->username = apr_pstrdup(pool, [creds.username UTF8String]);
        }
        if (creds.password.length) {
            credRet->password = apr_pstrdup(pool, [creds.password UTF8String]);
        }
        *cred = credRet;
    }

    return SVN_NO_ERROR;
}

static svn_error_t * username_prompt_func(svn_auth_cred_username_t **cred, void *baton, const char *realm, svn_boolean_t may_save, apr_pool_t *pool) {
    SVNAuthenticationProvider *provider = (__bridge SVNAuthenticationProvider *)(baton);

    SVNAuthenticationCredentials *creds = [SVNAuthenticationCredentials new];

    if (realm) {
        creds.realm = [NSString stringWithUTF8String:realm];
    }

    if (![provider.dataSource respondsToSelector:@selector(SVNAuthenticationProvider:usernameCredential:)]) {
        return SVN_NO_ERROR;
    }

    if ([provider.dataSource SVNAuthenticationProvider:provider usernameCredential:creds]) {
        svn_auth_cred_username_t *credRet = apr_pcalloc(pool, sizeof(*credRet));
        if (creds.username.length) {
            credRet->username = apr_pstrdup(pool, [creds.username UTF8String]);
        }
        *cred = credRet;
    }

    return SVN_NO_ERROR;
}

static svn_error_t * ssl_trust_prompt_func(svn_auth_cred_ssl_server_trust_t **cred_p, void *baton, const char *realm, apr_uint32_t failures, const svn_auth_ssl_server_cert_info_t *cert_info, svn_boolean_t may_save, apr_pool_t *pool) {
    *cred_p = apr_pcalloc(pool, sizeof(**cred_p));
    (*cred_p)->may_save = false;
    (*cred_p)->accepted_failures = failures;
    return SVN_NO_ERROR;
}


text:
#include <windows.h>
#include <stdio.h>
#include <assert.h>
#include <stdarg.h>

#include "wintab.h" // NOTE: get from wactab header package

#ifdef DEBUG
#define WACOM_DEBUG
#endif

// Ignore warnings about using unsafe string functions.
#pragma warning( disable : 4996 )

//////////////////////////////////////////////////////////////////////////////
// Function pointers to Wintab functions exported from wintab32.dll.
typedef UINT(API * WTINFOA) (UINT, UINT, LPVOID);
typedef HCTX(API * WTOPENA)(HWND, LPLOGCONTEXTA, BOOL);
typedef BOOL(API * WTGETA) (HCTX, LPLOGCONTEXT);
typedef BOOL(API * WTSETA) (HCTX, LPLOGCONTEXT);
typedef BOOL(API * WTCLOSE) (HCTX);
typedef BOOL(API * WTENABLE) (HCTX, BOOL);
typedef BOOL(API * WTPACKET) (HCTX, UINT, LPVOID);
typedef BOOL(API * WTOVERLAP) (HCTX, BOOL);
typedef BOOL(API * WTSAVE) (HCTX, LPVOID);
typedef BOOL(API * WTCONFIG) (HCTX, HWND);
typedef HCTX(API * WTRESTORE) (HWND, LPVOID, BOOL);
typedef BOOL(API * WTEXTSET) (HCTX, UINT, LPVOID);
typedef BOOL(API * WTEXTGET) (HCTX, UINT, LPVOID);
typedef BOOL(API * WTQUEUESIZESET) (HCTX, int);
typedef int  (API * WTDATAPEEK) (HCTX, UINT, UINT, int, LPVOID, LPINT);
typedef int  (API * WTPACKETSGET) (HCTX, int, LPVOID);
typedef HMGR(API * WTMGROPEN) (HWND, UINT);
typedef BOOL(API * WTMGRCLOSE) (HMGR);
typedef HCTX(API * WTMGRDEFCONTEXT) (HMGR, BOOL);
typedef HCTX(API * WTMGRDEFCONTEXTEX) (HMGR, UINT, BOOL);

// TODO - add more wintab32 function defs as needed

//////////////////////////////////////////////////////////////////////////////
// Loaded Wintab32 API functions.
extern HINSTANCE ghWintab;

extern WTINFOA gpWTInfoA;
extern WTOPENA gpWTOpenA;
extern WTGETA gpWTGetA;
extern WTSETA gpWTSetA;
extern WTCLOSE gpWTClose;
extern WTPACKET gpWTPacket;
extern WTENABLE gpWTEnable;
extern WTOVERLAP gpWTOverlap;
extern WTSAVE gpWTSave;
extern WTCONFIG gpWTConfig;
extern WTRESTORE gpWTRestore;
extern WTEXTSET gpWTExtSet;
extern WTEXTGET gpWTExtGet;
extern WTQUEUESIZESET gpWTQueueSizeSet;
extern WTDATAPEEK gpWTDataPeek;
extern WTPACKETSGET gpWTPacketsGet;
extern WTMGROPEN gpWTMgrOpen;
extern WTMGRCLOSE gpWTMgrClose;
extern WTMGRDEFCONTEXT gpWTMgrDefContext;
extern WTMGRDEFCONTEXTEX gpWTMgrDefContextEx;

// TODO - add more wintab32 function pointers as needed

//////////////////////////////////////////////////////////////////////////////
BOOL LoadWintab(void);
void UnloadWintab(void);

void ShowError(char *pszErrorMessage);

//////////////////////////////////////////////////////////////////////////////
#ifdef WACOM_DEBUG

void WacomTrace(char *lpszFormat, ...);

#define WACOM_ASSERT( x ) assert( x )
#define WACOM_TRACE(...)  WacomTrace(__VA_ARGS__)
#else
#define WACOM_TRACE(...)
#define WACOM_ASSERT( x )

#endif // WACOM_DEBUG


text:
from __future__ import unicode_literals
from badgekit_webhooks import utils
from django.test import TestCase
import httpretty
import json
import re

class ClaimImageTest(TestCase):

    def testBrokenAssertionURL(self):
        default_url = 'http://example.com/no.gophers.png'
        with self.settings(BADGEKIT_DEFAULT_BADGE_IMAGE=default_url):
            url = utils.get_image_for_assertion('gopher://bad.url')
            self.assertEqual(url, default_url)

    @httpretty.activate
    def testBrokenJSON(self):
        default_url = 'http://example.com/no.gophers.png'
        with self.settings(BADGEKIT_DEFAULT_BADGE_IMAGE=default_url):
            httpretty.register_uri(httpretty.GET,
                    re.compile('example.com/.*'),
                    body='!this ain\'t json')
            url = utils.get_image_for_assertion('http://example.com/assertion.json')

            self.assertEqual(url, default_url)
            req = httpretty.last_request()
            self.assertEqual(req.path, '/assertion.json')

    @httpretty.activate
    def testBrokenAssertion(self):
        default_url = 'http://example.com/no.gophers.png'
        with self.settings(BADGEKIT_DEFAULT_BADGE_IMAGE=default_url):
            httpretty.register_uri(httpretty.GET,
                    re.compile('example.com/.*'),
                    body=json.dumps({
                        'valid': 'Yes, good JSON, but not an assertion.',
                        }))
            url = utils.get_image_for_assertion('http://example.com/assertion.json')

            self.assertEqual(url, default_url)
            req = httpretty.last_request()
            self.assertEqual(req.path, '/assertion.json')

    @httpretty.activate
    def testassertion_properties_badgeURL(self):
        default_url = 'http://example.com/no.gophers.png'
        with self.settings(BADGEKIT_DEFAULT_BADGE_IMAGE=default_url):
            httpretty.register_uri(httpretty.GET,
                    re.compile('example.com/assertion'),
                    body=json.dumps({

                        "uid": "12435",
                        "recipient":"test@test.com",
                        "badge": "http://example.com/badge.json",
                        "issuedOn":1359217910

                        }))
            httpretty.register_uri(httpretty.GET,
                    re.compile('example.com/badge'),
                    body=json.dumps({
                        "name": "Awesome Robotics Badge",
                        "description": "For doing awesome things with robots that people think is pretty great.",
                        "image": "https://example.org/robotics-badge.png",
                        "criteria": "https://example.org/robotics-badge.html",
                        "tags": ["robots", "awesome"],
                        "issuer": "https://example.org/organization.json",
                        "alignment":[
                            {   "name": "CCSS.ELA-Literacy.RST.11-12.3",
                                "url": "http://www.corestandards.org/ELA-Literacy/RST/11-12/3",
                                "description": "Follow precisely a complex multistep procedure when carrying out experiments, taking measurements, or performing technical tasks; analyze the specific results based on explanations in the text."
                            },
                            {
                                "name": "CCSS.ELA-Literacy.RST.11-12.9",
                                "url": "http://www.corestandards.org/ELA-Literacy/RST/11-12/9",
                                "description": " Synthesize information from a range of sources (e.g., texts, experiments, simulations) into a coherent understanding of a process, phenomenon, or concept, resolving conflicting information when possible."
                            }
                          ]
                       }))

        url=utils.get_image_for_assertion('http://example.com/assertion.json')
        self.assertEqual(url,'https://example.org/robotics-badge.png')

    @httpretty.activate
    def testassertion_properties_badgeobj(self):
        default_url = 'http://example.com/no.gophers.png'
        with self.settings(BADGEKIT_DEFAULT_BADGE_IMAGE=default_url):
            httpretty.register_uri(httpretty.GET,
                    re.compile('example.com/assertion'),
                    body=json.dumps({

                        "uid": "12435",
                        "recipient":"test@test.com",
                        "badge": {
                        "name": "Awesome Robotics Badge",
                        "description": "For doing awesome things with robots that people think is pretty great.",
                        "image": "https://example.org/robotics-badge.png",
                        "criteria": "https://example.org/robotics-badge.html",
                        "tags": ["robots", "awesome"],
                        "issuer": "https://example.org/organization.json",
                        "alignment":[
                            {   "name": "CCSS.ELA-Literacy.RST.11-12.3",
                                "url": "http://www.corestandards.org/ELA-Literacy/RST/11-12/3",
                                "description": "Follow precisely a complex multistep procedure when carrying out experiments, taking measurements, or performing technical tasks; analyze the specific results based on explanations in the text."
                            },
                            {
                                "name": "CCSS.ELA-Literacy.RST.11-12.9",
                                "url": "http://www.corestandards.org/ELA-Literacy/RST/11-12/9",
                                "description": " Synthesize information from a range of sources (e.g., texts, experiments, simulations) into a coherent understanding of a process, phenomenon, or concept, resolving conflicting information when possible."
                            }
                          ]
                        },
                        "issuedOn":1359217910

                        }))

        url=utils.get_image_for_assertion('http://example.com/assertion.json')
        self.assertEqual(url,'https://example.org/robotics-badge.png')


text:
// @(#)$Id: Heavyweight.java,v 1.9 2005/04/01 23:38:12 leavens Exp $

// Copyright (C) 2002 Iowa State University

// This file is part of JML

// JML 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 2, or (at your option)
// any later version.

// JML 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 JML; see the file COPYING.  If not, write to
// the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

package org.jmlspecs.samples.jmlrefman;

public abstract class Heavyweight {

    protected boolean P, Q, R;
    protected int X;

    /*@ protected behavior
      @   requires P;
      @   diverges false;
      @   assignable X;
      @   when \not_specified;
      @   working_space \not_specified;
      @   duration \not_specified;
      @   ensures Q;
      @   signals_only Exception;
      @   signals (Exception) R;
      @*/
    protected abstract int m() throws Exception;
}


text:
package com.stanfy.enroscar.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * URL connection wrapper.
 * Delegates all the method calls to the wrapped instance.
 */
public abstract class UrlConnectionWrapper extends URLConnection {

  /** Core connection instance. */
  private URLConnection core;

  protected UrlConnectionWrapper(final URLConnection urlConnection) {
    super(urlConnection.getURL());
    this.core = urlConnection;
  }

  public static URLConnection unwrap(final URLConnection connection) {
    URLConnection result = connection;
    while (result instanceof UrlConnectionWrapper) {
      result = ((UrlConnectionWrapper)result).core;
    }
    return result;
  }

  public static <T extends UrlConnectionWrapper> T getWrapper(final URLConnection connection,
                                                              final Class<T> clazz) {
    URLConnection result = connection;
    if (!(result instanceof UrlConnectionWrapper)) { return null; }
    boolean found = false;
    do {
      if (!clazz.isInstance(result)) {
        result = ((UrlConnectionWrapper)result).core;
      } else {
        found = true;
      }
    } while (!found && result instanceof UrlConnectionWrapper);
    return found ? clazz.cast(result) : null;
  }

  public final URLConnection getCore() { return core; }

  @Override
  public void connect() throws IOException {
    core.connect();
    connected = true;
  }

  @Override
  public boolean getAllowUserInteraction() { return core.getAllowUserInteraction(); }

  @Override
  public Object getContent() throws IOException { return core.getContent(); }

  @Override
  @SuppressWarnings("rawtypes")
  public Object getContent(final Class[] types) throws IOException { return core.getContent(types); }

  @Override
  public String getContentEncoding() { return core.getContentEncoding(); }

  @Override
  public int getContentLength() { return core.getContentLength();  }

  @Override
  public String getContentType() { return core.getContentType(); }

  @Override
  public long getDate() { return core.getDate(); }

  @Override
  public boolean getDefaultUseCaches() { return core.getDefaultUseCaches(); }

  @Override
  public boolean getDoInput() { return core.getDoInput(); }

  @Override
  public boolean getDoOutput() { return core.getDoInput(); }

  @Override
  public long getExpiration() { return core.getExpiration(); }

  @Override
  public String getHeaderField(final int pos) { return core.getHeaderField(pos); }

  @Override
  public Map<String, List<String>> getHeaderFields() { return core.getHeaderFields(); }

  @Override
  public Map<String, List<String>> getRequestProperties() { return core.getRequestProperties(); }

  @Override
  public void addRequestProperty(final String field, final String newValue) {
    core.addRequestProperty(field, newValue);
  }

  @Override
  public String getHeaderField(final String key) { return core.getHeaderField(key); }

  @Override
  public long getHeaderFieldDate(final String field, final long defaultValue) { return core.getHeaderFieldDate(field, defaultValue); }

  @Override
  public int getHeaderFieldInt(final String field, final int defaultValue) { return core.getHeaderFieldInt(field, defaultValue); }

  @Override
  public String getHeaderFieldKey(final int posn) { return core.getHeaderFieldKey(posn); }

  @Override
  public long getIfModifiedSince() { return core.getIfModifiedSince(); }

  @Override
  public InputStream getInputStream() throws IOException { return core.getInputStream(); }

  @Override
  public long getLastModified() { return core.getLastModified(); }

  @Override
  public OutputStream getOutputStream() throws IOException { return core.getOutputStream(); }

  @Override
  public java.security.Permission getPermission() throws IOException { return core.getPermission(); }

  @Override
  public String getRequestProperty(final String field) { return core.getRequestProperty(field); }

  @Override
  public URL getURL() { return url; }

  @Override
  public boolean getUseCaches() { return core.getUseCaches(); }

  @Override
  public void setAllowUserInteraction(final boolean newValue) {
    core.setAllowUserInteraction(newValue);
  }

  @Override
  public void setDefaultUseCaches(final boolean newValue) {
    core.setDefaultUseCaches(newValue);
  }

  @Override
  public void setDoInput(final boolean newValue) {
    core.setDoInput(newValue);
  }

  @Override
  public void setDoOutput(final boolean newValue) {
    core.setDoOutput(newValue);
  }

  @Override
  public void setIfModifiedSince(final long newValue) {
    core.setIfModifiedSince(newValue);
  }

  @Override
  public void setRequestProperty(final String field, final String newValue) {
    core.setRequestProperty(field, newValue);
  }

  @Override
  public void setUseCaches(final boolean newValue) {
    core.setUseCaches(newValue);
  }

  @Override
  public void setConnectTimeout(final int timeout) {
    core.setConnectTimeout(timeout);
  }

  @Override
  public int getConnectTimeout() { return core.getConnectTimeout(); }

  @Override
  public void setReadTimeout(final int timeout) {
    core.setReadTimeout(timeout);
  }

  @Override
  public int getReadTimeout() { return core.getReadTimeout(); }

}


text:
import gulp from 'gulp';
import Elixir from 'laravel-elixir';
import postcss from 'gulp-postcss';
import rtlcss from 'rtlcss';

class RTLTask extends Elixir.Task {
    /**
     * Create a new RTLTask instance.
     *
     * @param {string}      name
     * @param {GulpPaths}   paths
     * @param {object|null} options
     */
    constructor(name, paths, options) {
        super(name, null, paths);

        this.options = options;
    }

    /**
     * Build the Gulp task.
     */
    gulpTask() {
        return (
            gulp
            .src(this.src.path)
            .pipe(this.initSourceMaps())
            .pipe(this.compile())
            .on('error', this.onError())
            .pipe(this.rtl())
            .on('error', this.onError())
            .pipe(this.autoPrefix())
            .pipe(this.concat())
            .pipe(this.minify())
            .on('error', this.onError())
            .pipe(this.writeSourceMaps())
            .pipe(this.saveAs(gulp))
            .pipe(this.onSuccess())
        );
    }

    /**
     * Register file watchers.
     */
    registerWatchers() {
        this.watch(this.src.baseDir + Elixir.config.css[this.name].search)
            .ignore(this.output.path);
    }

    /**
     * Compile the SASS.
     */
    compile() {
        this.recordStep('Compiling ' + this.ucName());

        let plugin = Elixir.Plugins.sass ||
                     Elixir.config.css[this.name].plugin;

        return plugin(
            this.options || Elixir.config.css[this.name].pluginOptions
        );
    }

    /**
     * RTL the CSS.
     */
    rtl() {
        return postcss([rtlcss]);
    }

    /**
     * Apply CSS auto-prefixing.
     */
    autoPrefix() {
        if (! Elixir.config.css.autoprefix.enabled) {
            return this.stream();
        }

        this.recordStep('Autoprefixing CSS');

        return Elixir.Plugins.autoprefixer(
            Elixir.config.css.autoprefix.options
        );
    }
}

export default RTLTask;


text:
require "spec_helper"

describe Bijou::Router do
  describe "#initialize" do
    it "Returns a new instance of Bijou Router" do
      expect(Bijou::Router.new).to be_an_instance_of Bijou::Router
      expect(Bijou::Router.new.instance_variable_get("@app_routes")).to eql({})
    end
  end

  describe "#draw" do
    it "Doesn't take any arguments" do
      expect{ Bijou::Router.new.draw(25) }.to raise_error ArgumentError
    end

    it "Expects a block and executes the content of the passed in block" do
      result = Bijou::Router.new.draw do
        2 + 2
      end
      expect(result).to be 4
    end
  end

  describe "#root" do
    it "Takes exactly one argument" do
      expect{ Bijou::Router.new.root }.to raise_error ArgumentError
      expect{ Bijou::Router.new.root("hello", "world") }.to raise_error ArgumentError
    end

    it "Returns an array when a valid argument is passed in" do
      expect(Bijou::Router.new.root("pages#index")).to be_an_instance_of Array
      expect(Bijou::Router.new.root("pages#index")).to eql(
        [["/", {:controller=>"pages", :action=>"index"}]]
      )
    end
  end

  describe "#handle_request" do
    subject(:bijou_router) { Bijou::Router.new }

    it "Takes exactly one argument" do
      expect{ bijou_router.handle_request }.to raise_error ArgumentError
      expect{ bijou_router.handle_request("hello", "world") }.to raise_error ArgumentError
    end

    it "Returns a new route instance when a valid argument is passed in" do
      bijou_router.draw do
        get "/agenda/new", to: "pages#index"
      end

      allow(ENV).to receive(:path_info).and_return("/agenda/new")
      allow(ENV).to receive(:request_method).and_return("GET")

      expect(bijou_router.handle_request(ENV)).to be_an_instance_of Bijou::Route
    end

    it "Returns a new route instance when the route matches the defined route pattern" do
      bijou_router.draw do
        get "/agenda/:id", to: "pages#create"
      end

      allow(ENV).to receive(:path_info).and_return("/agenda/1")
      allow(ENV).to receive(:request_method).and_return("GET")
      allow(ENV).to receive(:params).and_return({})

      expect(bijou_router.handle_request(ENV)).to be_an_instance_of Bijou::Route
    end
  end

  describe "#parse_action" do
    subject(:bijou_router) { Bijou::Router.new }

    it "Should be a private method" do
      expect{ bijou_router.parse_action("pages#index") }.to raise_error NoMethodError
    end

    it "Takes exactly one argument" do
      expect{ bijou_router.send(:parse_action) }.to raise_error ArgumentError
      expect{ bijou_router.send(:parse_action, "hello", "world") }.to raise_error ArgumentError
    end

    it "Returns a hash using the argument
        to generate controller and action keys" do
        expect(bijou_router.send(:parse_action, "pages#index")).to be_an_instance_of Hash
        expect(bijou_router.send(:parse_action, "pages#index")).to eql(
          {:controller => "pages", :action => "index"}
        )
    end
  end

  describe "#generate_regex" do
    subject(:bijou_router) { Bijou::Router.new }

    it "Should be a private method" do
      expect{ bijou_router.generate_regex("/agenda/1") }.to raise_error NoMethodError
    end

    it "Takes exactly one argument" do
      expect{ bijou_router.send(:generate_regex) }.to raise_error ArgumentError
      expect{ bijou_router.send(:generate_regex, "hello", "world") }.to raise_error ArgumentError
    end

    it "Returns a new Regexp instance using the argument" do
        expect(bijou_router.send(:generate_regex, "/agenda/1")).to be_an_instance_of Regexp
        expect(bijou_router.send(:generate_regex, "/agenda/1")).to eql(/\/agenda\/:[a-z]+/)
    end
  end
end


text:
namespace Friends.Locator
{
    public enum eStack
    {
        Authentication,
        Main
    }
}


text:
<?php

/*
 * This file is part of the Symfony CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\FixerInterface;
use Symfony\CS\Token;
use Symfony\CS\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ConcatWithSpaces implements FixerInterface
{
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            $token = $tokens[$index];

            if (!$token->isArray() && '.' === $token->content) {
                if (!$tokens[$index + 1]->isWhitespace()) {
                    $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
                }

                if (!$tokens[$index - 1]->isWhitespace()) {
                    $tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
                }
            }
        }

        return $tokens->generateCode();
    }

    public function getLevel()
    {
        return FixerInterface::CONTRIB_LEVEL;
    }

    public function getPriority()
    {
        // should be run after the ConcatWithoutSpaces
        return -10;
    }

    public function supports(\SplFileInfo $file)
    {
        return true;
    }

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

    public function getDescription()
    {
        return 'Concatenation should be used with at least one whitespace around.';
    }
}


text:
<?php

namespace Acme\MovieBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\MovieBundle\Entity\Director;
use Acme\MovieBundle\Form\DirectorType;

/**
 * Director controller.
 *
 * @Route("/directors")
 */
class DirectorController extends Controller
{
    /**
     * Lists all Director entities.
     *
     * @Route("/", name="directors", options={"expose"=true})
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $entities = $em->getRepository('AcmeMovieBundle:Director')->findAll();

        $entity = new Director();
        $form   = $this->createForm(new DirectorType(), $entity);

        $director_id = $this->getRequest()->get('id');

        return array(
            'entities' => $entities,
            'entity' => $entity,
            'director_id' => $director_id,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Director entity.
     *
     * @Route("/{id}/show", name="director_show", options={"expose"=true})
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AcmeMovieBundle:Director')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Director entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to create a new Director entity.
     *
     * @Route("/new", name="director_new", options={"expose"=true})
     * @Template()
     */
    public function newAction()
    {
        $entity = new Director();
        $form   = $this->createForm(new DirectorType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new Director entity.
     *
     * @Route("/create", name="director_create", options={"expose"=true})
     * @Method("POST")
     * @Template("AcmeMovieBundle:Director:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new Director();
        if ($request->isXmlHttpRequest()) {
            $form = $this->createForm(new DirectorType(), $entity,
                array('csrf_protection' => false));
        } else {
            $form = $this->createForm(new DirectorType(), $entity);
        }
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            if ($request->isXmlHttpRequest()) {
                $response = new Response();
                $response->setContent(json_encode(array(
                    'id' => $entity->getId(),
                    'name' => $entity->getName()
                )));
                return $response;
            }

            return $this->redirect($this->generateUrl('directors', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Director entity.
     *
     * @Route("/{id}/edit", name="director_edit", options={"expose"=true})
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AcmeMovieBundle:Director')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Director entity.');
        }

        $editForm = $this->createForm(new DirectorType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Director entity.
     *
     * @Route("/{id}/update", name="director_update", options={"expose"=true})
     * @Method("POST")
     * @Template("AcmeMovieBundle:Director:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AcmeMovieBundle:Director')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Director entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new DirectorType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('director_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Director entity.
     *
     * @Route("/{id}/delete", name="director_delete", options={"expose"=true})
     * @Method("POST")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AcmeMovieBundle:Director')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Director entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('director'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
layout: model
title: Lemma UD model for Persian (pos_perdt)
author: John Snow Labs
name: pos_perdt
date: 2022-05-01
tags: [open_source, universal_dependency, pos, part_of_speech, fa, persian]
task: Part of Speech Tagging
language: fa
edition: Spark NLP 3.4.3
spark_version: 3.0
supported: true
annotator: PerceptronModel
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Pretrained Lemmatizer model (`pos_perdt`) trained on Universal Dependencies 2.9 (UD_Persian-PerDT) in Persian language.

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
[Open in Colab](https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/GRAMMAR_EN.ipynb){:.button.button-orange.button-orange-trans.co.button-icon}
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/pos_perdt_fa_3.4.3_3.0_1651419683334.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python

document = DocumentAssembler()\
.setInputCol("text")\
.setOutputCol("document")

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

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

pos = PerceptronModel.pretrained("pos_perdt", "fa")\
.setInputCols(["sentence", "token"])\
.setOutputCol("pos")

pipeline = Pipeline(stages=[document, sentence, tokenizer, pos])

data = spark.createDataFrame([["I love Spark NLP"]]).toDF("text")

result = pipeline.fit(data).transform(data)
```
```scala

val document = new DocumentAssembler()
.setInputCol("text")
.setOutputCol("document")

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

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

val pos = PerceptronModel.pretrained("pos_perdt", "fa")
.setInputCols("sentence", "token")
.setOutputCol("pos")

val pipeline = new Pipeline().setStages(Array(document, sentence, tokenizer, pos))

val data = Seq("I love Spark NLP").toDF("text")

val result = pipeline.fit(data).transform(data)
```

{:.nlu-block}
```python
import nlu
nlu.load("fa.pos").predict("""I love Spark NLP""")
```

</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|pos_perdt|
|Compatibility:|Spark NLP 3.4.3+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[sentence, form]|
|Output Labels:|[pos]|
|Language:|fa|
|Size:|4.3 MB|

## References

Model is trained on Universal Dependencies (treebank 2.9) `UD_Persian-PerDT`
[https://github.com/UniversalDependencies/UD_Persian-PerDT](https://github.com/UniversalDependencies/UD_Persian-PerDT)


text:
  Saint-Menoux est
       un village
       situé dans le département de l'Allier en Auvergne. On dénombrait 920 habitants en 2008.

À Saint-Menoux, la valeur moyenne à l'achat d'un appartement s'évalue à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 953 € du m². À la location le prix moyen se situe à 5 € du m² par mois.

Si vous pensez venir habiter à Saint-Menoux, vous pourrez aisément trouver une maison à acheter.

Le nombre de logements, à Saint-Menoux, était réparti en 2011 en 25 appartements et 495 maisons soit
 un marché plutôt équilibré.

La ville propose quelques  aménagements, elle propose entre autres un terrain de tennis, un terrain de sport et une boucle de randonnée.

La localité est équipée concernant des études de un collège.
S'agissant les plus jeunes, la localité est équipée de deux écoles primaires.
Saint-Menoux est équipée des  équipements facilitant une éducation de qualité.
Lors d'un projet immobilier à Saint-Menoux, vous devrez impérativement regarder la qualité des équipements éducatifs

À proximité de Saint-Menoux sont positionnées géographiquement les villes de
Couzon à 8 km, 295 habitants,
Bourbon-l'Archambault localisée à 7 km, 2 617 habitants,
Souvigny à 6 km, 1 958 habitants,
Autry-Issards localisée à 4 km, 317 habitants,
Agonges localisée à 2 km, 371 habitants,
Bagneux à 9 km, 255 habitants,
 entre autres. De plus, Saint-Menoux est située à seulement treize km de Moulins.


text:
<?php

class Ebanx_Gateway_Model_Capture
{
    /**
     * @var \Ebanx\Benjamin\Facade
     */
    private $ebanx;
    private $payment;

    /**
     * @param observer $observer payment observer
     *
     * @return void
     *
     * @throws Ebanx_Gateway_Exception
     */
    public function capturePayment($observer)
    {
        $this->ebanx = Mage::getSingleton('ebanx/api')->ebanx();
        $this->payment = $observer
            ->getEvent()
            ->getInvoice()
            ->getOrder()
            ->getPayment();
        $hash = $this->payment->getEbanxPaymentHash();
        $method_code = $this->payment->getMethodInstance()->getCode();

        if (!isset($this->payment)
            || !isset($hash)
            || strpos($method_code, "ebanx_cc") === false
            || !$this->isPaymentPending($hash)) {
            return;
        }

        $this->ebanx->creditCard()->captureByHash($hash);
    }

    /**
     * @param string $hash payment hash
     *
     * @return bool
     *
     * @throws Ebanx_Gateway_Exception
     */
    private function isPaymentPending($hash)
    {
        $helper = Mage::helper('ebanx/order');
        $isSandbox = $this->payment->getEbanxEnvironment() === 'sandbox';
        $payment = $this->ebanx->paymentInfo()->findByHash($hash, $isSandbox);

        if ($payment['status'] !== 'SUCCESS') {
            throw new Ebanx_Gateway_Exception($helper->__('EBANX: Payment doesn\'t exist.'));
        }

        return $payment['payment']['status']  === 'PE';
    }
}


text:
package ch.epfl.scala.index.client
package rpc

import upickle.default.{Reader, Writer, read => uread, write => uwrite}

import scala.concurrent.Future
import scalajs.concurrent.JSExecutionContext.Implicits.queue
import org.scalajs.dom

object AutowireClient extends autowire.Client[String, Reader, Writer] {

  import scala.scalajs.js.URIUtils.encodeURIComponent

  /** Reuse URL encoding and update implementation to reserve square brackets. */
  def encode(uri: String): String =
    encodeURIComponent(uri.filterNot(c => c == '[' || c == ']'))

  def buildQueryGet(args: Map[String, String]): String = {
    args.iterator.map {
      case (key, value) =>
        key + "=" + encode(value.toString.tail.init) // removes quotes around
    }.mkString("&")
  }

  /** Change this if you add more features to the client. */
  override def doCall(req: Request): Future[String] = {
    dom.ext.Ajax
      .get(
        url = "/api/" + req.path.last + "?" + buildQueryGet(req.args)
      )
      .map(_.responseText)
  }

  def read[T: Reader](p: String) = uread[T](p)
  def write[T: Writer](r: T) = uwrite(r)
}


text:
class Roda
  module RodaPlugins
    # The slash_path_empty plugin considers "/" as an empty path,
    # in addition to the default of "" being considered an empty
    # path.  This makes it so +r.is+ without an argument will match
    # a path of "/", and +r.is+ and verb methods such as +r.get+ and
    # +r.post+ will match if the path is "/" after the arguments
    # are processed.  This can make it easier to handle applications
    # where a trailing "/" in the path should be ignored.
    module SlashPathEmpty
      module RequestMethods
        private

        # Consider the path empty if it is "/".
        def empty_path?
          super || remaining_path == '/'
        end
      end
    end

    register_plugin(:slash_path_empty, SlashPathEmpty)
  end
end