text:
```
sbt \
    -Dplugin.version=1.1-SNAPSHOT \
    -Dprofile.name="Example Staging Profile" \
    -Dhost=localhost \
    -Drepo=https://localhost:8081/nexus/service/local

[info] Loading global plugins from /Users/rouquett/.sbt/0.13/plugins
[info] Updating {file:/Users/rouquett/.sbt/0.13/plugins/}global-plugins...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
...
[info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
>
```

### 1. Create a new staging repository for a given staging profile

Use either:
 - `sonatypeOpen "<description>"`
 - `sonatypeOpen "<profile name>" "<description>"`

As a side-effect, two settings will be updated in the SBT state:
 - `publishTo` will be set to the URL of the staging repository: `<repoURL>/staging/deployByRepositoryId/<repoID>`
 - `sonatypeStagingRepositoryProfile` will be set to an `StagingRepositoryProfile` object

```
> sonatypeOpen "Example of creating & publishing to a staging repository"
[info] Nexus repository URL: https://localhost:8081/nexus/service/local
[info] sonatypeProfileName = Example Staging Profile
[info] Reading staging profiles...
[info] Creating staging repository in profile: Example Staging Profile
[info] Created successfully: example_staging_profile-1001
[info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
> show sonatypeStagingRepositoryProfile
[info] [example_staging_profile-1001] status:open, profile:Example Staging Profile(12aadc320d178f)
> show publishTo
[info] Some(Example Staging Profile: https://localhost:8081/nexus/service/local/staging/deployByRepositoryId/example_staging_profile-1001)
>
```

### 2. Publish artifacts using the [Targeted Repository](https://github.com/sonatype/nexus-maven-plugins/blob/master/staging/maven-plugin/WORKFLOWS.md#targeted-repository) strategy.

Since the `publishTo` setting has been updated to point to the newly created staging repository,
the artifacts will be uploaded there. This is equivalent to uploading to a staging repository
using `curl` as described
[here](https://support.sonatype.com/hc/en-us/articles/213465868-Uploading-to-a-Staging-Repository-via-REST-API?page=1#comment_204178478).

```
> publish
[info] Updating {file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/}operations...
[info] Wrote .../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/target/scala-2.10/operations_2.10-0.1.pom
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
[info] :: delivering :: org.xerial.operations#operations_2.10;0.1 :: 0.1 :: release :: Mon Jan 04 09:38:56 PST 2016
[info] 	delivering ivy file to .../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/target/scala-2.10/ivy-0.1.xml
[info] 	published operations_2.10 to https://localhost:8081/nexus/service/local/staging/deployByRepositoryId/example_staging_profile-1001/org/xerial/operations/operations_2.10/0.1/operations_2.10-0.1.pom
[info] 	published operations_2.10 to https://localhost:8081/nexus/service/local/staging/deployByRepositoryId/example_staging_profile-1001/org/xerial/operations/operations_2.10/0.1/operations_2.10-0.1.jar
[info] 	published operations_2.10 to https://localhost:8081/nexus/service/local/staging/deployByRepositoryId/example_staging_profile-1001/org/xerial/operations/operations_2.10/0.1/operations_2.10-0.1-sources.jar
[info] 	published operations_2.10 to https://localhost:8081/nexus/service/local/staging/deployByRepositoryId/example_staging_profile-1001/org/xerial/operations/operations_2.10/0.1/operations_2.10-0.1-javadoc.jar
[success] Total time: 2 s, completed Jan 4, 2016 9:38:58 AM
>
```

### 3. Close, Drop or Release the staging repository

```
> show sonatypeStagingRepositoryProfile
[info] [example_staging_profile-1001] status:open, profile:Example Staging Profile(12aadc320d178f)
> sonatypeClose
[info] Nexus repository URL: https://localhost:8081/nexus/service/local
[info] sonatypeProfileName = Example Staging Profile
[info] Reading staging repository profiles...
[info] Reading staging profiles...
[info] Closing staging repository [example_staging_profile-1001] status:open, profile:Example Staging Profile(12aadc320d178f)
[info] Activity open started:2016-01-04T09:38:00.167-08:00, stopped:2016-01-04T09:38:00.196-08:00
[info] repositoryCreated: id:example_staging_profile-1001, user:rouquett, ip:137.79.22.153
[info] Activity close started:2016-01-04T09:48:59.092-08:00, stopped:2016-01-04T09:48:59.159-08:00
[info]      email: to:Nicolas.F.Rouquette@jpl.nasa.gov
[info] repositoryClosed: id:example_staging_profile-1001
[info] Closed successfully
[info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
> show sonatypeStagingRepositoryProfile
[info] [example_staging_profile-1001] status:closed, profile:Example Staging Profile(12aadc320d178f)
> sonatypeList
[info] Nexus repository URL: https://localhost:8081/nexus/service/local
[info] sonatypeProfileName = Example Staging Profile
[info] Reading staging profiles...
[info] Staging profiles (profileName:Example Staging Profile):
[info] StagingProfile(12aadc320d178f,Example Staging Profile,1)
> sonatypeStagingRepositoryProfiles
[info] Nexus repository URL: https://localhost:8081/nexus/service/local
[info] sonatypeProfileName = Example Staging Profile
[info] Reading staging repository profiles...
[info] Staging repository profiles (sonatypeProfileName:Example Staging Profile):
[info] [example_staging_profile-1001] status:closed, profile:Example Staging Profile(12aadc320d178f)
>

```

## Multi-session workflow example

It is possible to perform staging-related operations across separate SBT sessions.

### SBT session creating a staging repository

```
sbt \
    -Dplugin.version=1.1-SNAPSHOT \
    -Dprofile.name="Example Staging Profile" \
    -Dhost=localhost \
    -Drepo=https://localhost:8081/nexus/service/local

[info] Loading global plugins from /Users/rouquett/.sbt/0.13/plugins
[info] Updating {file:/Users/rouquett/.sbt/0.13/plugins/}global-plugins...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
...
[info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
> sonatypeOpen "dummy"
 [info] Nexus repository URL: https://localhost:8081/nexus/service/local
 [info] sonatypeProfileName = Example Staging Profile
 [info] Reading staging profiles...
 [info] Creating staging repository in profile: Example Staging Profile
 [info] Created successfully: example_staging_profile-1005
 [info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
```

### Another SBT session closing a staging repository

```
sbt \
    -Dplugin.version=1.1-SNAPSHOT \
    -Dprofile.name="Example Staging Profile" \
    -Dhost=localhost \
    -Drepo=https://localhost:8081/nexus/service/local

[info] Loading global plugins from /Users/rouquett/.sbt/0.13/plugins
[info] Updating {file:/Users/rouquett/.sbt/0.13/plugins/}global-plugins...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
...
[info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
> sonatypeStagingRepositoryProfiles
[info] Nexus repository URL: https://localhost:8081/nexus/service/local
[info] sonatypeProfileName = Example Staging Profile
[info] Reading staging repository profiles...
[info] Staging repository profiles (sonatypeProfileName:Example Staging Profile):
[info] [example_staging_profile-1005] status:open, profile:Example Staging Profile(12aadc320d178f)
> sonatypeClose example_staging_profile-1005
[info] Nexus repository URL: https://localhost:8081/nexus/service/local
[info] sonatypeProfileName = Example Staging Profile
[info] Reading staging repository profiles...
[info] Reading staging profiles...
[info] Closing staging repository [example_staging_profile-1005] status:open, profile:Example Staging Profile(12aadc320d178f)
[info] Activity open started:2016-01-04T10:55:21.775-08:00, stopped:2016-01-04T10:55:21.820-08:00
[info] repositoryCreated: id:example_staging_profile-1005, user:rouquett, ip:137.79.22.153
[info] Activity close started:2016-01-04T11:05:13.610-08:00, stopped:2016-01-04T11:05:13.659-08:00
[info]      email: to:Nicolas.F.Rouquette@jpl.nasa.gov
[info] repositoryClosed: id:example_staging_profile-1005
[info] Closed successfully
[info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
>
```

### Another SBT session promoting a staging repository

```
sbt \
    -Dplugin.version=1.1-SNAPSHOT \
    -Dprofile.name="Example Staging Profile" \
    -Dhost=localhost \
    -Drepo=https://localhost:8081/nexus/service/local

[info] Loading global plugins from /Users/rouquett/.sbt/0.13/plugins
[info] Updating {file:/Users/rouquett/.sbt/0.13/plugins/}global-plugins...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
...
[info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
> sonatypeStagingRepositoryProfiles
[info] Nexus repository URL: https://localhost:8081/nexus/service/local
[info] sonatypeProfileName = Example Staging Profile
[info] Reading staging repository profiles...
[info] Staging repository profiles (sonatypeProfileName:Example Staging Profile):
[info] [example_staging_profile-1005] status:closed, profile:Example Staging Profile(12aadc320d178f)
> sonatypeRelease example_staging_profile-1005
[info] Nexus repository URL: https://localhost:8081/nexus/service/local
[info] sonatypeProfileName = Example Staging Profile
[info] Reading staging repository profiles...
[info] Repository example_staging_profile-1005 is already closed
[info] Activity open started:2016-01-04T10:55:21.775-08:00, stopped:2016-01-04T10:55:21.820-08:00
[info] repositoryCreated: id:example_staging_profile-1005, user:rouquett, ip:137.79.22.153
[info] Activity close started:2016-01-04T11:05:13.610-08:00, stopped:2016-01-04T11:05:13.659-08:00
[info]      email: to:Nicolas.F.Rouquette@jpl.nasa.gov
[info] repositoryClosed: id:example_staging_profile-1005
[info] Closed successfully
[info] Reading staging profiles...
[info] Promoting staging repository [example_staging_profile-1005] status:closed, profile:Example Staging Profile(12aadc320d178f)
[info] Activity release started:2016-01-04T11:08:20.954-08:00, stopped:2016-01-04T11:08:21.000-08:00
[info]   Evaluate: id:nx-internal-ruleset, rule:RepositoryWritePolicy
[info]   Evaluate: RepositoryWritePolicy
[info]     Passed: RepositoryWritePolicy
[info]     Passed: id:nx-internal-ruleset
[info]  copyItems: source:example_staging_profile-1005, target:jpl.beta.releases
[info]      email: to:Nicolas.F.Rouquette@jpl.nasa.gov
[info] repositoryReleased: id:example_staging_profile-1005, target:jpl.beta.releases
[info] Promoted successfully
[info] Dropping staging repository [example_staging_profile-1005] status:released, profile:Example Staging Profile(12aadc320d178f)
[info] Dropped successfully: example_staging_profile-1005
[info] Set current project to operations (in build file:.../sbt-sonatype/src/sbt-test/sbt-sonatype/operations/)
>
```


text:
package io.datarouter.aws.elb.job;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.amazonaws.services.elasticloadbalancingv2.model.LoadBalancer;
import com.amazonaws.services.elasticloadbalancingv2.model.LoadBalancerSchemeEnum;

import io.datarouter.aws.elb.service.ElbService;
import io.datarouter.storage.config.properties.DatarouterServerTypeSupplier;
import io.datarouter.storage.util.Ec2InstanceDetailsDto;
import io.datarouter.storage.util.Ec2InstanceTool;
import io.datarouter.web.autoconfig.ConfigScanDto;
import io.datarouter.web.autoconfig.ConfigScanResponseTool;
import io.datarouter.web.config.service.PrivateDomain;
import io.datarouter.web.config.service.PublicDomain;

@Singleton
public class AwsElbConfigScanner{

	private static final String HAS_PUBLIC_LOAD_BALANCER_KEY = "hasPublicAlb";
	private static final String HAS_PRIVATE_LOAD_BALANCER_KEY = "hasPrivateAlb";
	private static final String UNKNOWN_LOAD_BALANCER = "unknownAlb";

	@Inject
	private DatarouterServerTypeSupplier serverTypeSupplier;
	@Inject
	private ElbService elbService;
	@Inject
	private PrivateDomain privateDomain;
	@Inject
	private PublicDomain publicDomain;

	public ConfigScanDto checkAlbSchemeForEc2Instance(){
		Optional<Ec2InstanceDetailsDto> ec2InstanceDetailsDto = Ec2InstanceTool.getEc2InstanceDetails(false);
		String serverType = serverTypeSupplier.getServerTypeString();

		if(ec2InstanceDetailsDto.isEmpty()){
			return ConfigScanResponseTool.buildEmptyResponse();
		}

		String ec2InstanceId = ec2InstanceDetailsDto.get().instanceId;
		Map<String,Boolean> privatePublicAlbsMap = getAlbSchemeForEc2Instance(serverType, ec2InstanceId);
		boolean hasPublicAlb = privatePublicAlbsMap.get(HAS_PUBLIC_LOAD_BALANCER_KEY);
		boolean hasPrivateAlb = privatePublicAlbsMap.get(HAS_PRIVATE_LOAD_BALANCER_KEY);
		boolean hasUnknownAlb = privatePublicAlbsMap.get(UNKNOWN_LOAD_BALANCER);

		if(hasUnknownAlb){
			return ConfigScanResponseTool.buildResponse("Server does not have any known load balancers or"
					+ " something might be wrong, e.g ALB name does not match, instance not registered with"
					+ " target group, etc");
		}

		if(publicDomain.hasPublicDomain() && !hasPublicAlb){
			return ConfigScanResponseTool.buildResponse("Server expects public load balancer");
		}
		if(!publicDomain.hasPublicDomain() && hasPublicAlb){
			return ConfigScanResponseTool.buildResponse("Server has unexpected public load balancer");
		}
		if(publicDomain.hasPublicDomain()
				&& !hasPublicAlb
				&& privateDomain.hasPrivateDomain()
				&& !hasPrivateAlb){
			return ConfigScanResponseTool.buildResponse("Server expects both public and private load"
					+ " balancers but it is " + hasPublicAlb + " for public ALB and " + hasPrivateAlb
					+ " for private ALB");
		}
		return ConfigScanResponseTool.buildEmptyResponse();
	}

	private Map<String,Boolean> getAlbSchemeForEc2Instance(String serverType, String ec2InstanceId){
		Map<String,Boolean> privatePublicAlbsMap = new HashMap<>();
		boolean unknownAlb = true;
		boolean instanceHasPublicAlb = false;
		boolean instanceHasPrivateAlb = false;

		for(LoadBalancer loadBalancer : elbService.getLoadBalancers()){
			// due to teraform/aws naming character limitation, the ALB for some services with long names will have
			// the to be truncated - "some-example-service-joblet-privat" (missing last char), so can't check for
			// exact ALB name
			if(!loadBalancer.getLoadBalancerName().equals(serverType)
					&& !loadBalancer.getLoadBalancerName().startsWith(serverType + "-privat")){
				continue;
			}
			for(String targetGroupArn : elbService.getTargetGroupsArn(loadBalancer.getLoadBalancerArn())){
				for(String targetEc2InstanceId : elbService.getTargetEc2InstancesId(targetGroupArn)){
					if(!targetEc2InstanceId.equals(ec2InstanceId)){
						continue;
					}
					LoadBalancerSchemeEnum loadBalancerScheme = LoadBalancerSchemeEnum.fromValue(
							loadBalancer.getScheme());
					if(LoadBalancerSchemeEnum.InternetFacing == loadBalancerScheme){
						instanceHasPublicAlb = true;
					}
					if(LoadBalancerSchemeEnum.Internal == loadBalancerScheme){
						instanceHasPrivateAlb = true;
					}
					unknownAlb = false;
				}
			}
		}
		privatePublicAlbsMap.put(HAS_PUBLIC_LOAD_BALANCER_KEY, instanceHasPublicAlb);
		privatePublicAlbsMap.put(HAS_PRIVATE_LOAD_BALANCER_KEY, instanceHasPrivateAlb);
		privatePublicAlbsMap.put(UNKNOWN_LOAD_BALANCER, unknownAlb);
		return privatePublicAlbsMap;
	}

}

redpajama_set_name: RedPajamaGithub


text:
class CreateInstagramPosts < ActiveRecord::Migration
  def change
    create_table :instagram_posts do |t|
      t.string :postid, null: false
      t.datetime :posttime, null: false
      t.binary :caption
      t.text :url
      t.integer :width
      t.integer :height

      t.timestamps null: false
    end
    add_index :instagram_posts, :postid, unique: true
    add_index :instagram_posts, :posttime
  end
end


text:
using System.Threading;
using System.Threading.Tasks;

namespace Riganti.Utils.Infrastructure.Core
{
    public interface IPageableQuery
    {
        /// <summary>
        /// Gets or sets a number of rows to be skipped. If this value is null, the paging will be applied.
        /// </summary>
        int? Skip { get; set; }

        /// <summary>
        /// Gets or sets the page size. If this value is null, the paging will not be applied.
        /// </summary>
        int? Take { get; set; }

        /// <summary>
        /// Gets the total row count without respect to paging.
        /// </summary>
        int GetTotalRowCount();

        /// <summary>
        /// Gets the total row count without respect to paging.
        /// </summary>
        Task<int> GetTotalRowCountAsync();

        /// <summary>
        /// Gets the total row count without respect to paging.
        /// </summary>
        Task<int> GetTotalRowCountAsync(CancellationToken cancellationToken);
    }
}


text:
using System.ServiceModel.Syndication;
using System.Web.Mvc;
using System.Xml;

namespace Chief2moro.SyndicationFeeds
{
    /// <summary>
    /// Returns an Atom feed to the response stream.
    /// </summary>
    public class AtomActionResult : ActionResult
    {
        readonly SyndicationFeed _feed;

        /// <summary>
        /// Constructor to set up the action result feed.
        /// </summary>
        /// <param name="feed">Accepts a <see cref="SyndicationFeed"/>.</param>
        public AtomActionResult(SyndicationFeed feed)
        {
            _feed = feed;
        }

        /// <summary>
        /// Executes the call to the ActionResult method and returns the created feed to the output response.
        /// </summary>
        /// <param name="context">Accepts the current <see cref="ControllerContext"/>.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "application/atom+xml";
            var formatter = _feed.GetAtom10Formatter();

            using (var writer = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                formatter.WriteTo(writer);
            }
        }
    }
}


