text:
"""Accesses the google.devtools.clouderrorreporting.v1beta1 ErrorStatsService API."""

import functools
import pkg_resources
import warnings

from google.oauth2 import service_account
import google.api_core.gapic_v1.client_info
import google.api_core.gapic_v1.config
import google.api_core.gapic_v1.method
import google.api_core.grpc_helpers
import google.api_core.page_iterator
import google.api_core.path_template
import grpc

from google.cloud.errorreporting_v1beta1.gapic import enums
from google.cloud.errorreporting_v1beta1.gapic import error_stats_service_client_config
from google.cloud.errorreporting_v1beta1.gapic.transports import error_stats_service_grpc_transport
from google.cloud.errorreporting_v1beta1.proto import common_pb2
from google.cloud.errorreporting_v1beta1.proto import error_group_service_pb2
from google.cloud.errorreporting_v1beta1.proto import error_group_service_pb2_grpc
from google.cloud.errorreporting_v1beta1.proto import error_stats_service_pb2
from google.cloud.errorreporting_v1beta1.proto import error_stats_service_pb2_grpc
from google.protobuf import duration_pb2
from google.protobuf import timestamp_pb2

_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution(
    'google-cloud-error-reporting', ).version

class ErrorStatsServiceClient(object):
    """
    An API for retrieving and managing error statistics as well as data for
    individual events.
    """

    SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com:443'
    """The default address of the service."""

    # The name of the interface for this client. This is the key used to
    # find the method configuration in the client_config dictionary.
    _INTERFACE_NAME = 'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService'

    @classmethod
    def from_service_account_file(cls, filename, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
        file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            ErrorStatsServiceClient: The constructed client.
        """
        credentials = service_account.Credentials.from_service_account_file(
            filename)
        kwargs['credentials'] = credentials
        return cls(*args, **kwargs)

    from_service_account_json = from_service_account_file

    @classmethod
    def project_path(cls, project):
        """Return a fully-qualified project string."""
        return google.api_core.path_template.expand(
            'projects/{project}',
            project=project,
        )

    def __init__(self,
                 transport=None,
                 channel=None,
                 credentials=None,
                 client_config=error_stats_service_client_config.config,
                 client_info=None):
        """Constructor.

        Args:
            transport (Union[~.ErrorStatsServiceGrpcTransport,
                    Callable[[~.Credentials, type], ~.ErrorStatsServiceGrpcTransport]): A transport
                instance, responsible for actually making the API calls.
                The default transport uses the gRPC protocol.
                This argument may also be a callable which returns a
                transport instance. Callables will be sent the credentials
                as the first argument and the default transport class as
                the second argument.
            channel (grpc.Channel): DEPRECATED. A ``Channel`` instance
                through which to make calls. This argument is mutually exclusive
                with ``credentials``; providing both will raise an exception.
            credentials (google.auth.credentials.Credentials): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is mutually exclusive with providing a
                transport instance to ``transport``; doing so will raise
                an exception.
            client_config (dict): DEPRECATED. A dictionary of call options for
                each method. If not specified, the default configuration is used.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
        """
        # Raise deprecation warnings for things we want to go away.
        if client_config:
            warnings.warn('The `client_config` argument is deprecated.',
                          PendingDeprecationWarning)
        if channel:
            warnings.warn(
                'The `channel` argument is deprecated; use '
                '`transport` instead.', PendingDeprecationWarning)

        # Instantiate the transport.
        # The transport is responsible for handling serialization and
        # deserialization and actually sending data to the service.
        if transport:
            if callable(transport):
                self.transport = transport(
                    credentials=credentials,
                    default_class=error_stats_service_grpc_transport.
                    ErrorStatsServiceGrpcTransport,
                )
            else:
                if credentials:
                    raise ValueError(
                        'Received both a transport instance and '
                        'credentials; these are mutually exclusive.')
                self.transport = transport
        else:
            self.transport = error_stats_service_grpc_transport.ErrorStatsServiceGrpcTransport(
                address=self.SERVICE_ADDRESS,
                channel=channel,
                credentials=credentials,
            )

        if client_info is None:
            client_info = (
                google.api_core.gapic_v1.client_info.DEFAULT_CLIENT_INFO)
        client_info.gapic_version = _GAPIC_LIBRARY_VERSION
        self._client_info = client_info

        # Parse out the default settings for retry and timeout for each RPC
        # from the client configuration.
        # (Ordinarily, these are the defaults specified in the `*_config.py`
        # file next to this one.)
        self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(
            client_config['interfaces'][self._INTERFACE_NAME], )

        # Save a dictionary of cached API call functions.
        # These are the actual callables which invoke the proper
        # transport methods, wrapped with `wrap_method` to add retry,
        # timeout, and the like.
        self._inner_api_calls = {}

    # Service calls
    def list_group_stats(self,
                         project_name,
                         time_range,
                         group_id=None,
                         service_filter=None,
                         timed_count_duration=None,
                         alignment=None,
                         alignment_time=None,
                         order=None,
                         page_size=None,
                         retry=google.api_core.gapic_v1.method.DEFAULT,
                         timeout=google.api_core.gapic_v1.method.DEFAULT,
                         metadata=None):
        """
        Lists the specified groups.

        Example:
            >>> from google.cloud import errorreporting_v1beta1
            >>>
            >>> client = errorreporting_v1beta1.ErrorStatsServiceClient()
            >>>
            >>> project_name = client.project_path('[PROJECT]')
            >>>
            >>> # TODO: Initialize ``time_range``:
            >>> time_range = {}
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_group_stats(project_name, time_range):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_group_stats(project_name, time_range, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            project_name (str): [Required] The resource name of the Google Cloud Platform project. Written
                as projects/ plus the
                Google Cloud
                Platform project ID.

                Example: projects/my-project-123.
            time_range (Union[dict, ~google.cloud.errorreporting_v1beta1.types.QueryTimeRange]): [Optional] List data for the given time range.
                If not set a default time range is used. The field time_range_begin
                in the response will specify the beginning of this time range.
                Only ErrorGroupStats with a non-zero count in the given time
                range are returned, unless the request contains an explicit group_id list.
                If a group_id list is given, also ErrorGroupStats with zero
                occurrences are returned.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.errorreporting_v1beta1.types.QueryTimeRange`
            group_id (list[str]): [Optional] List all ErrorGroupStats with these IDs.
            service_filter (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter]): [Optional] List only ErrorGroupStats which belong to a service
                context that matches the filter.
                Data for all service contexts is returned if this field is not specified.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter`
            timed_count_duration (Union[dict, ~google.cloud.errorreporting_v1beta1.types.Duration]): [Optional] The preferred duration for a single returned ``TimedCount``.
                If not set, no timed counts are returned.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.errorreporting_v1beta1.types.Duration`
            alignment (~google.cloud.errorreporting_v1beta1.types.TimedCountAlignment): [Optional] The alignment of the timed counts to be returned.
                Default is ``ALIGNMENT_EQUAL_AT_END``.
            alignment_time (Union[dict, ~google.cloud.errorreporting_v1beta1.types.Timestamp]): [Optional] Time where the timed counts shall be aligned if rounded
                alignment is chosen. Default is 00:00 UTC.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.errorreporting_v1beta1.types.Timestamp`
            order (~google.cloud.errorreporting_v1beta1.types.ErrorGroupOrder): [Optional] The sort order in which the results are returned.
                Default is ``COUNT_DESC``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.errorreporting_v1beta1.types.ErrorGroupStats` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'list_group_stats' not in self._inner_api_calls:
            self._inner_api_calls[
                'list_group_stats'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.list_group_stats,
                    default_retry=self._method_configs['ListGroupStats'].retry,
                    default_timeout=self._method_configs['ListGroupStats'].
                    timeout,
                    client_info=self._client_info,
                )

        request = error_stats_service_pb2.ListGroupStatsRequest(
            project_name=project_name,
            time_range=time_range,
            group_id=group_id,
            service_filter=service_filter,
            timed_count_duration=timed_count_duration,
            alignment=alignment,
            alignment_time=alignment_time,
            order=order,
            page_size=page_size,
        )
        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls['list_group_stats'],
                retry=retry,
                timeout=timeout,
                metadata=metadata),
            request=request,
            items_field='error_group_stats',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator

    def list_events(self,
                    project_name,
                    group_id,
                    service_filter=None,
                    time_range=None,
                    page_size=None,
                    retry=google.api_core.gapic_v1.method.DEFAULT,
                    timeout=google.api_core.gapic_v1.method.DEFAULT,
                    metadata=None):
        """
        Lists the specified events.

        Example:
            >>> from google.cloud import errorreporting_v1beta1
            >>>
            >>> client = errorreporting_v1beta1.ErrorStatsServiceClient()
            >>>
            >>> project_name = client.project_path('[PROJECT]')
            >>>
            >>> # TODO: Initialize ``group_id``:
            >>> group_id = ''
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_events(project_name, group_id):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_events(project_name, group_id, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            project_name (str): [Required] The resource name of the Google Cloud Platform project. Written
                as ``projects/`` plus the
                [Google Cloud Platform project
                ID](https://support.google.com/cloud/answer/6158840).
                Example: ``projects/my-project-123``.
            group_id (str): [Required] The group for which events shall be returned.
            service_filter (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter]): [Optional] List only ErrorGroups which belong to a service context that
                matches the filter.
                Data for all service contexts is returned if this field is not specified.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter`
            time_range (Union[dict, ~google.cloud.errorreporting_v1beta1.types.QueryTimeRange]): [Optional] List only data for the given time range.
                If not set a default time range is used. The field time_range_begin
                in the response will specify the beginning of this time range.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.errorreporting_v1beta1.types.QueryTimeRange`
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.errorreporting_v1beta1.types.ErrorEvent` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'list_events' not in self._inner_api_calls:
            self._inner_api_calls[
                'list_events'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.list_events,
                    default_retry=self._method_configs['ListEvents'].retry,
                    default_timeout=self._method_configs['ListEvents'].timeout,
                    client_info=self._client_info,
                )

        request = error_stats_service_pb2.ListEventsRequest(
            project_name=project_name,
            group_id=group_id,
            service_filter=service_filter,
            time_range=time_range,
            page_size=page_size,
        )
        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls['list_events'],
                retry=retry,
                timeout=timeout,
                metadata=metadata),
            request=request,
            items_field='error_events',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator

    def delete_events(self,
                      project_name,
                      retry=google.api_core.gapic_v1.method.DEFAULT,
                      timeout=google.api_core.gapic_v1.method.DEFAULT,
                      metadata=None):
        """
        Deletes all error events of a given project.

        Example:
            >>> from google.cloud import errorreporting_v1beta1
            >>>
            >>> client = errorreporting_v1beta1.ErrorStatsServiceClient()
            >>>
            >>> project_name = client.project_path('[PROJECT]')
            >>>
            >>> response = client.delete_events(project_name)

        Args:
            project_name (str): [Required] The resource name of the Google Cloud Platform project. Written
                as ``projects/`` plus the
                [Google Cloud Platform project
                ID](https://support.google.com/cloud/answer/6158840).
                Example: ``projects/my-project-123``.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.errorreporting_v1beta1.types.DeleteEventsResponse` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'delete_events' not in self._inner_api_calls:
            self._inner_api_calls[
                'delete_events'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.delete_events,
                    default_retry=self._method_configs['DeleteEvents'].retry,
                    default_timeout=self._method_configs['DeleteEvents'].
                    timeout,
                    client_info=self._client_info,
                )

        request = error_stats_service_pb2.DeleteEventsRequest(
            project_name=project_name, )
        return self._inner_api_calls['delete_events'](
            request, retry=retry, timeout=timeout, metadata=metadata)


text:
/*global define*/
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
  "scaleLabel": "Povečava merila",
  "locationSymbol": "Simbol lokacije",
  "locationSymbolHintText": "Namig: simbol za trenutno lokacijo koordinate",
  "symbolPickerPreviewText": "Predogled:",
  "warning": "Izberite Najprej pokaži možnost.",
  "setDefaultFormatTitlePane": "Uredi privzeto obliko",
  "showHeaderLabel": "Pokaži",
  "indexHeaderLabel": "Kazalo",
  "notationHeaderLabel": "Zapis",
  "defaultFormatHeaderLabel": "Privzeti format",
  "editFormatHeaderLabel": "Uredi format",
  "errorMessage": "Izbirnik simbolov vsebuje napake. Popravite pred uporabo."
});

redpajama_set_name: RedPajamaGithub


text:
package com.auth0.android.lock.internal.configuration;

import androidx.annotation.NonNull;

import java.util.Set;

public interface OAuthConnection extends BaseConnection {

    /**
     * Returns if this Connection can use Resource Owner to authenticate
     *
     * @return if the Active Flow (Resource Owner) is enabled.
     */
    boolean isActiveFlowEnabled();

    /**
     * If this connection is of type Enterprise it will return the configured Domains.
     *
     * @return a set with all domains configured
     */
    @NonNull
    Set<String> getDomainSet();

}


text:
package org.pentaho.hadoop.shim.hdi.format.parquet;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.pentaho.hadoop.shim.HadoopShim;
import org.pentaho.hadoop.shim.api.cluster.NamedCluster;
import org.pentaho.hadoop.shim.common.format.S3NCredentialUtils;
import org.pentaho.hadoop.shim.common.format.parquet.delegate.apache.PentahoApacheOutputFormat;

import java.nio.file.FileAlreadyExistsException;

public class HDIApacheOutputFormat extends PentahoApacheOutputFormat {

  private HadoopShim shim;
  private org.pentaho.hadoop.shim.api.internal.Configuration pentahoConf;

  @SuppressWarnings( "squid:S1874" )
  public HDIApacheOutputFormat( NamedCluster namedCluster ) {
    super( namedCluster );
    inClassloader( () -> {
      shim = new HadoopShim();
      if ( namedCluster != null ) {
        pentahoConf = shim.createConfiguration( namedCluster );
      }
    } );
  }

  @Override
  public void setOutputFile( String file, boolean override ) throws Exception {
    inClassloader( () -> {
      S3NCredentialUtils util = new S3NCredentialUtils();
      util.applyS3CredentialsToHadoopConfigurationIfNecessary( file, job.getConfiguration() );
      outputFile = new Path( S3NCredentialUtils.scrubFilePathIfNecessary( file ) );
      FileSystem fs = (FileSystem) shim.getFileSystem( pentahoConf ).getDelegate();
      if ( fs.exists( outputFile ) ) {
        if ( override ) {
          fs.delete( outputFile, true );
        } else {
          throw new FileAlreadyExistsException( file );
        }
      }
      this.outputFile = new Path( fs.getUri().toString() + this.outputFile.toUri().getPath() );
      this.outputFile = fs.makeQualified( this.outputFile );
      this.job.getConfiguration().set( "mapreduce.output.fileoutputformat.outputdir", this.outputFile.toString() );
    } );
  }
}


text:
<?php

namespace Travel\AnnonceBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FactureType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('sommeFacture')
            ->add('datePayementFacture')
            ->add('idReservation')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Travel\AnnonceBundle\Entity\Facture'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'travel_annoncebundle_facture';
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

def check_user_1(apps, schema_editor):
    Proposal = apps.get_model('proposals', 'Proposal')
    User = apps.get_model(*settings.AUTH_USER_MODEL.split('.'))
    db_alias = schema_editor.connection.alias
    if (Proposal.objects.using(db_alias).exists()
            and not User.objects.using(db_alias).filter(pk=1).exists()):
        raise ImproperlyConfigured(
            'Default user with pk=1 is needed for this migration.'
        )

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Proposal',
            fields=[
                ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
                ('title', models.CharField(verbose_name=b'title', max_length=140)),
                ('category', models.CharField(choices=[(b'PRAC', b'Best Practices & Patterns'), (b'COM', b'Community'), (b'DB', b'Databases'), (b'DATA', b'Data Analysis'), (b'EDU', b'Education'), (b'EMBED', b'Embedd Systems'), (b'GAME', b'Gaming'), (b'OTHER', b'Other'), (b'CORE', b'Python Core & Internals (language, stdlib, etc.)'), (b'LIBS', b'Python Libraries'), (b'SCI', b'Science'), (b'SEC', b'Security'), (b'ADMIN', b'Systems Administration'), (b'TEST', b'Testing'), (b'WEB', b'Web Frameworks')], verbose_name=b'category', max_length=5)),
                ('duration', models.CharField(choices=[(b'NOPREF', b'No preference'), (b'PREF25', b'Prefer 25min'), (b'PREF45', b'Prefer 45min')], verbose_name=b'duration', max_length=6)),
                ('language', models.CharField(choices=[(b'ENG', b'English'), (b'CHI', b'Chinese')], verbose_name=b'language', max_length=3)),
                ('target_audience', models.CharField(verbose_name=b'target audience', max_length=140, help_text=b'Who is the intended audience for your talk? (Be specific, "Python users" is not a good answer)')),
                ('abstract', models.TextField(verbose_name=b'abstract', max_length=400, help_text=b'The overview of what the talk is about. If the talk assume some domain knowledge please state it here.')),
                ('python_level', models.CharField(choices=[(b'NOVICE', b'Novice'), (b'INTERMEDIATE', b'Intermediate'), (b'EXPERIENCED', b'Experienced')], verbose_name=b'python level', max_length=12, help_text=b'The choice of talk level matters during the review process. More definition of talk level can be found at the Talk Level Definition in [How to Propose a talk] page. Note that a proposal who\'t be more likely to accepted because of being "Novice" level. We may contact you to change the talk level when we find the contend is too-hard or too-easy for the target audience.')),
                ('objectives', models.TextField(verbose_name=b'objectives', help_text=b"What will attendees get out of your talk? When they leave the room, what will they know that they didn't know before?")),
                ('detailed_description', models.TextField(verbose_name=b'detailed description', help_text=b'Try not be too lengthy which will scare away many reviewers. A comfortable length is less than 1000 chars (about 650 Chinese chars). Including related links to the talk topic will help reviewers understand and more likely accept the proposal. Note that most reviewers may not understand the topic as deep as you do.')),
                ('outline', models.TextField(verbose_name=b'outline', default=b'', help_text=b'How the talk will be arranged. It is highly recommended to attach the estimated time length for each sections in the talk. Talks in favor of 45min should have a fallback plan about how to shrink the content into a 25min one.', blank=True)),
                ('supplementary', models.TextField(verbose_name=b'supplementary', default=b'', help_text=b"Anything else you'd like the program committee to know when making their selection: your past speaking experience, open source community experience, etc.", blank=True)),
                ('recording_policy', models.BooleanField(choices=[(True, b'Yes'), (False, b'No')], verbose_name=b'recording policy', max_length=1, help_text=b'Description: If you agree to give permission to PyCon Taiwan to record, edit, and release audio and video of your presentation, please check this box. See [Recoding Release] for details.')),
                ('slide_link', models.URLField(blank=True, verbose_name=b'slide link', default=b'', help_text=b'You can add your slide link near or after the conference day. Not required for review.')),
            ],
            options={
                'verbose_name': 'Proposal',
                'verbose_name_plural': 'Proposals',
            },
        ),
        migrations.AlterModelOptions(
            name='proposal',
            options={'verbose_name': 'proposal', 'verbose_name_plural': 'proposals'},
        ),
        migrations.AlterField(
            model_name='proposal',
            name='abstract',
            field=models.TextField(verbose_name='abstract', max_length=400, help_text='The overview of what the talk is about. If the talk assume some domain knowledge please state it here.'),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='category',
            field=models.CharField(choices=[('PRAC', 'Best Practices & Patterns'), ('COM', 'Community'), ('DB', 'Databases'), ('DATA', 'Data Analysis'), ('EDU', 'Education'), ('EMBED', 'Embedd Systems'), ('GAME', 'Gaming'), ('OTHER', 'Other'), ('CORE', 'Python Core & Internals (language, stdlib, etc.)'), ('LIBS', 'Python Libraries'), ('SCI', 'Science'), ('SEC', 'Security'), ('ADMIN', 'Systems Administration'), ('TEST', 'Testing'), ('WEB', 'Web Frameworks')], verbose_name='category', max_length=5),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='detailed_description',
            field=models.TextField(verbose_name='detailed description', help_text='Try not be too lengthy which will scare away many reviewers. A comfortable length is less than 1000 chars (about 650 Chinese chars). Including related links to the talk topic will help reviewers understand and more likely accept the proposal. Note that most reviewers may not understand the topic as deep as you do.'),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='duration',
            field=models.CharField(choices=[('NOPREF', 'No preference'), ('PREF25', 'Prefer 25min'), ('PREF45', 'Prefer 45min')], verbose_name='duration', max_length=6),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='language',
            field=models.CharField(choices=[('ENG', 'English'), ('CHI', 'Chinese')], verbose_name='language', max_length=3),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='objectives',
            field=models.TextField(verbose_name='objectives', help_text="What will attendees get out of your talk? When they leave the room, what will they know that they didn't know before?"),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='outline',
            field=models.TextField(verbose_name='outline', default='', help_text='How the talk will be arranged. It is highly recommended to attach the estimated time length for each sections in the talk. Talks in favor of 45min should have a fallback plan about how to shrink the content into a 25min one.', blank=True),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='python_level',
            field=models.CharField(choices=[('NOVICE', 'Novice'), ('INTERMEDIATE', 'Intermediate'), ('EXPERIENCED', 'Experienced')], verbose_name='python level', max_length=12, help_text='The choice of talk level matters during the review process. More definition of talk level can be found at the Talk Level Definition in [How to Propose a talk] page. Note that a proposal who\'t be more likely to accepted because of being "Novice" level. We may contact you to change the talk level when we find the contend is too-hard or too-easy for the target audience.'),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='recording_policy',
            field=models.BooleanField(choices=[(True, 'Yes'), (False, 'No')], verbose_name='recording policy', max_length=1, help_text='Description: If you agree to give permission to PyCon Taiwan to record, edit, and release audio and video of your presentation, please check this box. See [Recoding Release] for details.'),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='slide_link',
            field=models.URLField(blank=True, verbose_name='slide link', default='', help_text='You can add your slide link near or after the conference day. Not required for review.'),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='supplementary',
            field=models.TextField(verbose_name='supplementary', default='', help_text="Anything else you'd like the program committee to know when making their selection: your past speaking experience, open source community experience, etc.", blank=True),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='target_audience',
            field=models.CharField(verbose_name='target audience', max_length=140, help_text='Who is the intended audience for your talk? (Be specific, "Python users" is not a good answer)'),
        ),
        migrations.AlterField(
            model_name='proposal',
            name='title',
            field=models.CharField(verbose_name='title', max_length=140),
        ),
        migrations.RunPython(
            code=check_user_1,
            reverse_code=migrations.RunPython.noop,
        ),
        migrations.AddField(
            model_name='proposal',
            name='submitter',
            field=models.ForeignKey(verbose_name='submitter', on_delete=models.CASCADE, to=settings.AUTH_USER_MODEL, default=1),
            preserve_default=False,
        ),
    ]


text:
<?php

/* :arbeitsbuehnen:lkw.html.twig */
class __TwigTemplate_eb3e03985391b3037295577cea8708dee83f654547ed61ea1331df9a363382d6 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 2
        echo "

    ";
        // line 3
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["buehnen"]) ? $context["buehnen"] : $this->getContext($context, "buehnen")));
        foreach ($context['_seq'] as $context["_key"] => $context["buehne"]) {
            // line 4
            echo "
";
            echo twig_escape_filter($this->env, $this->getAttribute($context["buehne"], "name", array()), "html", null, true);
            echo "

    ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['buehne'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 6
        echo "
";
    }

    public function getTemplateName()
    {
        return ":arbeitsbuehnen:lkw.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  35 => 6,  26 => 4,  22 => 3,  19 => 2,);
    }
}


text:
"""
Volume driver for Pure Storage FlashArray storage system.

This driver requires Purity version 3.4.0 or later.
"""

import cookielib
import json
import urllib2

from oslo.config import cfg

from cinder import exception
from cinder.openstack.common import excutils
from cinder.openstack.common.gettextutils import _
from cinder.openstack.common import log as logging
from cinder.openstack.common import processutils
from cinder.openstack.common import units
from cinder import utils
from cinder.volume.drivers.san import san

LOG = logging.getLogger(__name__)

PURE_OPTS = [
    cfg.StrOpt("pure_api_token", default=None,
               help="REST API authorization token."),
]

CONF = cfg.CONF
CONF.register_opts(PURE_OPTS)

def _get_vol_name(volume):
    """Return the name of the volume Purity will use."""
    return volume["name"] + "-cinder"

def _get_snap_name(snapshot):
    """Return the name of the snapshot that Purity will use."""
    return "{0}-cinder.{1}".format(snapshot["volume_name"],
                                   snapshot["name"])

class PureISCSIDriver(san.SanISCSIDriver):
    """Performs volume management on Pure Storage FlashArray."""

    VERSION = "1.0.0"

    def __init__(self, *args, **kwargs):
        execute = kwargs.pop("execute", utils.execute)
        super(PureISCSIDriver, self).__init__(execute=execute, *args, **kwargs)
        self.configuration.append_config_values(PURE_OPTS)
        self._array = None
        self._iscsi_port = None
        self._backend_name = (self.configuration.volume_backend_name or
                              self.__class__.__name__)

    def do_setup(self, context):
        """Performs driver initialization steps that could raise exceptions."""
        # Raises PureDriverException if unable to connect and PureAPIException
        # if unable to authenticate.
        self._array = FlashArray(
            self.configuration.san_ip,
            self.configuration.pure_api_token)
        self._iscsi_port = self._choose_target_iscsi_port()

    def check_for_setup_error(self):
        # Avoid inheriting check_for_setup_error from SanDriver, which checks
        # for san_password or san_private_key, not relevant to our driver.
        pass

    def create_volume(self, volume):
        """Creates a volume."""
        LOG.debug("Enter PureISCSIDriver.create_volume.")
        vol_name = _get_vol_name(volume)
        vol_size = volume["size"] * units.Gi
        self._array.create_volume(vol_name, vol_size)
        LOG.debug("Leave PureISCSIDriver.create_volume.")

    def create_volume_from_snapshot(self, volume, snapshot):
        """Creates a volume from a snapshot."""
        LOG.debug("Enter PureISCSIDriver.create_volume_from_snapshot.")
        vol_name = _get_vol_name(volume)
        snap_name = _get_snap_name(snapshot)
        self._array.copy_volume(snap_name, vol_name)
        self._extend_if_needed(vol_name, snapshot["volume_size"],
                               volume["size"])
        LOG.debug("Leave PureISCSIDriver.create_volume_from_snapshot.")

    def create_cloned_volume(self, volume, src_vref):
        """Creates a clone of the specified volume."""
        LOG.debug("Enter PureISCSIDriver.create_cloned_volume.")
        vol_name = _get_vol_name(volume)
        src_name = _get_vol_name(src_vref)
        self._array.copy_volume(src_name, vol_name)
        self._extend_if_needed(vol_name, src_vref["size"], volume["size"])
        LOG.debug("Leave PureISCSIDriver.create_cloned_volume.")

    def _extend_if_needed(self, vol_name, src_size, vol_size):
        """Extend the volume from size src_size to size vol_size."""
        if vol_size > src_size:
            vol_size = vol_size * units.Gi
            self._array.extend_volume(vol_name, vol_size)

    def delete_volume(self, volume):
        """Deletes a volume."""
        LOG.debug("Enter PureISCSIDriver.delete_volume.")
        vol_name = _get_vol_name(volume)
        try:
            self._array.destroy_volume(vol_name)
        except exception.PureAPIException as err:
            with excutils.save_and_reraise_exception as ctxt:
                if err.kwargs["code"] == 400:
                    # This happens if the volume does not exist.
                    ctxt.reraise = False
                    LOG.error(_("Disconnection failed with message: {}"
                                ).format(err.msg))
        LOG.debug("Leave PureISCSIDriver.delete_volume.")

    def create_snapshot(self, snapshot):
        """Creates a snapshot."""
        LOG.debug("Enter PureISCSIDriver.create_snapshot.")
        vol_name, snap_suff = _get_snap_name(snapshot).split(".")
        self._array.create_snapshot(vol_name, snap_suff)
        LOG.debug("Leave PureISCSIDriver.create_snapshot.")

    def delete_snapshot(self, snapshot):
        """Deletes a snapshot."""
        LOG.debug("Enter PureISCSIDriver.delete_snapshot.")
        snap_name = _get_snap_name(snapshot)
        try:
            self._array.destroy_volume(snap_name)
        except exception.PureAPIException as err:
            with excutils.save_and_reraise_exception as ctxt:
                if err.kwargs["code"] == 400:
                    # This happens if the snapshot does not exist.
                    ctxt.reraise = False
                    LOG.error(_("Disconnection failed with message: {}"
                                ).format(err.msg))
        LOG.debug("Leave PureISCSIDriver.delete_snapshot.")

    def initialize_connection(self, volume, connector):
        """Allow connection to connector and return connection info."""
        LOG.debug("Enter PureISCSIDriver.initialize_connection.")
        target_port = self._get_target_iscsi_port()
        connection = self._connect(volume, connector)
        properties = {
            "driver_volume_type": "iscsi",
            "data": {
                "target_iqn": target_port["iqn"],
                "target_portal": target_port["portal"],
                "target_lun": connection["lun"],
                "target_discovered": True,
                "access_mode": "rw",
            },
        }
        LOG.debug("Leave PureISCSIDriver.initialize_connection. "
                  "Return value: " + str(properties))
        return properties

    def _get_target_iscsi_port(self):
        """Return dictionary describing iSCSI-enabled port on target array."""
        try:
            self._run_iscsiadm_bare(["-m", "discovery", "-t", "sendtargets",
                                     "-p", self._iscsi_port["portal"]])
        except processutils.ProcessExecutionError as err:
            LOG.warn(_("iSCSI discovery of port {0[name]} at {0[portal]} "
                       "failed with error: {1}").format(self._iscsi_port,
                                                        err.stderr))
            self._iscsi_port = self._choose_target_iscsi_port()
        return self._iscsi_port

    def _choose_target_iscsi_port(self):
        """Find a reachable iSCSI-enabled port on target array."""
        ports = self._array.list_ports()
        iscsi_ports = [port for port in ports if port["iqn"]]
        for port in iscsi_ports:
            try:
                self._run_iscsiadm_bare(["-m", "discovery",
                                         "-t", "sendtargets",
                                         "-p", port["portal"]])
            except processutils.ProcessExecutionError as err:
                LOG.debug(("iSCSI discovery of port {0[name]} at {0[portal]} "
                           "failed with error: {1}").format(port, err.stderr))
            else:
                LOG.info(_("Using port {0[name]} on the array at {0[portal]} "
                           "for iSCSI connectivity.").format(port))
                return port
        raise exception.PureDriverException(
            reason=_("No reachable iSCSI-enabled ports on target array."))

    def _connect(self, volume, connector):
        """Connect the host and volume; return dict describing connection."""
        host_name = self._get_host_name(connector)
        vol_name = _get_vol_name(volume)
        return self._array.connect_host(host_name, vol_name)

    def _get_host_name(self, connector):
        """Return dictionary describing the Purity host with initiator IQN."""
        hosts = self._array.list_hosts()
        for host in hosts:
            if connector["initiator"] in host["iqn"]:
                return host["name"]
        raise exception.PureDriverException(
            reason=(_("No host object on target array with IQN: ") +
                    connector["initiator"]))

    def terminate_connection(self, volume, connector, **kwargs):
        """Terminate connection."""
        LOG.debug("Enter PureISCSIDriver.terminate_connection.")
        vol_name = _get_vol_name(volume)
        try:
            host_name = self._get_host_name(connector)
            self._array.disconnect_host(host_name, vol_name)
        except exception.PureAPIException as err:
            with excutils.save_and_reraise_exception as ctxt:
                if err.kwargs["code"] == 400:
                    # This happens if the host and volume are not connected
                    ctxt.reraise = False
                    LOG.error(_("Disconnection failed with message: {}"
                                ).format(err.msg))
        LOG.debug("Leave PureISCSIDriver.terminate_connection.")

    def get_volume_stats(self, refresh=False):
        """Return the current state of the volume service.

        If 'refresh' is True, run the update first.
        """

        LOG.debug("Enter PureISCSIDriver.get_volume_stats.")
        if refresh:
            LOG.debug("Updating volume stats.")
            self._update_stats()
        LOG.debug("Leave PureISCSIDriver.get_volume_stats.")
        return self._stats

    def _update_stats(self):
        """Set self._stats with relevant information."""
        info = self._array.get_array(space=True)
        total = float(info["capacity"]) / units.Gi
        free = float(info["capacity"] - info["total"]) / units.Gi
        data = {"volume_backend_name": self._backend_name,
                "vendor_name": "Pure Storage",
                "driver_version": self.VERSION,
                "storage_protocol": "iSCSI",
                "total_capacity_gb": total,
                "free_capacity_gb": free,
                "reserved_percentage": 0,
                }
        self._stats = data

    def extend_volume(self, volume, new_size):
        """Extend volume to new_size."""
        LOG.debug("Enter PureISCSIDriver.extend_volume.")
        vol_name = _get_vol_name(volume)
        new_size = new_size * units.Gi
        self._array.extend_volume(vol_name, new_size)
        LOG.debug("Leave PureISCSIDriver.extend_volume.")

class FlashArray(object):
    """Wrapper for Pure Storage REST API."""
    SUPPORTED_REST_API_VERSIONS = ["1.2", "1.1", "1.0"]

    def __init__(self, target, api_token):
        cookie_handler = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
        self._opener = urllib2.build_opener(cookie_handler)
        self._target = target
        self._rest_version = self._choose_rest_version()
        self._root_url = "https://{0}/api/{1}/".format(target,
                                                       self._rest_version)
        self._api_token = api_token
        self._start_session()

    def _http_request(self, method, path, data=None, reestablish_session=True):
        """Perform HTTP request for REST API."""
        req = urllib2.Request(self._root_url + path,
                              headers={"Content-Type": "application/json"})
        req.get_method = lambda: method
        body = json.dumps(data)
        try:
            # Raises urllib2.HTTPError if response code != 200
            response = self._opener.open(req, body)
        except urllib2.HTTPError as err:
            if (reestablish_session and err.code == 401):
                self._start_session()
                return self._http_request(method, path, data,
                                          reestablish_session=False)
            elif err.code == 450:
                # Purity REST API version is bad
                new_version = self._choose_rest_version()
                if new_version == self._rest_version:
                    raise exception.PureAPIException(
                        code=err.code,
                        reason=(_("Unable to find usable REST API version. "
                                  "Response from Pure Storage REST API: ") +
                                err.read()))
                self._rest_version = new_version
                self._root_url = "https://{0}/api/{1}/".format(
                    self._target,
                    self._rest_version)
                return self._http_request(method, path, data)
            else:
                raise exception.PureAPIException(code=err.code,
                                                 reason=err.read())
        except urllib2.URLError as err:
            # Error outside scope of HTTP status codes,
            # e.g., unable to resolve domain name
            raise exception.PureDriverException(
                reason=_("Unable to connect to {0!r}. Check san_ip."
                         ).format(self._target))
        else:
            content = response.read()
            if "application/json" in response.info().get('Content-Type'):
                return json.loads(content)
            raise exception.PureAPIException(
                reason=(_("Response not in JSON: ") + content))

    def _choose_rest_version(self):
        """Return a REST API version."""
        self._root_url = "https://{0}/api/".format(self._target)
        data = self._http_request("GET", "api_version")
        available_versions = data["version"]
        available_versions.sort(reverse=True)
        for version in available_versions:
            if version in FlashArray.SUPPORTED_REST_API_VERSIONS:
                return version
        raise exception.PureDriverException(
            reason=_("All REST API versions supported by this version of the "
                     "Pure Storage iSCSI driver are unavailable on array."))

    def _start_session(self):
        """Start a REST API session."""
        self._http_request("POST", "auth/session",
                           {"api_token": self._api_token},
                           reestablish_session=False)

    def get_array(self, **kwargs):
        """Return a dictionary containing information about the array."""
        return self._http_request("GET", "array", kwargs)

    def create_volume(self, name, size):
        """Create a volume and return a dictionary describing it."""
        return self._http_request("POST", "volume/{0}".format(name),
                                  {"size": size})

    def copy_volume(self, source, dest):
        """Clone a volume and return a dictionary describing the new volume."""
        return self._http_request("POST", "volume/{0}".format(dest),
                                  {"source": source})

    def create_snapshot(self, volume, suffix):
        """Create a snapshot and return a dictionary describing it."""
        data = {"source": [volume], "suffix": suffix, "snap": True}
        return self._http_request("POST", "volume", data)[0]

    def destroy_volume(self, volume):
        """Destroy an existing volume or snapshot."""
        return self._http_request("DELETE", "volume/{0}".format(volume))

    def extend_volume(self, volume, size):
        """Extend a volume to a new, larger size."""
        return self._http_request("PUT", "volume/{0}".format(volume),
                                  {"size": size, "truncate": False})

    def list_hosts(self, **kwargs):
        """Return a list of dictionaries describing each host."""
        return self._http_request("GET", "host", kwargs)

    def connect_host(self, host, volume, **kwargs):
        """Create a connection between a host and a volume."""
        return self._http_request("POST",
                                  "host/{0}/volume/{1}".format(host, volume),
                                  kwargs)

    def disconnect_host(self, host, volume):
        """Delete a connection between a host and a volume."""
        return self._http_request("DELETE",
                                  "host/{0}/volume/{1}".format(host, volume))

    def list_ports(self, **kwargs):
        """Return a list of dictionaries describing ports."""
        return self._http_request("GET", "port", kwargs)


text:
description: Start running your Golang Buffalo Application on Azure quickly and cheaply.
page_type: sample
products:
- azure
- azure-resource-manager
urlFragment: gobuffalo
languages:
- json
---
# Buffalo Web App

![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/buffalo/gobuffalo/PublicLastTestDate.svg)
![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/buffalo/gobuffalo/PublicDeployment.svg)

![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/buffalo/gobuffalo/FairfaxLastTestDate.svg)
![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/buffalo/gobuffalo/FairfaxDeployment.svg)

![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/buffalo/gobuffalo/BestPracticeResult.svg)
![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/buffalo/gobuffalo/CredScanResult.svg)

[![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Fbuffalo%2Fgobuffalo%2Fazuredeploy.json)
[![Deploy To Azure US Gov](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazuregov.svg?sanitize=true)](https://portal.azure.us/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Fbuffalo%2Fgobuffalo%2Fazuredeploy.json)
[![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Fbuffalo%2Fgobuffalo%2Fazuredeploy.json)

For information about Buffalo and Azure, visit [https://github.com/Azure/buffalo-azure](https://github.com/Azure/buffalo-azure)

`Tags: Microsoft.Web/sites, [if(equals(parameters('database'), 'mysql'), 'mysql', 'custom')], Microsoft.Web/serverfarms, Microsoft.DBforPostgreSQL/servers, firewallRules, Microsoft.DBforMySQL/servers`


text:
package owltools.gaf.rules.go;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import owltools.gaf.Bioentity;
import owltools.gaf.ExtensionExpression;
import owltools.gaf.GafDocument;
import owltools.gaf.GeneAnnotation;
import owltools.gaf.inference.AnnotationPredictor;
import owltools.gaf.inference.BasicAnnotationPropagator;
import owltools.gaf.inference.FoldBasedPredictor;
import owltools.gaf.inference.Prediction;
import owltools.gaf.rules.AbstractAnnotationRule;
import owltools.gaf.rules.AnnotationRuleViolation;
import owltools.graph.OWLGraphWrapper;

public class GoAnnotationPredictionRule extends AbstractAnnotationRule {

	private static final Logger LOG = Logger.getLogger(GoAnnotationPredictionRule.class);

	/**
	 * The string to identify this class in the annotation_qc.xml and related factories.
	 * This is not supposed to be changed.
	 */
	public static final String PERMANENT_JAVA_ID = "org.geneontology.gold.rules.GoAnnotationPredictionRule";

	private static boolean USE_BASIC_PROPAGATION_RULE = true;

	private final OWLGraphWrapper source;

	public GoAnnotationPredictionRule(OWLGraphWrapper source) {
		super();
		this.source = source;
	}

	@Override
	public Set<AnnotationRuleViolation> getRuleViolations(GeneAnnotation a) {
		// Do nothing
		return Collections.emptySet();
	}

	@Override
	public boolean isAnnotationLevel() {
		// Deactivate annotation level
		return false;
	}

	@Override
	public List<Prediction> getPredictedAnnotations(GafDocument gafDoc, OWLGraphWrapper graph) {
		List<Prediction> predictions = new ArrayList<Prediction>();

		Map<Bioentity, Set<GeneAnnotation>> allAnnotations = new HashMap<Bioentity, Set<GeneAnnotation>>();
		boolean hasC16Annotations = false;

		for(GeneAnnotation annotation : gafDoc.getGeneAnnotations()) {
			List<List<ExtensionExpression>> expressions = annotation.getExtensionExpressions();
			if (expressions != null && expressions.isEmpty() == false) {
				hasC16Annotations = true;
			}
			Bioentity e = annotation.getBioentityObject();
			String id = e.getId();
			Set<GeneAnnotation> anns = allAnnotations.get(id);
			if (anns == null) {
				anns = new HashSet<GeneAnnotation>();
				allAnnotations.put(e, anns);
			}
			anns.add(annotation);
		}

		if (USE_BASIC_PROPAGATION_RULE) {
			LOG.info("Start creating predictions using basic propagation");
			AnnotationPredictor predictor = null;
			try {
				predictor = new BasicAnnotationPropagator(gafDoc, source, false);
				if (predictor.isInitialized()) {
					List<Prediction> basicPredictions = predictor.predictForBioEntities(allAnnotations);
					if (basicPredictions != null) {
						predictions.addAll(basicPredictions);
					}
				}
				else {
					LOG.error("Could not create predictions.");
				}
			} finally {
				if (predictor != null) {
					predictor.dispose();
				}
				predictor = null;
			}
			LOG.info("Done creating predictions using basic propagation");
		}
		if (hasC16Annotations) {
			LOG.info("Use c16 extension for fold based prediction");
			AnnotationPredictor predictor = null;
			try {
				predictor = new FoldBasedPredictor(gafDoc, source, false);
				if (predictor.isInitialized()) {
					LOG.info("Start prediction for "+allAnnotations.size()+" bioentities");
					List<Prediction> foldBasedPredictions = predictor.predictForBioEntities(allAnnotations);
					if (foldBasedPredictions != null) {
						predictions.addAll(foldBasedPredictions);
					}
				}
				else {
					LOG.error("Could not create predictions.");
				}
			}
			finally {
				if (predictor != null) {
					predictor.dispose();
				}
				predictor = null;
			}
			LOG.info("Done creating fold based prediction");
		}

		return predictions;
	}

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

}


text:
package com.hotf.client.view.control;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.gwt.user.client.ui.ValueBoxBase;
import com.google.gwt.user.client.ui.Widget;

public class Chooser extends Composite implements HasSelectionHandlers<Suggestion>, HasText {

	interface MyUiBinder extends UiBinder<Widget, Chooser> {
	}

	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	private String selectedOnFocus;
	private boolean clearOnSelect = false;
	private boolean changed = false;

	@UiField Label viewField;
	@UiField (provided=true) SuggestBox suggestBoxField;

	public Chooser(SuggestOracle suggestOracle) {

		super();

		suggestBoxField = new SuggestBox(suggestOracle);
		suggestBoxField.setAutoSelectEnabled(true);
		addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
			@Override
			public void onSelection(SelectionEvent<Suggestion> event) {
				String value = event.getSelectedItem().getReplacementString();
				if (value != null && !value.equals(selectedOnFocus)) {
					changed = true;
					Chooser.this.setText(value);
				}
				suggestBoxField.getValueBox().setFocus(false);
			}
		});

		suggestBoxField.getValueBox().addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent event) {
				selectedOnFocus = suggestBoxField.getText();
				changed = false;
				if (clearOnSelect) {
					suggestBoxField.setText("");
				}
				suggestBoxField.showSuggestionList();
			}
		});
		initWidget(uiBinder.createAndBindUi(this));

		suggestBoxField.getValueBox().addBlurHandler(new BlurHandler() {
			@Override
			public void onBlur(BlurEvent event) {
				if (clearOnSelect && !changed) {
					suggestBoxField.setText(selectedOnFocus);
				}
			}
		});

	}

	@Override
	public HandlerRegistration addSelectionHandler(SelectionHandler<Suggestion> handler) {
		return suggestBoxField.addSelectionHandler(handler);
	}

	@Override
	public void setText(String text) {
		viewField.setText(text);
		suggestBoxField.setValue(text);
		findFieldSize();
	}

	@Override
	public String getText() {
		return suggestBoxField.getText();
	}

	private void findFieldSize() {
		viewField.setVisible(true);
		boolean v = isVisible();
		if (!v) {
			setVisible(true);
		}
		if (!v) {
			setVisible(false);
		}
		viewField.setVisible(false);
	}

	@Override
	protected void onLoad() {
		findFieldSize();

	}

	public ValueBoxBase<String> getTextBox() {
		return suggestBoxField.getValueBox();
	}

	/**
	 * @param clearOnSelect the clearOnSelect to set
	 */
	public void setClearOnSelect(boolean clearOnSelect) {
		this.clearOnSelect = clearOnSelect;
	}

}


text:
import { Component, ChangeDetectionStrategy, AfterViewInit, ViewChild } from '@angular/core';
import { DataService, Atom } from '../data.service';
import { Observable } from 'rxjs';
import { Command, GridComponent, RowDetailsStatus } from 'ng2-qgrid';

const EXAMPLE_TAGS =
  ['details-row-api', 'Details section of every row can be expanded/collapsed using UI buttons in toolbar and chevron buttons'];

@Component({
  selector: 'example-details-row-api',
  templateUrl: 'example-details-row-api.component.html',
  styleUrls: ['example-details-row-api.component.scss'],
  providers: [DataService],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ExampleDetailsRowApiComponent implements AfterViewInit {
  @ViewChild(GridComponent, { static: true }) grid: GridComponent;

  static tags = EXAMPLE_TAGS;
  title = EXAMPLE_TAGS[1];

  rows$: Observable<Atom[]>;
  canExpand = true;

  expandAllCommand = new Command({
    execute: () => {
      const { model } = this.grid;
      const { rows } = model.data();
      model.row({
        status: new Map(rows.map<[Atom, RowDetailsStatus]>(x => [x, new RowDetailsStatus(true)])),
      });
    },
  });

  collapseAllCommand = new Command({
    execute: () => {
      const { model } = this.grid;
      const { rows } = model.data();
      model.row({
        status: new Map(rows.map<[Atom, RowDetailsStatus]>(x => [x, new RowDetailsStatus(false)])),
      });
    },
  });

  expandSecondCommand = new Command({
    execute: () => {
      this.collapseAllCommand.execute();
      const { model } = this.grid;
      const theSecondRow = model.data().rows[1];

      model.row({
        status: new Map([[theSecondRow, new RowDetailsStatus(true)]]),
      });
    },
  });

  toggle = new Command({
    canExecute: () => this.canExpand,
  });

  disableExpand = new Command({
    execute: () => {
      this.canExpand = false;
      this.toggle.canExecuteCheck.next();
    },
  });

  enableExpand = new Command({
    execute: () => {
      this.canExpand = true;
      this.toggle.canExecuteCheck.next();
    },
  });

  constructor(dataService: DataService) {
    this.rows$ = dataService.getAtoms();
  }

  ngAfterViewInit() {
    const { model } = this.grid;
    model.row({
      toggle: this.toggle,
    });
  }
}


text:
package cl

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestCL(t *testing.T) {
	params := GetDefaultParamSizes()
	attrCount := NewAttrCount(5, 1, 0) // TODO: integrate this into GetDefaultParamSizes

	org, err := NewOrg(params, attrCount)
	if err != nil {
		t.Errorf("error when generating CL org: %v", err)
	}

	// to generate new testing keys
	//WriteGob("../../client/testdata/clPubKey.gob", org.Keys.Pub)
	//WriteGob("../../client/testdata/clSecKey.gob", org.Keys.Sec)

	masterSecret := org.Keys.Pub.GenerateUserMasterSecret()

	cred := NewRawCred(attrCount)
	_ = cred.AddStrAttr("Name", "Jack", true)
	_ = cred.AddStrAttr("Gender", "M", true)
	_ = cred.AddStrAttr("Graduated", "true", true)
	_ = cred.AddInt64Attr("DateMin", 22342345, true)
	_ = cred.AddInt64Attr("DateMax", 32342345, true)
	_ = cred.AddInt64Attr("Age", 25, false)

	credMgr, err := NewCredManager(params, org.Keys.Pub, masterSecret, cred)
	if err != nil {
		t.Errorf("error when creating a user: %v", err)
	}

	credManagerPath := "../client/testdata/credManager.gob"
	WriteGob(credManagerPath, credMgr)

	credIssueNonceOrg := org.GetCredIssueNonce()

	credReq, err := credMgr.GetCredRequest(credIssueNonceOrg)
	if err != nil {
		t.Errorf("error when generating credential request: %v", err)
	}

	res, err := org.IssueCred(credReq)
	if err != nil {
		t.Errorf("error when issuing credential: %v", err)
	}

	// Store record to db
	mockDb := NewMockRecordManager()
	if err := mockDb.Store(credReq.Nym, res.Record); err != nil {
		t.Errorf("error saving record to db: %v", err)
	}

	userVerified, err := credMgr.Verify(res.Cred, res.AProof)
	if err != nil {
		t.Errorf("error when verifying credential: %v", err)
	}
	assert.Equal(t, true, userVerified, "credential proof not valid")

	// Before updating a credential, create a new Org object (obtaining and updating
	// credential usually don't happen at the same time)
	org, err = NewOrgFromParams(params, org.Keys)
	if err != nil {
		t.Errorf("error when generating CL org: %v", err)
	}

	// create new CredManager (updating or proving usually does not happen at the same time
	// as issuing)
	ReadGob(credManagerPath, credMgr)

	// TODO: update to rawcred
	a, _ := cred.GetAttr("Name")
	_ = a.UpdateValue("John")
	credMgr.Update(cred)

	rec, err := mockDb.Load(credMgr.Nym)
	if err != nil {
		t.Errorf("error saving record to db: %v", err)
	}

	newKnownAttrs := cred.GetKnownVals()
	res1, err := org.UpdateCred(credMgr.Nym, rec, credReq.Nonce, newKnownAttrs)
	if err != nil {
		t.Errorf("error when updating credential: %v", err)
	}
	if err := mockDb.Store(credMgr.Nym, res1.Record); err != nil {
		t.Errorf("error saving record to db: %v", err)
	}

	userVerified, err = credMgr.Verify(res1.Cred, res1.AProof)
	if err != nil {
		t.Errorf("error when verifying updated credential: %v", err)
	}
	assert.Equal(t, true, userVerified, "credential update failed")

	// Some other organization which would like to verify the credential can instantiate org without sec key.
	// It only needs Pub key of the organization that issued a credential.
	org, err = NewOrgFromParams(params, org.Keys)
	if err != nil {
		t.Errorf("error when generating CL org: %v", err)
	}

	revealedKnownAttrsIndices := []int{0}         // reveal only the first known attribute
	revealedCommitmentsOfAttrsIndices := []int{0} // reveal only the commitment of the first attribute (of those of which only commitments are known)

	nonce := org.GetProveCredNonce()
	randCred, proof, err := credMgr.BuildProof(res1.Cred, revealedKnownAttrsIndices,
		revealedCommitmentsOfAttrsIndices, nonce)
	if err != nil {
		t.Errorf("error when building credential proof: %v", err)
	}

	revealedKnownAttrs, revealedCommitmentsOfAttrs := credMgr.FilterAttributes(revealedKnownAttrsIndices,
		revealedCommitmentsOfAttrsIndices)

	cVerified, err := org.ProveCred(randCred.A, proof, revealedKnownAttrsIndices,
		revealedCommitmentsOfAttrsIndices, revealedKnownAttrs, revealedCommitmentsOfAttrs)
	if err != nil {
		t.Errorf("error when verifying credential: %v", err)
	}

	assert.Equal(t, true, cVerified, "credential verification failed")
}


text:
import tweepy
from tweepy.error import TweepError
import configparser
from urllib import parse

from ..user import UserCRUD

PATH_TO_CONFIG = 'src/tweetconfig.ini'
def getUsernameForTweet(tweetId, userId, userDataStrategy):
    api = getApi(userId, userDataStrategy)
    tweet = api.get_status(tweetId)
    username = tweet.user.screen_name
    return username

def sendReply(replyMessage, replyId, userId, userDataStrategy):
    api = getApi(userId, userDataStrategy)
    tweet = api.update_status(replyMessage, replyId)
    return tweet.id

def getSingleTweet(tweetIdOrUrl, userId, userDataStrategy):
    api = getApi(userId, userDataStrategy)
    tweetId = ""
    if tweetIdOrUrl.find('/') == -1:
        tweetId = tweetIdOrUrl
    else:
        tweetId = parse.urlparse(tweetIdOrUrl).path.split('/')[-1]

    try:
        tweetToReturn = api.get_status(tweetId)
        return tweetToReturn
    except TweepError as err:
        if err.reason.find("status code = 404") > -1:
            return "No such tweet"
        else:
            return err.reason

def getApi(userId, userDataStrategy):
    global PATH_TO_CONFIG
    user = UserCRUD.getUserById(userId, userDataStrategy)
    config = configparser.ConfigParser()
    config.read(PATH_TO_CONFIG)
    consumer_key = config['TOKEN']['consumerKey']
    consumer_secret = config['TOKEN']['consumerSecret']
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(user.authToken, user.secretToken)
    api = tweepy.API(auth)
    return api

def createAPIObject():
    global PATH_TO_CONFIG
    config = configparser.ConfigParser()
    config.read(PATH_TO_CONFIG)
    consumer_key = config['TOKEN']['consumerKey']
    consumer_secret = config['TOKEN']['consumerSecret']
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    api = tweepy.API(auth)
    return api

def getMentions(userId, count, userDataStrategy):
    api = getApi(userId, userDataStrategy)
    mentions = api.mentions_timeline(count=count)
    return mentions

def getUrlLengths():
    api = createAPIObject()
    configValues = api.configuration()
    return configValues['short_url_length'], configValues['short_url_length_https']


text:
package org.springframework.boot;

import java.io.PrintStream;

import org.junit.After;
import org.junit.Rule;
import org.junit.Test;

import org.springframework.boot.test.OutputCapture;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;

/**
 * Tests for {@link Banner} and its usage by {@link SpringApplication}.
 *
 * @author Phillip Webb
 * @author Michael Stummvoll
 */
public class BannerTests {

	private ConfigurableApplicationContext context;

	@After
	public void cleanUp() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Rule
	public OutputCapture out = new OutputCapture();

	@Test
	public void testDefaultBanner() throws Exception {
		SpringApplication application = new SpringApplication(Config.class);
		application.setWebEnvironment(false);
		this.context = application.run();
		assertThat(this.out.toString(), containsString(":: Spring Boot ::"));
	}

	@Test
	public void testDefaultBannerInLog() throws Exception {
		SpringApplication application = new SpringApplication(Config.class);
		application.setWebEnvironment(false);
		this.context = application.run();
		assertThat(this.out.toString(), containsString(":: Spring Boot ::"));
	}

	@Test
	public void testCustomBanner() throws Exception {
		SpringApplication application = new SpringApplication(Config.class);
		application.setWebEnvironment(false);
		application.setBanner(new DummyBanner());
		this.context = application.run();
		assertThat(this.out.toString(), containsString("My Banner"));
	}

	static class DummyBanner implements Banner {

		@Override
		public void printBanner(Environment environment, Class<?> sourceClass,
				PrintStream out) {
			out.println("My Banner");
		}

	}

	@Configuration
	public static class Config {

	}

}


text:
layout: courseIntroduction
---

# Databases

## Chapters

1) Databases
   1) [Introduction](chapters/01-databases/introduction/index.md)
   2) [Foreign Keys](chapters/01-databases/foreign-keys/index.md)
   3) [Datatypes](chapters/01-databases/datatypes/index.md)
   4) [Indexes](chapters/01-databases/indexes/index.md)
   5) [SQL Language](chapters/01-databases/sql-language/index.md)
   6) [MySQL Client](chapters/01-databases/mysql-client/index.md)
2) [Data Definition (Tables)](chapters/02-tables/index.md)
3) [Data Manipulation](chapters/03-data/index.md)
4) [ER Diagrams](chapters/04-er-diagrams/index.md)
5) [Retreiving Data](chapters/05-retreiving-data/index.md)
   1) [Retreiving Data](chapters/05-retreiving-data/retreiving/index.md)
   2) [Sorting](chapters/05-retreiving-data/sorting/index.md)
   3) [Filtering](chapters/05-retreiving-data/filtering/index.md)
   4) [Calculated Fields](chapters/05-retreiving-data/calculated-fields/index.md)
   5) [Manipulation](chapters/05-retreiving-data/manipulation/index.md)
   6) [Summarizing](chapters/05-retreiving-data/summarizing/index.md)
   7) [Grouping](chapters/05-retreiving-data/grouping/index.md)
6) [Combining Data](chapters/06-combining-data/index.md)
7) [Users & Privileges](chapters/07-users-and-privileges/index.md)
8) [Storing Passwords](chapters/08-passwords/index.md)
9) [Building Applications](chapters/09-applications/index.md)

## Exercises

1) [Software installation](exercises/01-software-installation/index.md)
2) [Setting up example databases](exercises/02-example-databases/index.md)

## Assignments

Under construction


text:
var assert = require('assert');
var StorageApi = require('asposestoragecloud');
var TasksApi = require('asposetaskscloud');
var configProps = require('../Config/config.json');
var data_path = '../../../Data/';

var AppSID = configProps.app_sid;
var AppKey = configProps.api_key;
var config = {'appSid':AppSID,'apiKey':AppKey , 'debug' : true};

// Instantiate Aspose Storage API SDK
var storageApi = new StorageApi(config);
// Instantiate Aspose.Tasks API SDK
var tasksApi = new TasksApi(config);

// Set input file name
var name =  "sample-project-2.mpp";
var taskUid = 1;
var storage = null;
var folder= null;

try {
	// Upload source file to aspose cloud storage
	storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) {
		assert.equal(responseMessage.status, 'OK');

		// Invoke Aspose.Tasks Cloud SDK API to task recurring info
		tasksApi.GetTaskRecurringInfo(name, taskUid, storage, folder, function(responseMessage) {
			assert.equal(responseMessage.status, 'OK');
			var RecurringInfo = responseMessage.body.RecurringInfo;
			console.log(RecurringInfo);
		});
	});

}catch (e) {
  console.log("exception in example");
  console.log(e);
}
//ExEnd:1