text:
from __future__ import unicode_literals
import json
import logging
import re
import warnings
try:
    from urllib2 import urlopen
    from urlparse import urlparse, parse_qs, unquote
except ImportError:
    from urllib.parse import urlparse, parse_qs, unquote
    from urllib.request import urlopen

from .exceptions import MultipleObjectsReturned, YouTubeError, CipherError, \
    DoesNotExist, AgeRestricted
from .jsinterp import JSInterpreter
from .models import Video
from .utils import safe_filename

log = logging.getLogger(__name__)

# YouTube quality and codecs id map.
YT_ENCODING = {
    # flash
    5: ["flv", "240p", "Sorenson H.263", "N/A", "0.25", "MP3", "64"],

    # 3gp
    17: ["3gp", "144p", "MPEG-4 Visual", "Simple", "0.05", "AAC", "24"],
    36: ["3gp", "240p", "MPEG-4 Visual", "Simple", "0.17", "AAC", "38"],

    # webm
    43: ["webm", "360p", "VP8", "N/A", "0.5", "Vorbis", "128"],
    100: ["webm", "360p", "VP8", "3D", "N/A", "Vorbis", "128"],

    # mpeg4
    18: ["mp4", "360p", "H.264", "Baseline", "0.5", "AAC", "96"],
    22: ["mp4", "720p", "H.264", "High", "2-2.9", "AAC", "192"],
    82: ["mp4", "360p", "H.264", "3D", "0.5", "AAC", "96"],
    83: ["mp4", "240p", "H.264", "3D", "0.5", "AAC", "96"],
    84: ["mp4", "720p", "H.264", "3D", "2-2.9", "AAC", "152"],
    85: ["mp4", "1080p", "H.264", "3D", "2-2.9", "AAC", "152"],
}

# The keys corresponding to the quality/codec map above.
YT_ENCODING_KEYS = (
    'extension',
    'resolution',
    'video_codec',
    'profile',
    'video_bitrate',
    'audio_codec',
    'audio_bitrate'
)

class YouTube(object):
    def __init__(self):
        self._filename = None
        self._fmt_values = []
        self._video_url = None
        self._js_code = False

    @property
    def url(self):
        """Get the video url."""
        return self._video_url

    @url.setter
    def url(self, url):
        """Set the YouTube video url (This method is deprecated. Use
        `from_url()` instead).

        :param str url:
            The YouTube video url.
        """
        warnings.warn("url setter deprecated, use `from_url()` "
                      "instead.", DeprecationWarning)
        self.from_url(url)

    def from_url(self, url):
        """Set the YouTube video url.

        :param str url:
            The YouTube video url.
        """
        self._video_url = url

        # Reset the filename.
        self._filename = None

        # Get the video details.
        video_data = self.get_video_data()

        # Set the title.
        self.title = video_data.get("args", {}).get("title")

        js_url = "http:" + video_data.get("assets", {}).get("js")
        stream_map = video_data.get("args", {}).get("stream_map")
        video_urls = stream_map.get("url")

        for i, url in enumerate(video_urls):
            try:
                fmt, fmt_data = self._extract_fmt(url)
                if not fmt_data:
                    log.warn("unable to identify itag=%s", fmt)
                    continue
            except (TypeError, KeyError) as e:
                log.exception("passing on exception %s", e)
                continue

            # If the signature must be ciphered...
            if "signature=" not in url:
                signature = self._get_cipher(stream_map["s"][i], js_url)
                url = "{}&signature={}".format(url, signature)
            self.videos.append(Video(url, self.filename, **fmt_data))
            self._fmt_values.append(fmt)
        self.videos.sort()

    @property
    def filename(self):
        """Get the title of the video."""
        if not self._filename:
            self._filename = safe_filename(self.title)
            log.debug("generated 'safe' filename: %s", self._filename)
        return self._filename

    @filename.setter
    def filename(self, filename):
        """Set the filename (This method is deprecated. Use
        `set_filename()` instead).

        :param str filename:
            The filename of the video.
        """
        warnings.warn("filename setter deprecated, use `set_filename()` "
                      "instead.", DeprecationWarning)
        self.set_filename(filename)

    def set_filename(self, filename):
        """Set the filename.

        :param str filename:
            The filename of the video.
        """
        self._filename = filename
        if self.videos:
            for video in self.videos:
                video.filename = filename

    @property
    def video_id(self):
        """Extracts the video id from the url."""
        parts = urlparse(self._video_url)
        qs = getattr(parts, 'query')
        if qs:
            video_id = parse_qs(qs).get('v')
            if video_id:
                return video_id.pop()

    def get(self, extension=None, resolution=None, profile=None):
        """Return a single video given a file extention and/or resolution
        and/or profile.

        :param str extention:
            The desired file extention (e.g.: mp4).
        :param str resolution:
            The desired video broadcasting standard.
        :param str profile:
            The desired quality profile.
        """
        result = []
        for v in self.videos:
            if extension and v.extension != extension:
                continue
            elif resolution and v.resolution != resolution:
                continue
            elif profile and v.profile != profile:
                continue
            else:
                result.append(v)
        matches = len(result)
        if matches <= 0:
            return DoesNotExist("No videos met criteria.")
        elif matches == 1:
            return result[0]
        else:
            raise MultipleObjectsReturned(
                "{} videos met criteria".format(matches))

    def filter(self, extension=None, resolution=None, profile=None):
        """Return a filtered list of videos given a file extention and/or
        resolution and/or profile.

        :param str extention:
            The desired file extention (e.g.: mp4).
        :param str resolution:
            The desired video broadcasting standard.
        :param str profile:
            The desired quality profile.
        """
        results = []
        for v in self.videos:
            if extension and v.extension != extension:
                continue
            elif resolution and v.resolution != resolution:
                continue
            elif profile and v.profile != profile:
                continue
            else:
                results.append(v)
        return results

    def _parse_stream_map(self, blob):
        """A modified version of `urlparse.parse_qs` that is able to decode
        YouTube's stream map.

        :param str blob:
            An encoded blob of text containing the stream map data.
        """
        dct = {
            "itag": [],
            "url": [],
            "quality": [],
            "fallback_host": [],
            "s": [],
            "type": []
        }

        # Split individual videos
        videos = blob.split(",")
        # Unquote the characters and split to parameters
        videos = [video.split("&") for video in videos]

        for video in videos:
            for kv in video:
                key, value = kv.split("=")
                log.debug('stream map key value: %s => %s', key, value)
                dct.get(key, []).append(unquote(value))
        log.debug('decoded stream map: %s', dct)
        return dct

    def get_video_data(self):
        """Fetch the page and extract out the video data."""
        self.title = None
        self.videos = []

        response = urlopen(self.url)

        if not response:
            return False
        html = response.read().decode("utf-8")

        if "og:restrictions:age" in html:
            raise AgeRestricted

        json_object = self._extract_json_data(html)

        if not json_object:
            raise YouTubeError("Unable to extract json.")

        encoded_stream_map = json_object.get("args", {}).get(
            "url_encoded_fmt_stream_map")

        json_object['args']['stream_map'] = self._parse_stream_map(
            encoded_stream_map)
        return json_object

    def _extract_json_data(self, html):
        """Extract the json from the html.

        :param str html:
            The raw html of the YouTube page.
        """
        # 18 represents the length of "ytplayer.config = ".
        start = html.find("ytplayer.config = ") + 18
        html = html[start:]
        offset = self._find_json_offset(html)

        if not offset:
            return None
        return json.loads(html[:offset])

    def _find_json_offset(self, html):
        """Find where the json object starts.

        :param str html:
            The raw html of the YouTube page.
        """
        bracket_count = 0
        index = 1
        for i, char in enumerate(html):
            if char == "{":
                bracket_count += 1
            elif char == "}":
                bracket_count -= 1
                if bracket_count == 0:
                    break
        else:
            return None
        return index + i

    def _get_cipher(self, signature, url):
        """Get the signature using the cipher.

        :param str signature:
            Signature.
        :param str url:
            url of JavaScript file.
        """
        # Getting JS code (if hasn't downloaded yet)
        if not self._js_code:
            # TODO: don't use conditional expression if line > 79 characters.
            self._js_code = (urlopen(url).read().decode()
                             if not self._js_code else self._js_code)
        try:
            mobj = re.search(r'\.sig\|\|([a-zA-Z0-9$]+)\(', self._js_code)
            if mobj:
                # return the first matching group
                funcname = next(g for g in mobj.groups() if g is not None)

            jsi = JSInterpreter(self._js_code)
            initial_function = jsi.extract_function(funcname)
            return initial_function([signature])
        except Exception as e:
            raise CipherError("Couldn't cipher the signature. Maybe YouTube "
                "has changed the cipher algorithm. Notify this issue on "
                "GitHub: %s" % e)

    def _extract_fmt(self, text):
        """YouTube does not pass you a completely valid URLencoded form, I
        suspect this is suppose to act as a deterrent.. Nothing some regex
        couldn't handle.

        :param str text:
            The malformed data contained within each url node.
        """
        itag = re.findall('itag=(\d+)', text)
        if itag and len(itag) == 1:
            itag = int(itag[0])
            attr = YT_ENCODING.get(itag, None)
            if not attr:
                return itag, None
            return itag, dict(zip(YT_ENCODING_KEYS, attr))


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/validate"

	manifold "github.com/manifoldco/go-manifold"
)

// CredentialRotationRequest The information on the credential rotation to perform.
//
// swagger:model CredentialRotationRequest
type CredentialRotationRequest struct {

	// credential id
	// Required: true
	CredentialID manifold.ID `json:"credential_id"`

	// reason
	// Required: true
	// Max Length: 256
	// Min Length: 3
	Reason *string `json:"reason"`

	// resource id
	// Required: true
	ResourceID manifold.ID `json:"resource_id"`
}

// Validate validates this credential rotation request
func (m *CredentialRotationRequest) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateCredentialID(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateReason(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateResourceID(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *CredentialRotationRequest) validateCredentialID(formats strfmt.Registry) error {

	if err := m.CredentialID.Validate(formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("credential_id")
		}
		return err
	}

	return nil
}

func (m *CredentialRotationRequest) validateReason(formats strfmt.Registry) error {

	if err := validate.Required("reason", "body", m.Reason); err != nil {
		return err
	}

	if err := validate.MinLength("reason", "body", string(*m.Reason), 3); err != nil {
		return err
	}

	if err := validate.MaxLength("reason", "body", string(*m.Reason), 256); err != nil {
		return err
	}

	return nil
}

func (m *CredentialRotationRequest) validateResourceID(formats strfmt.Registry) error {

	if err := m.ResourceID.Validate(formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("resource_id")
		}
		return err
	}

	return nil
}


text:
<?php
session_start();
$_SESSION['themesFolder'] = "lighty";
require_once('../include/config.php');
require_once('../class/class.pdo.php');
require_once('../class/class.display.php');
require_once('../class/class.error.php');
require_once('../class/class.log.php');
require_once('../class/class.user.php');
require_once('../class/class.mail.php');

//SET THEMES
if(isset($_SESSION['themesFolder']) and !empty($_SESSION['themesFolder']) ){
    $themesFolder = $_SESSION['themesFolder'];
}else{
    $themesFolder = 'lighty';
}

$display = new Display();
$display->loadTpl('forget_page');
$display->setVar("FORM", null);
$display->setVar("ERROR", null);

$error_dsp = new Error();
$mail = new Mail();
$user = new User($db);

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $info_user = $user->forget_username($_POST['email'], $_POST['password']);
    $sendmail = $mail->mailToUser($info_user->email, "Votre identifiant", "
Votre identifiant est ".$info_user->username."
");

    if($sendmail == 1){
        $error_dsp->set('Votre identifiant a bien été envoyé. Vous le recevrez dans peu de temps dans votre boîte mail.', 'Message de confirmation', 'index.php');
	$display->setVar("ERROR", $error_dsp->display_succes());
    }else{
        $error_dsp->set(array("Les informations entrées sont erroné. Veuillez recommencer."), 'ERROR Inscription', 'index.php');
        $display->setVar("ERROR", $error_dsp->display_error());
    }
}else{
    $display->setVar("FORM", file_get_contents('../themes/'.$themesFolder.'/tpl/forget_username_form.tpl'));
}
$display->setVar("HEADER", $display->header('SMASH Web - Retrouver mon identifiant'));
$display->setVar("FOOTER", $display->footer());

$display->display();

 ?>


text:
import time

from tempest.scenario import manager
from tempest.test import attr
from tempest.test import call_until_true
from tempest.test import services

class AutoScalingTest(manager.OrchestrationScenarioTest):

    def setUp(self):
        super(AutoScalingTest, self).setUp()
        if not self.config.orchestration.image_ref:
            raise self.skipException("No image available to test")
        self.client = self.orchestration_client

    def assign_keypair(self):
        self.stack_name = self._stack_rand_name()
        if self.config.orchestration.keypair_name:
            self.keypair_name = self.config.orchestration.keypair_name
        else:
            self.keypair = self.create_keypair()
            self.keypair_name = self.keypair.id

    def launch_stack(self):
        net = self._get_default_network()
        self.parameters = {
            'KeyName': self.keypair_name,
            'InstanceType': self.config.orchestration.instance_type,
            'ImageId': self.config.orchestration.image_ref,
            'StackStart': str(time.time()),
            'Subnet': net['subnets'][0]
        }

        # create the stack
        self.template = self._load_template(__file__, 'test_autoscaling.yaml')
        self.client.stacks.create(
            stack_name=self.stack_name,
            template=self.template,
            parameters=self.parameters)

        self.stack = self.client.stacks.get(self.stack_name)
        self.stack_identifier = '%s/%s' % (self.stack_name, self.stack.id)

        # if a keypair was set, do not delete the stack on exit to allow
        # for manual post-mortums
        if not self.config.orchestration.keypair_name:
            self.set_resource('stack', self.stack)

    @attr(type='slow')
    @services('orchestration', 'compute')
    def test_scale_up_then_down(self):

        self.assign_keypair()
        self.launch_stack()

        sid = self.stack_identifier
        timeout = self.config.orchestration.build_timeout
        interval = 10

        self.assertEqual('CREATE', self.stack.action)
        # wait for create to complete.
        self.status_timeout(self.client.stacks, sid, 'COMPLETE')

        self.stack.get()
        self.assertEqual('CREATE_COMPLETE', self.stack.stack_status)

        # the resource SmokeServerGroup is implemented as a nested
        # stack, so servers can be counted by counting the resources
        # inside that nested stack
        resource = self.client.resources.get(sid, 'SmokeServerGroup')
        nested_stack_id = resource.physical_resource_id

        def server_count():
            # the number of servers is the number of resources
            # in the nested stack
            self.server_count = len(
                self.client.resources.list(nested_stack_id))
            return self.server_count

        def assertScale(from_servers, to_servers):
            call_until_true(lambda: server_count() == to_servers,
                            timeout, interval)
            self.assertEqual(to_servers, self.server_count,
                             'Failed scaling from %d to %d servers' % (
                                 from_servers, to_servers))

        # he marched them up to the top of the hill
        assertScale(1, 2)
        assertScale(2, 3)

        # and he marched them down again
        assertScale(3, 2)
        assertScale(2, 1)


text:
import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';

import {
  IonicPage,
  Events,
  NavController,
  FabContainer,
  ToastController,
  LoadingController,
} from 'ionic-angular';

import * as Reveal from 'reveal.js';

import {
  PollService,
  RoomsProvider,
  AttendanceProvider,
} from '../../providers/providers';

@IonicPage({
  segment: 'polls'
})
@Component({
  selector: 'page-professor-live',
  templateUrl: 'professor-live.html',
})
export class ProfessorLivePage {
  @ViewChild('fab') fab: FabContainer;
  isDataLoaded: boolean = false;

  sessions: any;

  poll: any;
  questions: any;

  currentSlide: number;
  isChartAvailable: boolean;
  isAnswerAvailable: boolean;
  isFreeAnswerQuestion: boolean;

  isFullscreen: boolean = false;

  settings = {};

  room: any;

  attendance: any;

  /**
   * Used to control fab options
   */
  appState: string = 'SHOW_LIST'; // 'TAKE_ATTENDANCE' 'POLL_LIVE'
  previousState: string = 'SHOW_LIST';

  constructor(
    public toastCtrl: ToastController,
    public attendanceProvider: AttendanceProvider,
    public ps: PollService,
    public rs: RoomsProvider,
    public navCtrl: NavController,
    public cdf: ChangeDetectorRef,
    public events: Events,
    public loadCtrl: LoadingController,
  ) {
    this.events.subscribe('room:live', (room) => {
      this.room = room;
      this.initializeData();
    });
    //
    this.events.subscribe('attendance:live', (attendance) => {
      this.initAttendance(this.room);
    });
  }

  ionViewDidLoad() {
    // open fab button
    this.fab.toggleList();

    // get poll
    this.initializeData();

    // get sessions
    this.getOldSessions();

    // get default room
    !this.room && this.rs.active()
      .then((result) => {
        if (!result.total) return;

        this.room = result.data[0];
        this.initializeData();

        // attendance
        this.initAttendance(this.room);
      });

    // live update students online
    // TODO: try to init and update all room info here
    this.rs.active().subscribe((room) => {
      this.room = room.data[0];
    });
  }

  initializeData() {
    this.room && this.ps.getPollByProfessor(this.room.code).subscribe((poll) => {
      if (!poll.data.length) return;

      // force no view mode
      this.setState('POLL_LIVE');

      this.poll = poll.data[0];
      this.questions = this.poll.questions;

      // $scope.$apply()
      this.cdf.detectChanges();

      // init slides engine
      this.initializeReveal();

      // apply changes
      Reveal.setState(Reveal.getState());

      // set fab actions state
      this.currentSlide = Reveal.getState().indexh;
      const currentQuestion = this.poll.questions[this.currentSlide];

      this.isChartAvailable = currentQuestion.showChart;
      this.isAnswerAvailable = currentQuestion.showAnswer;
      this.isFreeAnswerQuestion = currentQuestion.type === 'free';

      // settings
      this.updateSettings();

      // to dismiss loading
      this.events.publish('session:loaded');

      // usage ProfessorStudentsResultsPage
      this.isFreeAnswerQuestion && this.events.publish('results:update', { question: this.poll.questions[this.currentSlide] });
    });
  }

  initAttendance(attendance) {
    this.attendanceProvider.find(attendance)
      .subscribe((res) => {
        if (!res.total) return;

        this.attendance = res.data[0];

        this.appState = 'TAKE_ATTENDANCE';
      });
  }

  getOldSessions() {
    this.ps.sessions().then((sessions) => {
      this.sessions = [];
      sessions.data.forEach((session) => {
        this.sessions.push(session);
      });

      this.isDataLoaded = true;
    });
  }

  goToDetails(poll) {
    this.navCtrl.push('ProfessorSessionResultsPage', { poll });
  }

  exitViewMode() {
    this.setState('SHOW_LIST');

    this.end();
  }

  updateSettings() {
    this.settings['available'] = this.currentSlide === this.poll.available;
  }

  initializeReveal() {
    Reveal.initialize({
      controls: false,

      // Enable the slide overview mode
      overview: false,

      // Vertical centering of slides
      center: false,

      // minScale: 1,
    });

    Reveal.addEventListener('slidechanged', (event) => {
      // TODO: called to many times
      // check to avoid many calls
      if (event.indexh === this.currentSlide) return;

      this.currentSlide = event.indexh;
      this.isChartAvailable = this.poll.questions[this.currentSlide].showChart;
      this.isAnswerAvailable = this.poll.questions[this.currentSlide].showAnswer;
      this.isFreeAnswerQuestion = this.poll.questions[this.currentSlide].type === 'free';

      // settings
      this.updateSettings();

      // if fullscreen, available is automatically
      if (this.isFullscreen) {
        this.setPollAvailable();
      }
    });
  }

  showAnswer() {
    const question = this.poll.questions[this.currentSlide];
    this.isAnswerAvailable = !question.showAnswer;

    this.ps.showAnswer(this.poll, this.currentSlide, !question.showAnswer);
  }

  stop() {
    this.currentSlide = Reveal.getState().indexh;

    if (this.poll.available === this.currentSlide) {
      // pause case
      this.setPollUnavailable();
    } else {
      // activate
      this.setPollAvailable();
    }
  }

  setPollAvailable() {
    this.ps.setAvailable(this.poll, this.currentSlide);
  }

  setPollUnavailable() {
    this.ps.setAvailable(this.poll, -1);
  }

  /**
   * End current session
   */
  end() {
    this.ps.setIsOver(this.poll);

    // clear var
    this.poll = null;

    // update app state
    this.setState('SHOW_LIST');

    // end poll cannot be previous anymore
    this.previousState = 'SHOW_LIST';

    // old sessions
    this.getOldSessions();
  }

  takeAttendance() {
    const loading = this.createLoading();
    loading.present();

    const fourRandomDigits = Math.floor(1000 + Math.random() * 9000);
    const attendance = {
      room: this.room._id,
      name: this.room.name,
      code: fourRandomDigits,
      students: this.room.students,
      online: true,
    };

    this.attendanceProvider.create(attendance)
      .then((res) => {
        loading.dismiss();
      })
      .catch((error) => {
        this.presentToast('Algo inesperado aconteceu. Verifique a sua conexão com a internet');
      });
  }

  presentToast(msg) {
    this.toastCtrl.create({
      message: msg,
      duration: 2000,
      position: 'bottom',
      showCloseButton: true,
    }).present();
  }

  createLoading() {
    return this.loadCtrl.create({
      content: 'Carregando...',
      duration: 5000
    });
  }

  pauseAttendance() {
    this.attendanceProvider
      .stop(this.attendance)
      .then(() => {
        // TODO: pop history
        this.backState();
      });
  }

  backToPoll() {
    this.setState('POLL_LIVE');
  }

  endAttendance() {
    this.attendanceProvider
      .stop(this.attendance)
      .then(() => {
        this.backState();

        // end attendance cannot be previous anymore
        this.previousState = 'SHOW_LIST';

        // clear attendance object
        this.attendance = null;

        // show action button to see list
        this.presentToastWithButton();
      });
  }

  presentToastWithButton() {
    let toast = this.toastCtrl.create({
      message: 'Frequência encerrada',
      duration: 4000,
      position: 'bottom',
      showCloseButton: true,
      closeButtonText: 'Ver lista'
    });

    toast.present();

    toast.onDidDismiss((data, role) => {
      if (role === 'close') {
        this.navCtrl.push('ProfessorAttendanceListPage', { room: this.room });
      }
    });
  }

  setState(state: string) {
    this.previousState = this.appState;
    this.appState = state;
  }

  backState() {
    this.setState(this.previousState);
  }

  moveSlideTo(side) {
    if (side === 'right') {
      Reveal.right();
    } else if (side === 'left') {
      Reveal.left();
    }
  }

  showChart() {
    const question = this.poll.questions[this.currentSlide];
    this.isChartAvailable = !question.showChart;

    this.ps.showChart(this.poll, this.currentSlide, !question.showChart);
  }

  showFreeAnswers() {
    this.navCtrl.push('ProfessorStudentsResultsPage', { question: this.poll.questions[this.currentSlide] });
  }

  fullscreen() {
    if (this.isFullscreen) {
      exitFullscreen();
    } else {
      launchIntoFullscreen(document.documentElement);
      this.setPollAvailable();
    }
    this.isFullscreen = !this.isFullscreen;
  }

}

// Find the right method, call on correct element
function launchIntoFullscreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
}

// Whack fullscreen
function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}


text:
// Shared amongst projects
// ReSharper disable once CheckNamespace

namespace SpikeSpike
{
    public enum GameState
    {
        MainMenu,
        Game,
        GamePaused,
        GameOver
    }
}


text:
<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use JWTAuth, JWTException;
use App\Models\Role;
use App\Models\Permission;
use App\Http\Controllers\Controller;
use Validator;
use Dingo\Api\Routing\Helpers;

class PermissionController extends Controller
{
    use Helpers;

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        if ($id == 0) {
            $role = JWTAuth::parseToken()->authenticate()->roles[0];
        } else {
            if (Validator::make(['id' => $id], ['id' => 'numeric'])->fails()) $this->response->errorBadRequest(400000);
            if (Validator::make(['id' => $id], ['id' => 'exists:roles'])->fails()) $this->response->errorBadRequest(400003);
            $role = Role::find($id);
        }
        $permission = new Permission();
        $res = $permission->where('depth', 1)->get()->map(function ($item) use ($role, $permission) {
            $item->state = $role->hasPermission($item->name);
            $item->children = $item->where('parent_id', $item->id)->get()->map(function ($c_item) use ($role, $permission) {
                $c_item->state = $role->hasPermission($c_item->name);
                return $c_item;
            });
            return $item;
        });
        return $res->all();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if (!JWTAuth::parseToken()->authenticate()->roles[0]->hasPermission('users/permission/edit')) $this->response->errorForbidden(403029);

        if (Validator::make(['id' => $id], ['id' => 'numeric'])->fails()) $this->response->errorBadRequest(400000);
        if (Validator::make(['id' => $id], ['id' => 'exists:roles'])->fails()) $this->response->errorBadRequest(400003);
        if (!key_exists('permissions', $request->all())) $this->response->errorBadRequest(401010);

        $role = Role::find($id);
        $permission = new Permission();
        $permissions = collect($request->only('permissions')['permissions']);
        collect($permissions)->each(function ($item) use ($role, $permission) {
            if ($item['state'] === 'true' && !$role->hasPermission($item['name'])) $role->attachPermission($item['id']);
            if ($item['state'] === 'false' && $role->hasPermission($item['name'])) $role->detachPermission($item['id']);
            if (key_exists('children', $item) && count($item['children'])) {
                foreach ($item['children'] as $child) {
                    if ($child['state'] === 'true' && !$role->hasPermission($child['name'])) $role->attachPermission($child['id']);
                    if ($child['state'] === 'false' && $role->hasPermission($child['name'])) $role->detachPermission($child['id']);
                }
            }
        });
        return $this->show($id);
    }
}


text:
#include "../Classes/AppDelegate.h"
#include "cocos2d.h"

USING_NS_CC;

int main(int argc, char **argv)
{
	// create the application instance
    AppDelegate app;

	int width, height;
	const char *width_str, *height_str;
	width_str = getenv("WIDTH");
	height_str = getenv("HEIGHT");
	if (width_str && height_str)
	{
		width = atoi(width_str);
		height = atoi(height_str);
	}
	else
	{
		width = 1024;
		height = 600;
	}

	CCApplication::sharedApplication()->setResourceRootPath("app/native/Resources/");

    CCEGLView* eglView = CCEGLView::sharedOpenGLView();
    eglView->setFrameSize(width, height);

    return CCApplication::sharedApplication()->run();
}


text:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using Iodine.Runtime;
using Iodine.Compiler;

namespace Iodine.Runtime.Debug
{
    public class DebugSession
    {
        class DebugResponse
        {
            public readonly SourceLocation Location;
            public readonly StackFrame Frame;

            public DebugResponse (SourceLocation location, StackFrame frame)
            {
                Location = location;
                Frame = frame;
            }
        }

        private VirtualMachine virtualMachine;
        private NetworkStream baseStream;
        private StreamReader requestStream;
        private StreamWriter responseStream;

        private Dictionary<string, string[]> fileCache = new Dictionary<string, string[]> ();

        public DebugSession (VirtualMachine vm, Socket socket)
        {
            virtualMachine = vm;
            baseStream = new NetworkStream (socket);
            requestStream = new StreamReader (baseStream);
            responseStream = new StreamWriter (baseStream);
        }

        public void Connect ()
        {
            while (true) {
                string command = requestStream.ReadLine ();
                SendResponse (InterpretCommand (command));
            }
        }

        private void SendResponse (DebugResponse response)
        {
            if (!fileCache.ContainsKey (response.Location.File)) {
                fileCache [response.Location.File] = File.ReadAllLines (response.Location.File);
            }

            StringBuilder sb = new StringBuilder ();
            sb.AppendFormat ("Line:{0};", response.Location.Line);
            sb.AppendFormat ("File:{0}", response.Location.File);
            sb.AppendFormat ("!{0}", fileCache [response.Location.File] [response.Location.Line - 1]);
            responseStream.WriteLine (sb.ToString ());
            responseStream.Flush ();
        }

        private DebugResponse InterpretCommand (string command)
        {
            string[] args = command.Split (' ');
            switch (args [0]) {
            case "s":
            case "step":
                return Step ();
            case "d":
            case "down":
                return Down ();
            case "n":
            case "next":
                return Next ();
            case "c":
            case "continue":
                DebugResponse resp = new DebugResponse (
                    virtualMachine.Top.Location,
                    virtualMachine.Top
                );
                virtualMachine.SetTrace (null);

                virtualMachine.ContinueExecution ();
                return resp;
            }
            return null;
        }

        private DebugResponse Step ()
        {
            ManualResetEvent done = new ManualResetEvent (false);
            DebugResponse response = null;
            virtualMachine.SetTrace (((TraceType type,
                VirtualMachine vm,
                StackFrame frame,
                SourceLocation location) => {
                if (type == TraceType.Line) {
                    response = new DebugResponse (location, frame);
                    done.Set ();
                    return true;
                }
                return false;
            }));
            virtualMachine.ContinueExecution ();
            done.WaitOne ();

            return response;
        }

        private DebugResponse Next ()
        {
            ManualResetEvent done = new ManualResetEvent (false);
            DebugResponse response = null;
            StackFrame currentFrame = virtualMachine.Top;
            virtualMachine.SetTrace (((TraceType type,
                VirtualMachine vm,
                StackFrame frame,
                SourceLocation location) => {
                if (type == TraceType.Line && frame == currentFrame) {
                    response = new DebugResponse (location, frame);
                    done.Set ();
                    return true;
                }
                return false;
            }));
            virtualMachine.ContinueExecution ();
            done.WaitOne ();

            return response;
        }

        private DebugResponse Down ()
        {
            ManualResetEvent done = new ManualResetEvent (false);
            DebugResponse response = null;
            StackFrame currentFrame = virtualMachine.Top;
            virtualMachine.SetTrace (((TraceType type,
                VirtualMachine vm,
                StackFrame frame,
                SourceLocation location) => {
                if (type == TraceType.Line && frame.Parent == currentFrame) {
                    response = new DebugResponse (location, frame);
                    done.Set ();
                    return true;
                }
                return false;
            }));
            virtualMachine.ContinueExecution ();
            done.WaitOne ();
            return response;
        }
    }
}


text:
using System.Web.UI;

namespace BugGuardian.WebForms.TestWebApp.Account
{
    public partial class ResetPasswordConfirmation : Page
    {
    }
}


text:
/**
 * Geometry helper functions
 */

/**
 * Determine if polygon hull is convex
 * @param  {Array}  hull Array of vertices (Vectorish)
 * @return {Boolean}
 */
Physics.geometry.isPolygonConvex = function( hull ){

    var scratch = Physics.scratchpad()
        ,prev = scratch.vector()
        ,next = scratch.vector()
        ,tmp = scratch.vector()
        ,ret = true
        ,sign = false
        ,l = hull.length
        ;

    if ( l < 3 ){
        // it must be a point or a line...
        // which are convex
        scratch.done();
        return ret;
    }

    prev.clone( hull[ 0 ] ).vsub( tmp.clone( hull[ l - 1 ] ) );

    // loop over the edges of the hull and construct vectors of the current
    // edge and retain the last edge
    // add two to the length to do a full cycle
    for ( var i = 1; i <= l; ++i ){

        next.clone( hull[ i % l ] ).vsub( tmp.clone( hull[ (i - 1) % l ] ) );

        if ( sign === false ){

            // first check the sign of the first cross product
            sign = prev.cross( next );

        } else if ( (sign > 0) ^ (prev.cross( next ) > 0) ){

            // if the cross products are different signs it's not convex
            ret = false;
            break;
        }

        // remember the last edge
        next.swap( prev );
    }

    scratch.done();
    return ret;
};

/**
 * Gets the moment of inertia of a convex polygon
 * @see: http://en.wikipedia.org/wiki/List_of_moments_of_inertia
 * assumptions:
 *  * mass is unitary
 *  * axis of rotation is the origin
 * @param  {Array} hull Array of vertices (vectorish)
 * @return {Number} The polygon MOI
 */
Physics.geometry.getPolygonMOI = function( hull ){

    var scratch = Physics.scratchpad()
        ,prev = scratch.vector()
        ,next = scratch.vector()
        ,num = 0
        ,denom = 0
        ,tmp
        ,l = hull.length
        ;

    if ( l < 2 ){
        // it must be a point
        // moi = 0
        scratch.done();
        return 0;
    }

    if ( l === 2 ){
        // it's a line
        // get length squared
        tmp = next.clone( hull[ 1 ] ).distSq( prev.clone( hull[ 0 ] ) );
        scratch.done();
        return tmp / 12;
    }

    prev.clone( hull[ 0 ] );

    for ( var i = 1; i < l; ++i ){

        next.clone( hull[ i ] );

        tmp = Math.abs( next.cross( prev ) );
        num += tmp * ( next.normSq() + next.dot( prev ) + prev.normSq() );
        denom += tmp;

        prev.swap( next );
    }

    scratch.done();
    return num / ( 6 * denom );
};

/**
 * Check if point is inside polygon hull
 * @param  {Vectorish}  pt
 * @param  {Array}  hull Array of vertices (Vectorish)
 * @return {Boolean}
 */
Physics.geometry.isPointInPolygon = function( pt, hull ){

    var scratch = Physics.scratchpad()
        ,point = scratch.vector().clone( pt )
        ,prev = scratch.vector()
        ,next = scratch.vector()
        ,ang = 0
        ,l = hull.length
        ;

    if ( l < 2 ){
        // it's a point...
        ang = point.equals( prev.clone( hull[ 0 ] ));
        scratch.done();
        return ang;
    }

    if ( l === 2 ){
        // it's a line
        ang = point.angle( prev.clone( hull[ 0 ] ));
        ang += point.angle( prev.clone( hull[ 1 ] ));
        scratch.done();
        return ( Math.abs(ang) === Math.PI );
    }

    prev.clone( hull[ 0 ] ).vsub( point );

    // calculate the sum of angles between vector pairs
    // from point to vertices
    for ( var i = 1; i <= l; ++i ){

        next.clone( hull[ i % l ] ).vsub( point );
        ang += next.angle( prev );
        prev.swap( next );
    }

    scratch.done();
    return ( Math.abs(ang) > 0 );
};

/**
 * Get the signed area of the polygon
 * @param  {Array} hull Array of vertices
 * @return {Number} Area (positive for clockwise ordering)
 */
Physics.geometry.getPolygonArea = function getPolygonArea( hull ){

    var scratch = Physics.scratchpad()
        ,prev = scratch.vector()
        ,next = scratch.vector()
        ,ret = 0
        ,l = hull.length
        ;

    if ( l < 3 ){
        // it must be a point or a line
        // area = 0
        scratch.done();
        return 0;
    }

    prev.clone( hull[ l - 1 ] );

    for ( var i = 0; i < l; ++i ){

        next.clone( hull[ i ] );

        ret += prev.cross( next );

        prev.swap( next );
    }

    scratch.done();
    return ret / 2;
};

/**
 * Get the coordinates of the centroid
 * @param  {Array} hull Polygon hull definition
 * @return {Vector} centroid
 */
Physics.geometry.getPolygonCentroid = function getPolygonCentroid( hull ){

    var scratch = Physics.scratchpad()
        ,prev = scratch.vector()
        ,next = scratch.vector()
        ,ret = Physics.vector()
        ,tmp
        ,l = hull.length
        ;

    if ( l < 2 ){
        // it must be a point
        scratch.done();
        return Physics.vector( hull[0] );
    }

    if ( l === 2 ){
        // it's a line
        // get the midpoint
        scratch.done();
        return Physics.vector((hull[ 1 ].x + hull[ 0 ].x)/2, (hull[ 1 ].y + hull[ 0 ].y)/2 );
    }

    prev.clone( hull[ l - 1 ] );

    for ( var i = 0; i < l; ++i ){

        next.clone( hull[ i ] );

        tmp = prev.cross( next );
        prev.vadd( next ).mult( tmp );
        ret.vadd( prev );

        prev.swap( next );
    }

    tmp = 1 / (6 * Physics.geometry.getPolygonArea( hull ));

    scratch.done();
    return ret.mult( tmp );
};

/**
 * Get the closest point on a discrete line to specified point.
 * @param  {Vectorish} pt The point
 * @param  {Vectorish} linePt1 The first endpoint of the line
 * @param  {Vectorish} linePt2 The second endpoint of the line
 * @return {Vector} The closest point
 */
Physics.geometry.nearestPointOnLine = function nearestPointOnLine( pt, linePt1, linePt2 ){

    var scratch = Physics.scratchpad()
        ,p = scratch.vector().clone( pt )
        ,A = scratch.vector().clone( linePt1 ).vsub( p )
        ,L = scratch.vector().clone( linePt2 ).vsub( p ).vsub( A )
        ,lambdaB
        ,lambdaA
        ;

    if ( L.equals(Physics.vector.zero) ){
        // oh.. it's a zero vector. So A and B are both the closest.
        // just use one of them
        scratch.done();
        return Physics.vector( linePt1 );
    }

    lambdaB = - L.dot( A ) / L.normSq();
    lambdaA = 1 - lambdaB;

    if ( lambdaA <= 0 ){
        // woops.. that means the closest simplex point
        // isn't on the line it's point B itself
        scratch.done();
        return Physics.vector( linePt2 );
    } else if ( lambdaB <= 0 ){
        // vice versa
        scratch.done();
        return Physics.vector( linePt1 );
    }

    // guess we'd better do the math now...
    p = Physics.vector( linePt2 ).mult( lambdaB ).vadd( A.clone( linePt1 ).mult( lambdaA ) );
    scratch.done();
    return p;
};


text:
package me.zhongmingmao;

import me.zhongmingmao.domain.User;
import me.zhongmingmao.repository.UserReposity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.function.BiFunction;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class DataJpaApplicationTests {

    @Autowired
    private UserReposity userReposity;

    @Test
    public void findByIdTest() {
        assertEquals(2L, userReposity.count());

        BiFunction<Long, String, User> userSupplier = User::new;
        userReposity.save(userSupplier.apply(3L, "Mary"));
        userReposity.save(userSupplier.apply(4L, "Lili"));
        assertEquals(4L, userReposity.count());

        User user = userReposity.findById(3L);
        assertNotNull(user);
        assertEquals(Long.valueOf(3L), user.getId());
        assertEquals("Mary", user.getName());
    }

    @Test
    public void findUserTest() {
        User user = userReposity.findUser(1L);
        assertNotNull(user);
        assertEquals(Long.valueOf(1L), user.getId());
        assertEquals("zhongmingmao", user.getName());
    }

}


text:
<?php

namespace IHQS\ForumBundle\Controller;

use Bundle\ForumBundle\Controller\TopicController as BaseTopicController;
use Bundle\ForumBundle\Model\Topic;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class TopicController extends BaseTopicController
{
    /**
     * @Template()
     */
    public function _latestAction()
    {
        $topics = $this->get('forum.repository.topic')->findAll(true);

        $topics->setCurrentPage(1);
        $topics->setMaxPerPage(5);

        return array(
            'topics'    => $topics,
        );
    }
}


text:
#ifndef SOFT_VPX_H_

#define SOFT_VPX_H_

#include <media/stagefright/omx/SoftVideoDecoderOMXComponent.h>

#include "vpx/vpx_decoder.h"
#include "vpx/vpx_codec.h"
#include "vpx/vp8dx.h"

namespace android {

struct SoftVPX : public SoftVideoDecoderOMXComponent {
    SoftVPX(const char *name,
            const char *componentRole,
            OMX_VIDEO_CODINGTYPE codingType,
            const OMX_CALLBACKTYPE *callbacks,
            OMX_PTR appData,
            OMX_COMPONENTTYPE **component);

protected:
    virtual ~SoftVPX();

    virtual void onQueueFilled(OMX_U32 portIndex);
    virtual void onPortFlushCompleted(OMX_U32 portIndex);
    virtual void onReset();
    virtual bool supportDescribeHdrStaticInfo();

private:
    enum {
        kNumBuffers = 10
    };

    enum {
        MODE_VP8,
        MODE_VP9
    } mMode;

    enum {
        INPUT_DATA_AVAILABLE,  // VPX component is ready to decode data.
        INPUT_EOS_SEEN,        // VPX component saw EOS and is flushing On2 decoder.
        OUTPUT_FRAMES_FLUSHED  // VPX component finished flushing On2 decoder.
    } mEOSStatus;

    void *mCtx;
    bool mFrameParallelMode;  // Frame parallel is only supported by VP9 decoder.
    OMX_TICKS mTimeStamps[kNumBuffers];
    uint8_t mTimeStampIdx;
    vpx_image_t *mImg;

    status_t initDecoder();
    status_t destroyDecoder();
    bool outputBuffers(bool flushDecoder, bool display, bool eos, bool *portWillReset);
    bool outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader);

    DISALLOW_EVIL_CONSTRUCTORS(SoftVPX);
};

}  // namespace android

#endif  // SOFT_VPX_H_


text:
require 'ads_common/savon_service'
require 'adwords_api/v201406/feed_item_service_registry'

module AdwordsApi; module V201406; module FeedItemService
  class FeedItemService < AdsCommon::SavonService
    def initialize(config, endpoint)
      namespace = 'https://adwords.google.com/api/adwords/cm/v201406'
      super(config, endpoint, namespace, :v201406)
    end

    def get(*args, &block)
      return execute_action('get', args, &block)
    end

    def mutate(*args, &block)
      return execute_action('mutate', args, &block)
    end

    def query(*args, &block)
      return execute_action('query', args, &block)
    end

    private

    def get_service_registry()
      return FeedItemServiceRegistry
    end

    def get_module()
      return AdwordsApi::V201406::FeedItemService
    end
  end
end; end; end


text:
.. _Disagreement-sampling:

Disagreement sampling
=====================

When you have several hypotheses about your data, selecting the next instances to label can be done by measuring the disagreement between the hypotheses. Naturally, there are many ways to do that. In modAL, there are three built-in disagreement measures and query strategies: *vote entropy*, *consensus entropy* and *maximum disagreement*. In this quick tutorial, we are going to review them. For more details, see Section 3.4 of the awesome book `Active learning by Burr Settles <http://active-learning.net/>`__.

Disagreement sampling for classifiers
-------------------------------------

Committee-based models in modAL come in two flavors: Committee for classifiers and CommitteeRegressor for regressors. First, let's take a look at disagreement-based sampling strategies for classification!

Vote entropy
^^^^^^^^^^^^

Suppose that you have a Committee of three classifiers, classes ``[0, 1, 2]`` and five instances to classify. If you would like to
calculate the vote entropy, first you ask every classifier about its prediction:

.. code:: python

    >>> vote
    ... [[0, 1, 0]
    ...  [1, 1, 2]
    ...  [0, 1, 2]
    ...  [2, 2, 2]
    ...  [1, 2, 2]]

Each instance has a corresponding probability distribution to it: the distribution of class labels when picking a classifier by random. In the first instance, there are two votes for ``0``, one votes for ``1`` and zero votes for ``2``. In this case, this distribution is ``[0.6666, 0.3333, 0.0]``. The distributions for all instances are

.. code:: python

    >>> p_vote
    ... [[0.6666, 0.3333, 0.0   ]
    ...  [0.0   , 0.6666, 0.3333]
    ...  [0.3333, 0,3333, 0,3333]
    ...  [0.0   , 0.0   , 1.0   ]
    ...  [0.0   , 0.3333, 0.6666]]

Vote entropy selects the instance for which the entropy of this vote distribution is the largest. In this case, the vote entropies are

.. code:: python

    >>> vote_entropy
    ... [0.6365, 0.6365, 1.0986, 0.0, 0.6365]

Since all three votes are different for the third instance, the entropy is the largest there, thus a vote entropy based query strategy would choose that one.

Consensus entropy
^^^^^^^^^^^^^^^^^

Instead of calculating the distribution of the votes, the *consensus
entropy* disagreement measure first calculates the average of the class
probabilities of each classifier. This is called the consensus
probability. Then the entropy of the consensus probability is calculated
and the instance with the largest consensus entropy is selected.

For an example, let's suppose that we continue the previous example with
three classifiers, classes ``[0, 1, 2]`` and five instances to classify.
For each classifier, the class probabilities are

.. code:: python

    >>> vote_proba
    ... [[[0.8, 0.1, 0.0]    # \
    ...   [0.3, 0.7, 0.0]    # |
    ...   [1.0, 0.0, 0.0]    # |  <-- class probabilities for the first classifier
    ...   [0.2, 0.2, 0.6]    # |
    ...   [0.2, 0.7, 0.1]],  # /
    ...  [[0.0, 1.0, 0.0]    # \
    ...   [0.4, 0.6, 0.0]    # |
    ...   [0.2, 0.7, 0.1]    # |  <-- class probabilities for the second classifier
    ...   [0.3, 0.1, 0.6]    # |
    ...   [0.0, 0.0, 1.0]],  # /
    ...  [[0.7, 0.2, 0.1]    # \
    ...   [0.4, 0.0, 0.6]    # |
    ...   [0.3, 0.2, 0.5]    # |  <-- class probabilities for the third classifier
    ...   [0.1, 0.0, 0.9]    # |
    ...   [0.0, 0.1, 0.9]]]  # /

In this case, the consensus probabilities are

.. code:: python

    >>> consensus_proba
    ... [[0.5   , 0.4333, 0.0333]
    ...  [0.3666, 0.4333, 0.2   ]
    ...  [0.5   , 0.3   , 0.2   ]
    ...  [0.2   , 0.1   , 0.7   ]
    ...  [0.0666, 0.2666, 0.6666]]

The entropy of this is

.. code:: python

    >>> consensus_entropy
    ... [0.8167, 1.0521, 1.0296, 0.8018, 0.8033]

Even though the votes for the second instance are ``[1, 1, 2]``, since the classifiers are quite unsure, thus the consensus entropy is high. In this case, the query strategy would select the second example to be labelled by the Oracle.

Max disagreement
^^^^^^^^^^^^^^^^

The disagreement measures so far take the actual *disagreement* into account in a weak way. Instead of this, it is possible to measure each learner's disagreement with the consensus probabilities and query the instance where the disagreement is largest for some learner. This is called *max disagreement sampling*. Continuing our example, if the vote probabilities for each learner and the consensus probabilities are given, we can calculate the `Kullback-Leibler divergence <https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence>`__ of each learner to the consensus prediction and then for each instance, select the largest value.

.. code:: python

    >>> for i in range(5):
    >>>     for j in range(3):
    >>>         learner_KL_div[i, j] = entropy(vote_proba[j, i], qk=consensus_proba[i])
    >>>
    >>> learner_KL_div
    ... [[0.32631363,  0.80234647,  0.15685227],
    ...  [0.27549995,  0.23005799,  0.69397192],
    ...  [0.69314718,  0.34053564,  0.22380466],
    ...  [0.04613903,  0.02914912,  0.15686827],
    ...  [0.70556709,  0.40546511,  0.17201121]]
    >>>
    >>> max_disagreement
    ... [0.80234647,  0.69397192,  0.69314718,  0.15686827,  0.70556709]

In this case, one of the learner highly disagrees with the others in the class of the first instance. Thus, the max disagreement sampling would choose this one to be labelled by the Oracle.

Disagreement sampling for regressors
------------------------------------

Since regressors, in general, don't provide a way to calculate prediction probabilities, disagreement measures for classifiers may not work with regressors. Despite this, ensemble regression models can be always used in an active learning scenario, because the standard deviation of the predictions at a given point can be thought of as a measure of disagreement.

Standard deviation sampling
^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. figure:: img/er-initial.png
   :align: center

When a committee of regressors is available, the uncertainty of predictions can be estimated by calculating the standard deviation of predictions. This is done by the ``modAL.disagreement.max_std_sampling`` function.

Disagreement measures in action
-------------------------------

To visualize the disagreement measures, let's consider a toy example! Suppose that we would like to learn these two objects:

.. figure:: img/dis-data.png
   :align: center

We train two random forest classifiers:

.. figure:: img/dis-learners.png
   :align: center

The consensus predictions of these learners are

.. figure:: img/dis-consensus.png
   :align: center

In this case, the disagreement measures from left to right are vote entropy, consensus entropy, and max disagreement.

.. figure:: img/dis-measures.png
   :align: center


text:
export ECR_REGION="us-east-1"
export IMAGE_NAME="java8-base"
export IMAGE_TAG="8s.02"

AWS_ACCOUNT_ID=$(aws sts get-caller-identity --output text --query Account)

ECR_URL="$AWS_ACCOUNT_ID.dkr.ecr.$ECR_REGION.amazonaws.com"

$(aws ecr get-login --no-include-email --region $ECR_REGION)

docker build -t $IMAGE_NAME:$IMAGE_TAG .
docker tag $IMAGE_NAME:$IMAGE_TAG $ECR_URL/$IMAGE_NAME:$IMAGE_TAG
docker push $ECR_URL/$IMAGE_NAME:$IMAGE_TAG


text:
class Todo < ActiveRecord::Base
  validates :name, presence: true
end


text:
                    Hasan Basri

            Freelance programmer

            Also known as creatorb [creatorbe] an a muslim who has passion for searching, researching, learning new things to acquiring immense knowledge for help others. Everyday i spend my day as software engineer, life in front of a computer as i am coding, debugging, reading, discussing and i spare my time to learn Quran.

                    WA

                        +6289619060672

                    TG

                        @creatorbe

                    BBM

                        5F5353B6

                     Email

                        creatorb45@gmail.com


text:
/**
 * @file Manage actions and UI for test commands
 * @since 1.0.0
 * @author kh5325.kim@samsung.com
 * @extends module:ProjectWizard/ViewCommands
 */
define([
    'dojo',
    'dojo/Deferred',
    'dojo/topic',
    'lib/test/bootstrap/bootstrap.custom',
    'lib/test/bootstrap/bootstrap-multiselect',
    'webida-lib/util/logger/logger-client',
    'webida-lib/util/path',
    'webida-lib/plugins/workspace/plugin',
    'webida-lib/webida-0.3',
    'webida-lib/widgets/views/view',
    'webida-lib/widgets/views/viewmanager',
    'text!./layer/test-layout.html',
    'text!./layer/test-toolbar.html',
    'text!./frames.json',
    './messages',
    './view-commands',
    './lib/clipboard',
    './lib/util'
], function (
    dojo,
    Deferred,
    topic,
    bootstrap,
    bootstrapMultiselect,
    Logger,
    pathUtil,
    wv,
    webida,
    View,
    vm,
    tplLayout,
    tplToolbar,
    frames,
    Messages,
    ViewCommand,
    Clipboard,
    Util
) {
    'use strict';

    var logger = new Logger();
    logger.off();

    var VIEW_ID = 'VIEW_TEST';

    var FRAMES = JSON.parse(frames).frames;

    function TestViewCommand() {
        _self = this;
        this.$resolutions = null;
        this.url = null;
    }

    // inherit ViewCommand
    var _super = TestViewCommand.prototype = new ViewCommand(VIEW_ID);
    // correct the constructor pointer because it points to ViewCommand
    TestViewCommand.prototype.constructor = TestViewCommand;
    var _self = null;

    TestViewCommand.prototype.doTest = function () {
        var curDir = wv.getSelectedPath();
        logger.log('doTest', curDir || null);

        _super.setHandler();
        _super.createView('Test', 'Test Center', tplLayout);
        _super.getView().select();
    }; // doTest

    TestViewCommand.prototype.onViewAppended = function () {
        _super.initView(tplToolbar, function (selectedProjectPath) {
            if (_self.getProjectPath() === selectedProjectPath) {
                return;
            }
            _self.refreshView();
            // FIXME use directly `reg.byId('testTab').selectChild()` method
            Util.selectTab('testTab', 'testPreview');
        });

        _self.$resolutions = $('#testResolutions');
        _self.$resolutions.multiselect({
            includeSelectAllOption: false,
            enableCaseInsensitiveFiltering: false
        });

        _self.init(); // Event listeners should be attached once
        _self.refreshView();
        _super.getView().select();
    };

    TestViewCommand.prototype.init = function () {
        logger.log('init');
        var self = this;

        this.setProjectPath(pathUtil.getProjectRootPath(wv.getSelectedPath()));
        var projectPath = this.getProjectPath();
        if (!projectPath) {
            logger.log(Messages.NO_PROJECT);
            return;
        }

        $('#testAppTitle').text(pathUtil.getName(projectPath));

        $('#testFrames').empty();
        $('.device-list').empty();

        var cbResolutions = self.$resolutions;
        $.each(FRAMES, function (index, value) {
            var $option = $('<option value=\'' + value.label + '\'>' +
                            (value.width + ' x ' + value.height + ' ' + value.label) + '</option>');
            if (value.selected) {
                $option.attr('selected', '');
            }
            cbResolutions.append($option);
        });

        $('#testCapture').click(function () {
            require(['plugins/project-wizard/lib/capture'], function (Capture) {
                var capture = new Capture();
                capture.capture('#testFrames .frame',
                                { base: self.url.substring(0, self.url.lastIndexOf('/') + 1) }).then(
                    function (data) {
                        Util.downloadFile(data, 'screenshot.png');
                    },
                    function (err) {
                        switch (err.message) {
                        case Capture.NONE_SELECTED :
                            Util.showAssist('#testResolutions + .btn-group', Messages.SELECT_RESOLUTIONS);
                            break;
                        }
                    }
                );
            });
        });

        $('#testToolsCompAppPreview').click(function (e) {
            // FIXME use directly `reg.byId('testTab').selectChild()` method
            Util.selectTab('testTab', 'testPreview');
            // Stopping the click event from propagating to the document.
            // Bootstrap sets an event listener on the document that closes dropdowns.
            e.stopPropagation();
            $('#testViewOnPhone').find('[data-toggle=dropdown]').dropdown('toggle');
        });

        require(['plugins/project-wizard/device/device'], function (Device) {
            var device = new Device();
            device.init();
        });
    };

    TestViewCommand.prototype.refreshView = function () {
        logger.log('refreshView');
        var self = this;
        this.refresh().then(
            function () {
                $('#testAppTitle').text(pathUtil.getName(self.getProjectPath()));
                $('#testFrames').empty();
            }
        );
    };

    TestViewCommand.prototype.refresh = function () {
        logger.log('refresh');
        var self = this;
        var deferred = new Deferred();
        this.setProjectPath(pathUtil.getProjectRootPath(wv.getSelectedPath()));
        var projectPath = this.getProjectPath();
        if (!projectPath) {
            logger.log(Messages.NO_PROJECT);
            return deferred.reject(new Error(Messages.NO_PROJECT));
        }

        var path = pathUtil.detachSlash(projectPath);
        Util.getAliasPathForIndexFile(path, function (url) {
            self.url = url;
            $('#testQRCode').attr('src', '//chart.googleapis.com/chart?cht=qr&chs=150x150&chl=' + url);

            Clipboard.destroy();
            // init ZeroClipboard
            new Clipboard('.js-zeroclipboard', url); //jshint ignore:line

            var cbResolutions = self.$resolutions;
            cbResolutions.multiselect('setOptions', {
                onChange: function () {
                    cbResolutions.siblings('div').children('ul').dropdown('toggle');
                    self.reload(url);
                }
            });
            cbResolutions.multiselect('rebuild');
            // deselect all
            $('option', cbResolutions).each(function () {
                cbResolutions.multiselect('deselect', $(this).val());
            });

            $('#testCapture').prop('disabled', true);

            return deferred.resolve();
        });
        return deferred.promise;
    };

    TestViewCommand.prototype.reload = function (url) {
        var selectedFrames = [];
        $('#testFrames').empty();
        if (this.$resolutions.val()) {
            $('#testCapture').prop('disabled', false);
            $.each(this.$resolutions.val(), function (index, value) {
                var frame = _getFrame(value);
                if (frame) {
                    selectedFrames.push(frame);
                }
            });

            responsivate(url, selectedFrames);
        } else {
            $('#testCapture').prop('disabled', true);
        }
    };

    function responsivate(url, selectedFrames) {
        if (url.indexOf('http:') === -1 && url.indexOf('https:') === -1) {
            url = 'http://' + url;
        }

        require(['plugins/project-wizard/lib/frames'], function (Frames) {
            /* jshint -W031 */
            new Frames({
                'url': url,
                target: '#testFrames',
                frames: selectedFrames
            });
             /* jshint +W031 */
        });
    }

    function _getFrame(value) {
        var frame = null;
        $.each(FRAMES, function (index, FRAME) {
            if (value === FRAME.label) {
                frame = FRAME;
                return false;
            }
        });
        return frame;
    }

    return new TestViewCommand();
});


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Cake.Core;

namespace Cake.Common.Build.Jenkins.Data
{
    /// <summary>
    /// Provides Jenkins environment information for the current build.
    /// </summary>
    public sealed class JenkinsEnvironmentInfo : JenkinsInfo
    {
        /// <summary>
        /// Gets Jenkins build information.
        /// </summary>
        /// <value>
        /// The build.
        /// </value>
        public JenkinsBuildInfo Build { get; }

        /// <summary>
        /// Gets Jenkins repository information.
        /// </summary>
        /// <value>
        /// The repository.
        /// </value>
        public JenkinsRepositoryInfo Repository { get; }

        /// <summary>
        /// Gets Jenkins job information.
        /// </summary>
        /// <value>
        /// The job.
        /// </value>
        public JenkinsJobInfo Job { get; }

        /// <summary>
        /// Gets the node.
        /// </summary>
        /// <value>
        /// The node.
        /// </value>
        public JenkinsNodeInfo Node { get; }

        /// <summary>
        /// Gets the jenkins home.
        /// </summary>
        /// <value>
        /// The jenkins home.
        /// </value>
        public string JenkinsHome => GetEnvironmentString("JENKINS_HOME");

        /// <summary>
        /// Gets the jenkins URL.
        /// </summary>
        /// <value>
        /// The jenkins URL.
        /// </value>
        public string JenkinsUrl => GetEnvironmentString("JENKINS_URL");

        /// <summary>
        /// Gets the executor number.
        /// </summary>
        /// <value>
        /// The executor number.
        /// </value>
        public int ExecutorNumber => GetEnvironmentInteger("EXECUTOR_NUMBER");

        /// <summary>
        /// Gets the workspace.
        /// </summary>
        /// <value>
        /// The workspace.
        /// </value>
        public string Workspace => GetEnvironmentString("WORKSPACE");

        /// <summary>
        /// Initializes a new instance of the <see cref="JenkinsEnvironmentInfo" /> class.
        /// </summary>
        /// <param name="environment">The environment.</param>
        public JenkinsEnvironmentInfo(ICakeEnvironment environment) : base(environment)
        {
            Build = new JenkinsBuildInfo(environment);
            Repository = new JenkinsRepositoryInfo(environment);
            Node = new JenkinsNodeInfo(environment);
            Job = new JenkinsJobInfo(environment);
        }
    }
}


text:
package com.soteradefense.datawake.trails.topology.save.data

/**
 * Helper class for defining parameters passed along with the crawl request.
 * @param org Org
 * @param domain Domain
 * @param trail Trail
 * @param title Url's title
 * @param rank Rank of the Url
 */
case class DatawakeDomainTriplet(org: String, domain: String, trail: String, title: String, rank: String)


text:
```bash
$ csspack **/*.html dist
```

## Installation

```bash
$ npm install -g csspack
```


text:
class Campaign < ActiveRecord::Base
  def to_resource(options = {})
    CampaignResource.new(self, options)
  end
end


text:
from django.urls import include, path

urlpatterns = [path("api/v1/", include("tests.app.router", namespace="api_v1"))]


text:
using System;
using Csla;

namespace SelfLoadROSoftDelete.DataAccess.Sql.ERCLevel
{
    public partial class H11_CityRoadCollDal
    {
    }
}


text:
namespace AustinSite.Utils
{
    public static class StringUtils
    {
        public static string RemoveInvalidCharsAndNormalize(string removeFrom)
        {
            return removeFrom.ToLower().Replace("-", " ");
        }

        public static string GetFirstName(this string name)
        {
            var names = name.Split(' ');

            if (name.Length == 0)
                return string.Empty;

            return names[0];
        }
    }
}


text:
This is the main interface for using the ported RSA implementation. See http://en.wikipedia.org/wiki/RSA for more details. This port to repy is primarily taken from Dwayne C. Litzenberger's (www.dlitz.net) python code.

### Functions

```
def rsa_gen_pubpriv_keys(bitsize):
```

   Will generate a new key object with a key size of the argument bitsize and return it. A recommended value would be 1024.

   Notes:

   * bitsize is the number of bits that the key should have. This means the modulus (publickey - n) will be in the range [2**(bitsize - 1), 2**(bitsize) - 1]
   * Will return a key object that rsa_encrypt, rsa_decrypt, rsa_sign, and rsa_validate can use to preform their tasts.

```
def rsa_encrypt(message, publickey):
```

   Will use the key to encrypt the message string. If the string is to large to be encrypted it will be broken into chunks that are suitable for the keys modulus by the _rsa_chopstring function.

   Notes:

   * message is the string to be encrypted, there is no restriction on size.
   * publickey must be a valid publickey dictionary of the form {'n': 1.., 'e': 6..} with the keys being 'n' and 'e'.
   * Raises ValueError if public key is invalid.
   * Raises _slowmath_error if the key object lacks a public key, (elements 'e' and 'n')
   * Will return a string with the cypher text broken up and stored in the seperate integer representation. For example it might be similar to the string " 1422470 3031373 65044827" but with much larger integers.

```
def rsa_decrypt(cypher, privatekey):
```

   Will use the private key to decrypt the cypher string.

   If the plaintext string was to large to be encrypted it will use _rsa_gluechops and _rsa_unpicklechops to reassemble the origional plaintext after the individual peices are decrypted.

   Notes:

   * cypher is the encrypted string that was returned by rsa_encrypt. Example: " 142247030 31373650 44827705"
   * privatekey must be a valid privatekey dictionary of the form {'d':1.., 'p':1.. 'q': 1..} with the keys being 'd', 'p', and 'q'.
   * Raises ValueError if private key is invalid.
   * Raises _slowmath_error if the key object lacks a private key with (elements 'd' and 'n').
   * This will return the plaintext string that was encrypted with rsa_encrypt.

```
def rsa_sign(message, privatekey):
```

   Will use the key to sign the plaintext string.

   Notes:

   * message is the string to be encrypted, there is no restriction on size.
   * publickey must be a valid publickey dictionary of the form {'n': 1.., 'e': 6..} with the keys being 'n' and 'e'.
   * Raises ValueError if public key is invalid.
   * Raises _slowmath_error if the key object lacks a public key, (elements 'e' and 'n')
   * Will return a string with the cypher text broken up and stored in the seperate integer representation. For example it might be similar to the string " 1422470 3031373 65044827" but with much larger integers.

```
def rsa_verify(cypher, publickey):
```

   Will use the private key to decrypt the cypher string.

   Notes:

   * If the plaintext string was to large to be encrypted it will use _rsa_gluechops and _rsa_unpicklechops to reassemble the origional plaintext after the individual peices are decrypted.
   * cypher is the encrypted string that was returned by rsa_encrypt. Example: " 142247030 31373650 44827705"
   * privatekey must be a valid privatekey dictionary of the form {'d':1.., 'p':1.. 'q': 1..} with the keys being 'd', 'p', and 'q'.
   * Raises ValueError if private key is invalid.
   * Raises _slowmath_error if the key object lacks a private key with (elements 'd' and 'n').
   * This will return the plaintext string that was encrypted with rsa_encrypt.

```
def rsa_is_valid_privatekey(key):
```

   This tries to determine if a key is valid. If it returns False, the key is definitely invalid. If True, the key is almost certainly valid.

   Notes:

   * key is a dictionary of the form {'d':1.., 'p':1.. 'q': 1..} with the keys 'd', 'p', and 'q'
   * If the key is valid, True will be returned. Otherwise False will be returned.

```
def rsa_is_valid_publickey(key):
```

   Exactly as the rsa_is_valid_privatekey method, but for public keys.

```
def rsa_publickey_to_string(publickey):
```
   To convert a publickey to a string. It will read the publickey which should a dictionary, and return it in the appropriate string format.

   Notes:

   * Must be a valid publickey dictionary of the form {'n': 1.., 'e': 6..} with the keys 'n' and 'e'.
   * Raises ValueError if the publickey is invalid.
   * Returns a string containing the publickey. Example: if the publickey was {'n':21, 'e':3} then returned string would be "3 21"

```
def rsa_string_to_publickey(mystr):
```

   To read a private key string and return a dictionary in the appropriate format: {'n': 1.., 'e': 6..} with the keys 'n' and 'e'.

   Notes:

   * mystr is a string containing the publickey, should be in the format created by the function rsa_publickey_to_string. Example if e=3 and n=21, mystr = "3 21"
   * Raises ValueError if the string containing the privateky is in a invalid format.
   * Returns a publickey dictionary of the form {'n': 1.., 'e': 6..} with the keys 'n' and 'e'.

```
def rsa_privatekey_to_string(privatekey):
```

   Same as above, but with private keys.

```
def rsa_string_to_privatekey(mystr):
```

   Same as above, but with private keys.

```
def rsa_privatekey_to_file(key,filename):
```

   To write a privatekey to a file. It will convert the privatekey which should a dictionary, to the appropriate format and write it to a file, so that it can be read by rsa_file_to_privatekey.

   Notes:

   * privatekey must be a valid privatekey dictionary of the form {'d':1.., 'p':1.. 'q': 1..} with the keys 'd', 'p', and 'q'
   * filename is the string containing the name for the desired publickey file.
   * Raises ValueError if the privatekey is invalid.
   * Raises IOError if the file cannot be opened.

```
def rsa_file_to_privatekey(filename):
```

   To read a file containing a key that was created with rsa_privatekey_to_file and return it in the appropriate format: {'d':1.., 'p':1.. 'q': 1..} with the keys 'd', 'p', and 'q'.

   Notes:

   * filename is the name of the file containing the privatekey.
   * Raises ValueError if the file contains an invalid private key string.
   * Raises IOError if the file cannot be opened.
   * Returns a privatekey dictionary of the form {'d':1.., 'p':1.. 'q': 1..} with the keys 'd', 'p', and 'q'.

```
def rsa_publickey_to_file(publickey, filename):
```
   Same as above but with public keys.

```
def rsa_file_to_publickey(filename):
```
   Same as above but with public keys.

```
def rsa_matching_keys(privatekey, publickey):
```

### Includes

[random.repy](random.repy.md)

[pycryptorsa.repy](pycryptorsa.repy.md)


text:
package com.InfinityRaider.AgriCraft.compatibility.computercraft.method;

public class MethodException extends Exception {
    private IMethod method;
    private String msg;

    public MethodException(IMethod method, String msg) {
        this.method = method;
        this.msg = msg;
    }

    public String getDescription() {
        return "Method '"+method.getName()+"' errored: "+msg;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace academyTest
{
    class Program
    {
        static void testFn (StringBuilder test)
        {
            test.Append("lets try this way");
        }

        static void Main(string[] args)
        {
            StringBuilder test = new StringBuilder("This is a test");
            testFn(test);
            Console.WriteLine(test);
        }
    }
}


text:
using UnityEngine;
using System;

namespace AmplifyShaderEditor
{
	//public enum VertexData
	//{
	//	vertex = 0,
	//	tangent,
	//	normal,
	//	texcoord,
	//	texcoord1,
	//	color
	//}

	[Serializable]
	public class VertexDataNode : ParentNode
	{
		[SerializeField]
		protected string m_currentVertexData;

		protected override void CommonInit( int uniqueId )
		{
			base.CommonInit( uniqueId );
			m_currentVertexData = "vertex";

//			Type type = typeof( StandardSurfaceOutputNode );
			//m_restictions.AddPortRestriction( type, 0 );
			//m_restictions.AddPortRestriction( type, 2 );
			//m_restictions.AddPortRestriction( type, 3 );
			//m_restictions.AddPortRestriction( type, 4 );
			//m_restictions.AddPortRestriction( type, 5 );
			//m_restictions.AddPortRestriction( type, 6 );
			//m_restictions.AddPortRestriction( type, 7 );
			//m_restictions.AddPortRestriction( type, 8 );
			//m_restictions.AddPortRestriction( type, 9 );
			//m_restictions.AddPortRestriction( type, 10 );
			AddOutputVectorPorts( WirePortDataType.FLOAT4, "Out" );
		}

		public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar )
		{
			base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalVar );
			return GetOutputVectorItem( 0, outputId, Constants.VertexShaderInputStr + "." + m_currentVertexData );
		}
	}
}


text:
ACCEPTED

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

#### Published in
in Smith, Trappe, Rizzo & Miller, Mycol. Res. 110(5): 577 (2006)

#### Original name
Gymnomyces xerophilus M.E. Sm. & Trappe, 2006

### Remarks
null


text:
#include "tensorflow/lite/micro/micro_error_reporter.h"

#include <cstdarg>
#include <cstdint>
#include <new>

#include "tensorflow/lite/micro/micro_log.h"

namespace {
uint8_t micro_error_reporter_buffer[sizeof(tflite::MicroErrorReporter)];
tflite::MicroErrorReporter* error_reporter_ = nullptr;

}  // namespace

namespace tflite {
ErrorReporter* GetMicroErrorReporter() {
  if (error_reporter_ == nullptr) {
    error_reporter_ = new (micro_error_reporter_buffer) MicroErrorReporter();
  }
  return error_reporter_;
}

int MicroErrorReporter::Report(const char* format, va_list args) {
  Log(format, args);
  return 0;
}

}  // namespace tflite


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<!-- Your own application should inherit from spring-boot-starter-parent -->
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-samples</artifactId>
		<version>${revision}</version>
	</parent>
	<artifactId>spring-boot-sample-web-method-security</artifactId>
	<name>Spring Boot Web Method Security Sample</name>
	<description>Spring Boot Web Method Security Sample</description>
	<properties>
		<main.basedir>${basedir}/../..</main.basedir>
	</properties>
	<dependencies>
		<!-- Compile -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<!-- Test -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>