text:
from __future__ import unicode_literals

from django.db import models, migrations
import taggit.managers
import aldryn_categories.fields
import aldryn_newsblog.models
import filer.fields.image
from django.conf import settings
import sortedm2m.fields
import django.utils.timezone
import djangocms_text_ckeditor.fields
import cms.models.fields
import app_data.fields
import aldryn_apphooks_config.fields
import django.core.validators

class Migration(migrations.Migration):

    dependencies = [
        ('taggit', '0001_initial'),
        ('cms', '0001_initial'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('aldryn_people', '0001_initial'),
        ('filer', '0001_initial'),
        ('aldryn_categories', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Article',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('publishing_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='publishing date')),
                ('is_published', models.BooleanField(default=True, db_index=True, verbose_name='is published')),
                ('is_featured', models.BooleanField(default=False, db_index=True, verbose_name='is featured')),
            ],
            options={
                'ordering': ['-publishing_date'],
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='ArticleTranslation',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('language_code', models.CharField(max_length=15, verbose_name='Language', db_index=True)),
                ('title', models.CharField(max_length=234, verbose_name='title')),
                ('slug', models.SlugField(help_text='Used in the URL. If changed, the URL will change. Clear it to have it re-created automatically.', max_length=255, verbose_name='slug', blank=True)),
                ('lead_in', djangocms_text_ckeditor.fields.HTMLField(default='', help_text='Will be displayed in lists, and at the start of the detail page (in bold)', verbose_name='Optional lead-in', blank=True)),
                ('meta_title', models.CharField(default='', max_length=255, verbose_name='meta title', blank=True)),
                ('meta_description', models.TextField(default='', verbose_name='meta description', blank=True)),
                ('meta_keywords', models.TextField(default='', verbose_name='meta keywords', blank=True)),
                ('search_data', models.TextField(editable=False, blank=True)),
                ('master', models.ForeignKey(related_name='translations', editable=False, to='aldryn_newsblog.Article', null=True)),
            ],
            options={
                'managed': True,
                'db_table': 'aldryn_newsblog_article_translation',
                'db_tablespace': '',
                'default_permissions': (),
                'verbose_name': 'article Translation',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='NewsBlogArchivePlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(parent_link=True, related_name='+', primary_key=True, serialize=False, to='cms.CMSPlugin')),
            ],
            options={
                'abstract': False,
            },
            bases=(aldryn_newsblog.models.PluginEditModeMixin, 'cms.cmsplugin'),
        ),
        migrations.CreateModel(
            name='NewsBlogArticleSearchPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(parent_link=True, related_name='+', primary_key=True, serialize=False, to='cms.CMSPlugin')),
                ('max_articles', models.PositiveIntegerField(default=10, help_text='The maximum number of found articles display.', verbose_name='max articles', validators=[django.core.validators.MinValueValidator(1)])),
            ],
            options={
                'abstract': False,
            },
            bases=('cms.cmsplugin',),
        ),
        migrations.CreateModel(
            name='NewsBlogAuthorsPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(parent_link=True, related_name='+', primary_key=True, serialize=False, to='cms.CMSPlugin')),
            ],
            options={
                'abstract': False,
            },
            bases=(aldryn_newsblog.models.PluginEditModeMixin, 'cms.cmsplugin'),
        ),
        migrations.CreateModel(
            name='NewsBlogCategoriesPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(parent_link=True, related_name='+', primary_key=True, serialize=False, to='cms.CMSPlugin')),
            ],
            options={
                'abstract': False,
            },
            bases=(aldryn_newsblog.models.PluginEditModeMixin, 'cms.cmsplugin'),
        ),
        migrations.CreateModel(
            name='NewsBlogConfig',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('type', models.CharField(max_length=100, verbose_name='type')),
                ('namespace', models.CharField(default=None, unique=True, max_length=100, verbose_name='instance namespace')),
                ('app_data', app_data.fields.AppDataField(default=dict, editable=False)),
                ('permalink_type', models.CharField(default='slug', help_text='Choose the style of urls to use from the examples. (Note, all types are relative to apphook)', max_length=8, verbose_name='permalink type', choices=[('s', 'the-eagle-has-landed/'), ('ys', '1969/the-eagle-has-landed/'), ('yms', '1969/07/the-eagle-has-landed/'), ('ymds', '1969/07/16/the-eagle-has-landed/'), ('ymdi', '1969/07/16/11/')])),
                ('non_permalink_handling', models.SmallIntegerField(default=302, help_text='How to handle non-permalink urls?', verbose_name='non-permalink handling', choices=[(200, 'Allow'), (302, 'Redirect to permalink (default)'), (301, 'Permanent redirect to permalink'), (404, 'Return 404: Not Found')])),
                ('paginate_by', models.PositiveIntegerField(default=5, help_text='When paginating list views, how many articles per page?', verbose_name='Paginate size')),
                ('create_authors', models.BooleanField(default=True, help_text='Automatically create authors from logged-in user?', verbose_name='Auto-create authors?')),
                ('search_indexed', models.BooleanField(default=True, help_text='Include articles in search indexes?', verbose_name='Include in search index?')),
                ('placeholder_base_sidebar', cms.models.fields.PlaceholderField(related_name='aldryn_newsblog_base_sidebar', slotname='newsblog_base_sidebar', editable=False, to='cms.Placeholder', null=True)),
                ('placeholder_base_top', cms.models.fields.PlaceholderField(related_name='aldryn_newsblog_base_top', slotname='newsblog_base_top', editable=False, to='cms.Placeholder', null=True)),
                ('placeholder_detail_bottom', cms.models.fields.PlaceholderField(related_name='aldryn_newsblog_detail_bottom', slotname='newsblog_detail_bottom', editable=False, to='cms.Placeholder', null=True)),
                ('placeholder_detail_footer', cms.models.fields.PlaceholderField(related_name='aldryn_newsblog_detail_footer', slotname='newsblog_detail_footer', editable=False, to='cms.Placeholder', null=True)),
                ('placeholder_detail_top', cms.models.fields.PlaceholderField(related_name='aldryn_newsblog_detail_top', slotname='newsblog_detail_top', editable=False, to='cms.Placeholder', null=True)),
                ('placeholder_list_footer', cms.models.fields.PlaceholderField(related_name='aldryn_newsblog_list_footer', slotname='newsblog_list_footer', editable=False, to='cms.Placeholder', null=True)),
                ('placeholder_list_top', cms.models.fields.PlaceholderField(related_name='aldryn_newsblog_list_top', slotname='newsblog_list_top', editable=False, to='cms.Placeholder', null=True)),
            ],
            options={
                'abstract': False,
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='NewsBlogConfigTranslation',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('language_code', models.CharField(max_length=15, verbose_name='Language', db_index=True)),
                ('app_title', models.CharField(max_length=234, verbose_name='application title')),
                ('master', models.ForeignKey(related_name='translations', editable=False, to='aldryn_newsblog.NewsBlogConfig', null=True)),
            ],
            options={
                'managed': True,
                'db_table': 'aldryn_newsblog_newsblogconfig_translation',
                'db_tablespace': '',
                'default_permissions': (),
                'verbose_name': 'news blog config Translation',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='NewsBlogFeaturedArticlesPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(parent_link=True, related_name='+', primary_key=True, serialize=False, to='cms.CMSPlugin')),
                ('article_count', models.PositiveIntegerField(default=1, help_text='The maximum number of featured articles display.', validators=[django.core.validators.MinValueValidator(1)])),
                ('app_config', models.ForeignKey(to='aldryn_newsblog.NewsBlogConfig')),
            ],
            options={
                'abstract': False,
            },
            bases=(aldryn_newsblog.models.PluginEditModeMixin, 'cms.cmsplugin'),
        ),
        migrations.CreateModel(
            name='NewsBlogLatestArticlesPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(parent_link=True, related_name='+', primary_key=True, serialize=False, to='cms.CMSPlugin')),
                ('latest_articles', models.IntegerField(default=5, help_text='The maximum number of latest articles to display.')),
                ('app_config', models.ForeignKey(to='aldryn_newsblog.NewsBlogConfig')),
            ],
            options={
                'abstract': False,
            },
            bases=(aldryn_newsblog.models.PluginEditModeMixin, 'cms.cmsplugin'),
        ),
        migrations.CreateModel(
            name='NewsBlogRelatedPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(parent_link=True, related_name='+', primary_key=True, serialize=False, to='cms.CMSPlugin')),
            ],
            options={
                'abstract': False,
            },
            bases=(aldryn_newsblog.models.PluginEditModeMixin, 'cms.cmsplugin'),
        ),
        migrations.CreateModel(
            name='NewsBlogTagsPlugin',
            fields=[
                ('cmsplugin_ptr', models.OneToOneField(parent_link=True, related_name='+', primary_key=True, serialize=False, to='cms.CMSPlugin')),
                ('app_config', models.ForeignKey(to='aldryn_newsblog.NewsBlogConfig')),
            ],
            options={
                'abstract': False,
            },
            bases=(aldryn_newsblog.models.PluginEditModeMixin, 'cms.cmsplugin'),
        ),
        migrations.AlterUniqueTogether(
            name='newsblogconfigtranslation',
            unique_together=set([('language_code', 'master')]),
        ),
        migrations.AddField(
            model_name='newsblogcategoriesplugin',
            name='app_config',
            field=models.ForeignKey(to='aldryn_newsblog.NewsBlogConfig'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='newsblogauthorsplugin',
            name='app_config',
            field=models.ForeignKey(to='aldryn_newsblog.NewsBlogConfig'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='newsblogarticlesearchplugin',
            name='app_config',
            field=models.ForeignKey(to='aldryn_newsblog.NewsBlogConfig'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='newsblogarchiveplugin',
            name='app_config',
            field=models.ForeignKey(to='aldryn_newsblog.NewsBlogConfig'),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='articletranslation',
            unique_together=set([('language_code', 'master'), ('language_code', 'slug')]),
        ),
        migrations.AddField(
            model_name='article',
            name='app_config',
            field=aldryn_apphooks_config.fields.AppHookConfigField(verbose_name='app. config', to='aldryn_newsblog.NewsBlogConfig', help_text='When selecting a value, the form is reloaded to get the updated default'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='article',
            name='author',
            field=models.ForeignKey(verbose_name='author', blank=True, to='aldryn_people.Person', null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='article',
            name='categories',
            field=aldryn_categories.fields.CategoryManyToManyField(to='aldryn_categories.Category', verbose_name='categories', blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='article',
            name='content',
            field=cms.models.fields.PlaceholderField(related_name='newsblog_article_content', slotname='newsblog_article_content', editable=False, to='cms.Placeholder', null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='article',
            name='featured_image',
            field=filer.fields.image.FilerImageField(blank=True, to='filer.Image', null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='article',
            name='owner',
            field=models.ForeignKey(verbose_name='owner', to=settings.AUTH_USER_MODEL),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='article',
            name='related',
            field=sortedm2m.fields.SortedManyToManyField(help_text=None, related_name='related_rel_+', verbose_name='related articles', to='aldryn_newsblog.Article', blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='article',
            name='tags',
            field=taggit.managers.TaggableManager(to='taggit.Tag', through='taggit.TaggedItem', blank=True, help_text='A comma-separated list of tags.', verbose_name='Tags'),
            preserve_default=True,
        ),
    ]


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.Network
{
	/// <summary>
	/// Specifies whether to always send extra HTTP headers with the requests from this page.
	/// </summary>
	[CommandResponse(ProtocolName.Network.SetExtraHTTPHeaders)]
	public class SetExtraHTTPHeadersCommandResponse
	{
	}
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef Prime_INCLUDED
#define Prime_INCLUDED

#include <vector>
#include "Types.h"

using std::vector;

class Prime
{
public:
    typedef vector<UInt32> Primes;

    bool IsPrime( Int32 n );

    Primes GetPrimes( Int32 n );

private:
    Primes _primes;
    UInt32 _nprimes;
};

#endif // Prime_INCLUDED


text:
// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with Alana Farkas:
// This challenge took me 2 hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode
// 1. Iterate over votes object for votes.length
// 2. Get president value and push it to voteCount
// 3. If voteCount is empty, add value of 1 to name property. Or else create a value of 1
// 4. Repeat steps 1-3 for the rest of the offices.

// __________________________________________
// Initial Solution

// function pushVotes(object){
//   for (var student in votes) {
//     if (voteCount.president.hasOwnProperty(votes[student].president)){
//         voteCount.president[[votes[student].president]] += 1;
//     }
//     else {
//       voteCount.president[[votes[student].president]] = 1;
//     }
//   };

//   for (var student in votes) {
//     if (voteCount.vicePresident.hasOwnProperty(votes[student].vicePresident)) {
//       voteCount.vicePresident[[votes[student].vicePresident]] += 1;
//     }
//     else {
//       voteCount.vicePresident[[votes[student].vicePresident]] = 1;
//     };
//   }

//     for (var student in votes) {
//     if (voteCount.secretary.hasOwnProperty(votes[student].secretary)) {
//       voteCount.secretary[[votes[student].secretary]] += 1;
//     }
//     else {
//       voteCount.secretary[[votes[student].secretary]] = 1;
//     };
//   }
//       for (var student in votes) {
//     if (voteCount.treasurer.hasOwnProperty(votes[student].treasurer)) {
//       voteCount.treasurer[[votes[student].treasurer]] += 1;
//     }
//     else {
//       voteCount.treasurer[[votes[student].treasurer]] = 1;
//     };
//   }

// }

// function winner(object) {

//   for (var position in voteCount) {
//     var highest_vote = 0;
//     for (var name in voteCount[position]) {
//       if (voteCount[position][name] > highest_vote) {
//         var highest_vote = voteCount[position][name];
//         officers[position] = name;
//       }
//     }
//   };
// };

// DRIVER CODE
// pushVotes(votes)

// console.log(voteCount)

// console.log(winner(voteCount))

// console.log(officers);
// __________________________________________
// Refactored Solution

function pushVotes(object){
  for (var student in votes) {
    for (var position in votes[student]) {
    if (voteCount[position].hasOwnProperty(votes[student][position])){
        voteCount[position][votes[student][position]] += 1;
    }
    else {
      voteCount[position][votes[student][position]] = 1;
    }
  };
}

}

function winner(object) {

  for (var position in voteCount) {
    var highest_vote = 0;
    for (var name in voteCount[position]) {
      if (voteCount[position][name] > highest_vote) {
        var highest_vote = voteCount[position][name];
        officers[position] = name;
      }
    }
  };
};

pushVotes(votes)

console.log(voteCount)

console.log(winner(voteCount))

console.log(officers);

// __________________________________________
// Reflection

// What did you learn about iterating over nested objects in JavaScript?
// We learned that while iterating over an object, you can further iterate to reach the deeper objects/properties that you want to manipulate, and then act depending on what you find in those deeper levels.
// Were you able to find useful methods to help you with this?
// We used .hasOwnProperty() to see if an object already has the property that we are trying to manipulate.  If it did not then we set that property equal to something.  Also, I learned that in Coderpad you can select something you wish to change and press cmnd + d to find the next instance of that text.  One all selected, you can modify all of them at once.
// What concepts were solidified in the process of working through this challenge?
// Iterating over nested arrays was definitely solidified in the challenge, as well as using the "addresses" of values of properties.  We had to double check a lot of the "addresses" that we were using, to see if we were grabbing the correct values.

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)


text:
package io.datakernel.di.module;

import io.datakernel.di.annotation.QualifierAnnotation;

import java.lang.annotation.Target;

@QualifierAnnotation
@Target({}) // no target since this is a dummy annotation type
public @interface UniqueQualifier {
}


text:
require_relative "../../../test_helper"

class ContentTagsHelperTest < ActiveSupport::TestCase

  def test_init
    tag = ComfortableMexicanSofa::Content::Tag::Helper.new(context: @page, params: ["helper_method"])
    assert_equal "helper_method", tag.method_name
    assert_equal [], tag.params
  end

  def test_init_with_params
    tag = ComfortableMexicanSofa::Content::Tag::Helper.new(
      context: @page,
      params: ["helper_method", "param", { "key" => "val" }]
    )
    assert_equal "helper_method", tag.method_name
    assert_equal ["param", { "key" => "val" }], tag.params
  end

  def test_init_without_method_name
    message = "Missing method name for helper tag"
    assert_exception_raised ComfortableMexicanSofa::Content::Tag::Error, message do
      ComfortableMexicanSofa::Content::Tag::Helper.new(context: @page)
    end
  end

  def test_content
    tag = ComfortableMexicanSofa::Content::Tag::Helper.new(
      context: @page,
      params: ["method_name", "param", { "key" => "val" }]
    )
    assert_equal "<%= method_name(\"param\",{\"key\"=>\"val\"}) %>", tag.content
  end

  def test_render
    tag = ComfortableMexicanSofa::Content::Tag::Helper.new(
      context: @page,
      params: ["method_name", "param", { "key" => "val" }]
    )
    assert_equal "<%= method_name(\"param\",{\"key\"=>\"val\"}) %>", tag.render
  end

  def test_render_with_whitelist
    ComfortableMexicanSofa.config.allowed_helpers = %i[tester eval]
    tag = ComfortableMexicanSofa::Content::Tag::Helper.new(context: @page, params: ["tester"])
    assert_equal "<%= tester() %>", tag.render

    tag = ComfortableMexicanSofa::Content::Tag::Helper.new(context: @page, params: ["eval"])
    assert_equal "<%= eval() %>", tag.render

    tag = ComfortableMexicanSofa::Content::Tag::Helper.new(context: @page, params: ["not_whitelisted"])
    assert_nil tag.render
  end

  def test_render_with_blacklist
    ComfortableMexicanSofa::Content::Tag::Helper::BLACKLIST.each do |method|
      tag = ComfortableMexicanSofa::Content::Tag::Helper.new(context: @page, params: [method])
      assert_nil tag.render
    end
  end

  def test_render_with_erb_injection
    tag = ComfortableMexicanSofa::Content::Tag::Helper.new(
      context: @page,
      params: ["foo\#{:bar}", "foo\#{Kernel.exec('poweroff')"]
    )
    assert_equal "<%= foo\#{:bar}(\"foo\\\#{Kernel.exec('poweroff')\") %>", tag.render
  end

end


text:
import httplib
import logging
import mimetypes
import os
import re
import sys

import webob

mimetypes.add_type('image/vnd.microsoft.icon', 'ico')

LOG = logging.getLogger('routinglib')
LOG.setLevel(logging.INFO)

VAR_RE = re.compile(r'\${([^}]+)}')

def _re(o, flags, full):
    if isinstance(o, (tuple, list)):
        o = '|'.join(o)
    if full:
        o += '$'
    return re.compile(o, flags)

def _req(env):
    req = env.get('routinglib.Request')
    if not req:
        env['routinglib.Request'] = req = webob.Request(env)
    return req

def _make_expander(s):
    bits = VAR_RE.split(s)
    if len(bits) == 1:
        return lambda env: s
    expr_bits = []
    while bits:
        expr_bits.append(repr(bits.pop()))
        expr_bits.append('str(%s)' % bits.pop())
        expr_bits.append(repr(bits.pop()))
    cod = compile('+'.join(reversed(expr_bits)), '', 'eval')
    def expand(env):
        env2 = env.copy()
        env2['req'] = _req(env)
        return eval(cod, env2)
    return expand

def _log(_name, fn, *args, **kwargs):
    if LOG.level > logging.DEBUG:
        return fn
    args = filter(None, [
        ', '.join(repr(a) for a in args),
        ', '.join('%s=%r' % p for p in kwargs.iteritems()) ])
    frame = sys._getframe(2) # inspect is noticeably slow.
    msg = '%s:%d: %s(%s)' % (os.path.basename(frame.f_code.co_filename),
                             frame.f_lineno, _name, ', '.join(args))
    def logger(*args):
        result = fn(*args)
        LOG.info('%s -> %r', msg, result)
        return result
    return logger

# Predicates.
def host(pat, flags=0, full=True):
    match = _re(pat, flags, full).match
    return _log('host', lambda env: match(env.get('HTTP_HOST', '')),
                pat=pat, flags=flags, full=full)

def ssl(on):
    on = 'on' if on else 'off'
    return _log('ssl', lambda env: env.get('HTTPS') == on,
                on=on)

def path(pat, flags=0, full=True):
    match = _re(pat, flags, full).match
    return _log('path', lambda env: match(env.get('PATH_INFO', '')),
                pat=pat, flags=flags, full=full)

def getvar(name, pat='.*', flags=0, full=True):
    match = _re(pat, flags, full).match
    def pred(env):
        value = _req(env).GET.get(name)
        return value is not None and match(value)
    return _log('getvar', pred, name=name, pat=pat, flags=flags, full=full)

def postvar(name, pat, flags=0, full=True):
    match = _re(pat, flags, full).match
    return _log('postvar',
                lambda env: match(_req(env).POST.get(name, '')),
                name=name, pat=pat, flags=flags, full=full)

def method(pat, flags=0, full=True):
    match = _re(pat, flags, full).match
    return _log('method',
                lambda env: match(env.get('REQUEST_METHOD', '')),
                pat=pat, flags=flags, full=full)

def url(pat, flags=0, full=True):
    match = _re(pat, flags, full).match
    return _log('url', lambda env: match(_req(env).path_url),
                pat=pat, flags=flags, full=full)

def urlqs(pat, flags=0, full=True):
    match = _re(pat, flags, full).match
    return _log('urlqs', lambda env: match(_req(env).url),
                pat=pat, flags=flags, full=full)

def admin():
    return _log('admin', lambda env: env.get('USER_ID_ADMIN') == '1')

def allof(*preds):
    return _log('allof', lambda env: all(p(env) for p in preds))

def anyof(*preds):
    return _log('anyof', lambda env: any(p(env) for p in preds))

def invert(pred):
    return _log('invert', lambda env: not pred(env))

def always(boolean=True):
    return _log('always', lambda env: boolean, boolean=boolean)

# Helpers.
def ae_handler(klass, **extra):
    if extra:
        klass = type(klass.__name__ + 'Custom', (klass,), extra)
    return _log('ae_handler', webapp.WSGIApplication([('.*', klass)]),
                klass=klass, extra=extra)

def ae_ext_module(modpath, **extra):
    dirname, modname = os.path.split(modpath)
    modname = os.path.splitext(modname)[0]
    dirname = os.path.abspath(dirname)
    def app(env, start_response):
        sys_path = sys.path[:]
        sys.path.insert(0, dirname)
        try:
            return __import__(modname).main()
        finally:
            sys.path[:] = sys_path
    return _log('ae_ext_module', app, modpath=modpath, extra=extra)

def proxy(dest):
    from google.appengine.api import urlfetch
    def app(env, start_response):
        headers = _req(env).headers
        headers['X-Forwarded-For'] = env.get('REMOTE_ADDR')
        response = urlfetch.fetch(dest, headers=headers)
        code = response.status_code
        status = '%s %s' % (code, httplib.responses.get(code, code))
        start_response(status, response.headers.items())
        return response.content,
    return _log('proxy', app, dest=dest)

def redirect(dest, permanent=True):
    return respond(301 if permanent else 302, Location=dest)

def respond(code, entity=None, **headers):
    msg = '%s %s' % (code, httplib.responses.get(code, code))
    headers = [(k.replace('_', '-').title(), v) for (k, v) in headers.iteritems()]
    entity_ = entity

    if 'Content-Type' not in (h[0] for h in headers):
        headers.append(('Content-Type', 'text/html'))
        entity = '<h1>%s</h1>' % msg
    entity = () if entity is None else entity,

    def app(env, start_response):
        start_response(msg, headers)
        return entity
    return _log('status', app, code, entity=entity_, headers=headers)

def static(path, expires=60*60*24*7, ctype=None, **headers):
    expand = _make_expander(path)
    headers = headers.items()

    e404 = respond(404)

    import stat
    def app(env, start_response):
        path = expand(env)
        try:
            st = os.stat(path)
        except OSError:
            st = None
        if not (st and stat.S_ISREG(st.st_mode)):
            return e404(env, start_response)
        ctype_ = ctype or mimetypes.guess_type(path)[0]
        resp = webob.Response(body=file(path).read(),
                              last_modified=st.st_mtime,
                              content_type=ctype_,
                              headerlist=headers,
                              conditional_response=True)
        resp.cache_expires(expires)
        return resp(env, start_response)
    return app

def ae_main(app):
    from google.appengine.ext.webapp import util
    import __main__ as mod
    # "if caller is main"
    if sys._getframe(1).f_code.co_filename == mod.__file__:
        mod.main = lambda: util.run_wsgi_app(app)
        mod.main()

# Modifiers.
def rebase(pat, repl='', flags=0, prefix=True, full=False):
    if isinstance(pat, (tuple, list)):
        pat = '|'.join(pat)
    if prefix:
        pat = '^(?:%s)' % pat
    sub = _re(pat, flags, full).sub

    def rebaser(env):
        env['PATH_INFO'] = sub(repl, env.get('PATH_INFO', ''))
    return _log('rebase', rebaser,
                pat=pat, repl=repl, flags=flags, prefix=prefix, full=full)

# Router.
def chain(*pairs):
    def app(env, start_response):
        for p in pairs:
            if type(p) is tuple:
                if p[0](env): # pred,app pair
                    return p[1](env, start_response)
            else: # modifier
                p(env)
    return _log('chain', app)

API = dict((fn.__name__, fn) for fn in (
    host, ssl, path, getvar, postvar, method, admin, allof, anyof, invert,
    ae_handler, ae_ext_module, proxy, respond, static, redirect, ae_main,
    rebase, chain, always, url, urlqs
))

def install(dct, debug=False):
    dct.update(API)
    if debug:
        LOG.setLevel(logging.DEBUG)


text:
package org.clafer.test;

import org.chocosolver.solver.Model;
import org.chocosolver.solver.variables.IntVar;
import org.clafer.ir.IrIntExpr;
import org.clafer.ir.IrIntVar;
import org.clafer.ir.compiler.IrSolutionMap;
import static org.clafer.test.TestUtil.toVar;

/**
 *
 * @author jimmy
 */
public class IntTerm implements Term {

    private final IrIntVar var;

    IntTerm(IrIntVar var) {
        this.var = var;
    }

    @Override
    public IrIntExpr toIrExpr() {
        return var;
    }

    @Override
    public IrIntVar getIrVar() {
        return var;
    }

    @Override
    public IntVar toChocoVar(Model model) {
        return toVar(var, model);
    }

    @Override
    public int getValue(IrSolutionMap map) {
        return map.getValue(var);
    }

    @Override
    public String toString() {
        return var.toString();
    }
}


text:
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Autosuggest from 'react-autosuggest';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import TagContainer from '../Tag/TagContainer';
import { generateTagList, getSuggestionValue, renderSuggestion } from '../../helpers/TagAutosuggestHelper';
import s from './TagFilterForm.scss';

// eslint-disable-next-line css-modules/no-unused-class
import autosuggestTheme from './TagFilterFormAutosuggest.scss';

// eslint-disable-next-line css-modules/no-undef-class
autosuggestTheme.input = 'form-control';

const returnTrue = () => true;

class TagFilterForm extends Component {
  static propTypes = {
    exclude: PropTypes.bool,
    addByName: PropTypes.func.isRequired,
    addTag: PropTypes.func.isRequired,
    allTags: PropTypes.array.isRequired,
    clearTags: PropTypes.func.isRequired,
    removeTag: PropTypes.func.isRequired,
    restaurantIds: PropTypes.array.isRequired,
    addedTags: PropTypes.array.isRequired,
    setFlipMove: PropTypes.func.isRequired,
  };

  static defaultProps = {
    exclude: false
  };

  constructor(props) {
    super(props);

    this.state = {
      autosuggestValue: '',
    };

    this.state.shown = !!props.addedTags.length;
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.shown !== prevState.shown && this.state.shown) {
      this.autosuggest.input.focus();
    }
    this.props.setFlipMove(true);
  }

  setAutosuggestValue = (event, { newValue, method }) => {
    if (method === 'up' || method === 'down') {
      return;
    }
    this.setState(() => ({
      autosuggestValue: newValue
    }));
  };

  handleSuggestionSelected = (event, { suggestion, method }) => {
    if (method === 'enter') {
      event.preventDefault();
    }
    this.props.setFlipMove(false);
    this.props.addTag(suggestion.id);
    this.setState(() => ({
      autosuggestValue: '',
    }));
  }

  hideForm = () => {
    this.props.clearTags();
    this.props.setFlipMove(false);
    this.setState(() => ({
      autosuggestValue: '',
      shown: false,
    }));
  }

  showForm = () => {
    this.setState(() => ({
      shown: true,
    }));
  }

  removeTagFilter = (tag) => {
    this.props.removeTag(tag);
    this.props.setFlipMove(false);
  }

  render() {
    const {
      addByName,
      addedTags,
      allTags,
      exclude,
      restaurantIds,
    } = this.props;

    const { autosuggestValue, shown } = this.state;

    let form;
    let showButton;

    if (!allTags.length || !restaurantIds.length) {
      return null;
    }

    if (shown) {
      const tags = generateTagList(allTags, addedTags, autosuggestValue);

      form = (
        <form className={s.form} onSubmit={addByName}>
          <Autosuggest
            suggestions={tags}
            focusInputOnSuggestionClick={false}
            getSuggestionValue={getSuggestionValue}
            renderSuggestion={renderSuggestion}
            inputProps={{
              placeholder: exclude ? 'exclude' : 'filter',
              value: autosuggestValue,
              onChange: this.setAutosuggestValue,
            }}
            theme={autosuggestTheme}
            onSuggestionSelected={this.handleSuggestionSelected}
            onSuggestionsFetchRequested={() => {}}
            onSuggestionsClearRequested={() => {}}
            shouldRenderSuggestions={returnTrue}
            ref={a => { this.autosuggest = a; }}
          />
          {addedTags.map(tag => (
            <div
              className={s.tagContainer}
              key={exclude ? `tagExclusion_${tag}` : `tagFilter_${tag}`}
            >
              <TagContainer
                id={tag}
                showDelete
                onDeleteClicked={() => this.removeTagFilter(tag)}
                exclude={exclude}
              />
            </div>
          ))}
          <button
            className="btn btn-default"
            type="button"
            onClick={this.hideForm}
          >
            cancel
          </button>
        </form>
      );
    } else {
      showButton = (
        <button className="btn btn-default" onClick={this.showForm} type="button">
          {exclude ? 'exclude tags' : 'filter by tag'}
        </button>
      );
    }
    return (
      <div className={s.root}>
        {showButton}
        {form}
      </div>
    );
  }
}

export const undecorated = TagFilterForm;
export default withStyles(s)(withStyles(autosuggestTheme)(TagFilterForm));


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RESTGrid.Interfaces;
using RESTGrid.Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace RESTGrid.Tasks
{
    internal static class Transformer
    {
        public static List<QueueMetadata> RunTask(QueueMetadata metadata, JObject taskProperties, string identifier, IOrchestration orchestration)
        {
            List<QueueMetadata> result = null;
            try
            {
                if (taskProperties== null)
                    throw new Exception("TaskProperties for Transformer cannot be NULL");

                TransformerConfiguration taskConfig = taskProperties.ToObject<TransformerConfiguration>();
                JObject transformerJson = orchestration.GetTransformer(taskConfig.TransformerID);

                QueueMetadata transformedMetadata = new QueueMetadata()
                {
                    CustomPropertiesJson = metadata.CustomPropertiesJson,
                    ID = Guid.NewGuid(),
                    MessageBodyJson = metadata.MessageBodyJson,
                    Retries = metadata.Retries,
                    SplitID = metadata.SplitID,
                    StepIdentifier = identifier,
                    Success = true,
                    Timestamp = DateTime.UtcNow
                };

                transformedMetadata.MessageBodyJson = JUST.JsonTransformer.Transform(transformerJson, metadata.MessageBodyJson);
                result = new List<QueueMetadata>();
                result.Add(transformedMetadata);

            }
            catch (Exception ex)
            {
                result = new List<QueueMetadata>();
                QueueMetadata errorMetaData = new QueueMetadata()
                {
                    CustomPropertiesJson = metadata.CustomPropertiesJson,
                    ID = Guid.NewGuid(),
                    MessageBodyJson = metadata.MessageBodyJson,
                    Retries = metadata.Retries,
                    SplitID = metadata.SplitID,
                    StepIdentifier = identifier,
                    Success = false,
                    Timestamp = DateTime.UtcNow

                };

                Dictionary<string, string> customPropertiesSerialized = errorMetaData.CustomPropertiesJson.ToObject<Dictionary<string, string>>();
                if (customPropertiesSerialized.ContainsKey("Error"))
                    customPropertiesSerialized.Remove("Error");

                customPropertiesSerialized.Add("Error", ex.Message);

                errorMetaData.CustomPropertiesJson = JObject.FromObject(customPropertiesSerialized);

                result.Add(errorMetaData);
            }

            return result;
        }
    }

    internal class TransformerConfiguration
    {
        public int TransformerID { get; set; }
    }
}


text:
package com.rajendarreddyj.algorithms.sort;

/**
 * Quicksort is a sorting algorithm which, on average, makes O(n*log n) comparisons to sort n items. In the worst case,
 * it makes O(n^2) comparisons, though this behavior is rare. Quicksort is often faster in practice than other
 * algorithms.
 *
 * Average case = O(n*log n), Worst case = O(n^2), Best case = O(n) [three-way partition and equal keys]
 *
 * http://en.wikipedia.org/wiki/Quick_sort
 *
 * @author rajendarreddy.jagapathi <rajendarreddyj@gmail.com>
 *
 */
public class QuickSort {
    /**
     * public method exposed to client, sorts given array using QuickSort Algorithm in Java
     *
     * @param array
     */
    public static int[] quickSort(final int[] array) {
        if (array == null) {
            throw new NullPointerException("array cannot be null");
        }
        if (array.length == 0) {
            return array;
        }
        // pre: array is full, all elements are non-null integers
        // quicksort all the elements in the array
        recursiveQuickSort(array, 0, array.length - 1);
        // post: the array is sorted in ascending order
        return array;
    }

    /**
     * Recursive quicksort logic
     *
     * @param array
     *            An array of integers that is to be sorted.
     * @param lowerBound
     *            The lower index of the region of the array that is to be sorted.
     * @param upperBound
     *            The upper index of the region of the array that is to be sorted.
     */
    private static void recursiveQuickSort(final int[] array, final int lowerIndex, final int upperIndex) {

        // check that there are at least two elements to sort
        if ((upperIndex - lowerIndex) >= 1) {
            int idx = partition(array, lowerIndex, upperIndex);

            // Recursively call quicksort with left part of the partitioned array
            if (lowerIndex < (idx - 1)) {
                recursiveQuickSort(array, lowerIndex, idx - 1);
            }

            // Recursively call quick sort with right part of the partitioned array
            if (upperIndex > idx) {
                recursiveQuickSort(array, idx, upperIndex);
            }
        } else {
            // if there is only one element in the partition, do not do any sorting
            return;
        }
        // the array is sorted, so exit
    }

    /**
     * Divides array from pivot, left side contains elements less than Pivot while right side contains elements greater
     * than pivot.
     *
     * @param array
     *            array to partitioned
     * @param lowerIndex
     *            lower bound of the array
     * @param upperIndex
     *            upper bound of the array
     * @return the partition index
     */
    private static int partition(final int[] array, final int lowerIndex, final int upperIndex) {
        int left = lowerIndex;
        int right = upperIndex;
        // set a pivot, simply taking the middle value of the array
        int pivot = array[(left + right) / 2];

        // while the scan indices from left and right have not met,
        while (left <= right) {
            // searching number which is greater than pivot, bottom up
            // check if array value at left is less than our pivot
            while (array[left] < pivot) {
                // if it is less-than pivot, the value array[left] is in correct place
                // so we can increment i to go to next
                left++;
            }
            // searching number which is less than pivot, top down
            // now do exactly same thing for right Index, however, right Index starts at array.length, so decrement
            while (array[right] > pivot) {
                right--;
            }
            // if the left seekindex is still smaller than the right index, swap the corresponding elements
            if (left <= right) {
                swap(array, left, right);
                // increment left index and decrement right index
                left++;
                right--;
            }
        }
        return left;
    }

    /**
     * @param array
     * @param index1
     * @param index2
     */
    private static void swap(final int[] array, final int index1, final int index2) {
        if (index1 != index2) {
            // pre: array is full and index1, index2 < array.length
            // store the first value in a temp
            int temp = array[index1];
            // copy the value of the second into the first
            array[index1] = array[index2];
            // copy the value of the temp into the second
            array[index2] = temp;
            // post: the values at indices 1 and 2 have been swapped
        }
    }
}


text:
package com.github.agourlay.cornichon.http

import com.github.agourlay.cornichon.core.Step
import com.github.agourlay.cornichon.dsl.BodyElementCollector
import com.github.agourlay.cornichon.http.server.HttpMockServerResource
import com.github.agourlay.cornichon.http.steps.HttpListenSteps.HttpListenStepBuilder
import com.github.agourlay.cornichon.steps.wrapped.WithBlockScopedResource

trait HttpMockDsl {

  def httpListen(label: String) = HttpListenStepBuilder(label)

  def HttpListenTo(interface: Option[String], portRange: Option[Range], maxPortBindingRetries: Int = 5)(label: String): BodyElementCollector[Step, Step] =
    BodyElementCollector[Step, Step] { steps =>
      WithBlockScopedResource(nested = steps, resource = HttpMockServerResource(interface, label, portRange, maxPortBindingRetries))
    }

}


text:
'use strict';

angular.module('marketplace.register', [])

.controller('RegisterCtrl', ['$scope', 'user', 'app', 'util', function ($scope, user, app, util) {
    // Alert array
    $scope.alerts = [];
    $scope.submitting = false;
    $scope.emailRegex = app.EMAIL_REGEX;

    // Close alert
    $scope.closeAlert = function (index) {
        $scope.alerts.splice(index, 1);
    };

    // Handle submit action
    $scope.submit = function () {

        // Prevent submit multiple time
        if ($scope.submitting)
            return;

        if ($scope.email === undefined || $scope.password === undefined) {

            $scope.alerts = [{
                    type: 'danger',
                    msg: "Invalid ID or password"
                }];

            return;
        }

        $scope.submitting = true;

        // Do login
        user.register({

            email: $scope.email,
            passwordHash: $scope.password,
            lastName: $scope.lastName,
            firstName: $scope.firstName

        }, function (err) {

            // Handle error
            $scope.submitting = false;

            $scope.alerts = [{
                    type: 'danger',
                    msg: "Invalid ID or password"
                }];

        });
    };

    $scope.open = function() {
        util.openModal();
    };

    $scope.checkPasswordMatch = function() {
        return $scope.password === $scope.retypePassword;
    };

}]);


text:
<?php

namespace common\models;

use common\models\query\ShopProductQuery;
use trntv\filekit\behaviors\UploadBehavior;
use Yii;
use yii\behaviors\SluggableBehavior;
use yii\behaviors\TimestampBehavior;
use yz\shoppingcart\CartPositionTrait;

/**
 * This is the model class for table "{{%shop_product}}".
 *
 * @property integer $id
 * @property string $title
 * @property string $slug
 * @property string $description
 * @property integer $category_id
 * @property string $price
 * @property integer $jifen
 * @property string $content
 * @property string $keywords
 * @property string $thumbnail_base_url
 * @property string $thumbnail_path
 * @property string $img_base_url
 * @property string $img_path
 * @property integer $product_number
 * @property integer $return_jifen
 * @property integer $is_on_sale
 * @property integer $is_delete
 * @property integer $is_hot
 * @property integer $is_promote
 * @property integer $is_check
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $status
 *
 * @property ShopImage[] $shopImages
 * @property ShopOrderItem[] $shopOrderItems
 * @property ShopCategory $category
 *
 * @property ShopCategory $relation_game
 */
class ShopProduct extends \yii\db\ActiveRecord
{

	use CartPositionTrait;

	//该常亮表示该条数据是否可用
	const STATUS_IN_USE = 1;//使用中
	const STATUS_NOT_USED = 0;//停止使用

	const IS_ON_SALE_UP = 1;//上架
	const IS_ON_SALE_DOWN = 0;//下架

	const IS_DELETE_YES = 1;//删除
	const IS_DELETE_NO = 0;//未删除

	const IS_HOT_YES = 1;//是 热销产品
	const IS_HOT_NO = 0;//不是热销产品

	const IS_PROMOTE_YES = 1;//是促销
	const IS_PROMOTE_NO = 0;//不是促销产品

	const IS_CHECK_YES = 1;
	const IS_CHECK_NO = 0;

	public $thumbnail;
	public $img;

	public function behaviors()
	{
		return [
			[
				'class' => SluggableBehavior::className(),
				'attribute' => 'title',
			],
			[
				'class' => TimestampBehavior::className(),
			],
			[
				'class' => UploadBehavior::className(),
				'attribute' => 'thumbnail',
				'pathAttribute' => 'thumbnail_path',
				'baseUrlAttribute' => 'thumbnail_base_url'
			],
			[
				'class' => UploadBehavior::className(),
				'attribute' => 'img',
				'pathAttribute' => 'img_path',
				'baseUrlAttribute' => 'img_base_url'
			]
		];
	}

	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return '{{%shop_product}}';
	}

	/**
	 * @return ShopProductQuery
	 */
	public static function find()
	{
		return new ShopProductQuery(get_called_class());
	}

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['title', 'category_id', 'status'], 'required'],
			[['description', 'content'], 'string'],
			[['category_id', 'jifen', 'product_number', 'return_jifen', 'is_on_sale', 'is_delete', 'is_hot', 'is_promote', 'is_check', 'created_at', 'updated_at', 'status', 'relation_game'], 'integer'],
			[['price'], 'number'],
			[['title', 'slug', 'keywords'], 'string', 'max' => 255],
			[['thumbnail_base_url', 'thumbnail_path', 'img_base_url', 'img_path'], 'string', 'max' => 1024],
			[['thumbnail', 'img'], 'safe']
		];
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'id' => Yii::t('common', 'ID'),
			'title' => Yii::t('common', 'Title'),
			'slug' => Yii::t('common', 'Slug'),
			'description' => Yii::t('common', 'Description'),
			'category_id' => Yii::t('common', 'Category ID'),
			'price' => Yii::t('common', 'Price'),
			'jifen' => Yii::t('common', 'Jifen'),
			'content' => Yii::t('common', 'Content'),
			'keywords' => Yii::t('common', 'Keywords'),
			'thumbnail' => Yii::t('common', 'Thumbnail'),
			'img' => '大图(1170x300)',
			'thumbnail_base_url' => Yii::t('common', 'Thumbnail Base Url'),
			'thumbnail_path' => Yii::t('common', 'Thumbnail Path'),
			'img_base_url' => Yii::t('common', 'Img Base Url'),
			'img_path' => Yii::t('common', 'Img Path'),
			'product_number' => Yii::t('common', 'Product Number'),
			'return_jifen' => Yii::t('common', 'Return Jifen'),
			'is_on_sale' => Yii::t('common', 'Is On Sale'),
			'is_delete' => Yii::t('common', 'Is Delete'),
			'is_hot' => Yii::t('common', 'Is Hot'),
			'is_promote' => Yii::t('common', 'Is Promote'),
			'is_check' => Yii::t('common', 'Is Check'),
			'created_at' => Yii::t('common', 'Created At'),
			'updated_at' => Yii::t('common', 'Updated At'),
			'status' => Yii::t('common', 'Status'),
			'relation_game' => Yii::t('common', 'Relation Game'),
		];
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getShopImages()
	{
		return $this->hasMany(ShopImage::className(), ['product_id' => 'id']);
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getShopOrderItems()
	{
		return $this->hasMany(ShopOrderItem::className(), ['product_id' => 'id']);
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getCategory()
	{
		return $this->hasOne(ShopCategory::className(), ['id' => 'category_id']);
	}

	public function getPrice()
	{
		return $this->price;
	}

	public function getJiFen()
	{
		return $this->jifen;
	}

	public function getId()
	{
		return $this->id;
	}

	/**
	 * @return array
	 */
	public static function getStatus()
	{
		return [
			self::STATUS_NOT_USED => Yii::t('common', 'Not Used'),
			self::STATUS_IN_USE => Yii::t('common', 'In Use'),
		];
	}

	public function getRelationGame()
	{
		return $this->hasOne(Game::className(), ['id' => 'relation_game']);
	}
}


text:
namespace Task1.ClassChef.Contracts
{
    public interface IOven
    {
        IMeal Cook(IBowl bowl);
    }
}


text:
package com.ibm.uk.hursley.perfharness.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * A basic JDK log formatter which prepends messages with a given string.
 *
 */
public class PrependFormatter extends Formatter {

	private final static String ls = System.getProperty("line.separator");
	private String header = null;

	public PrependFormatter( String header ) {
		this.header = header;
	}

	public String format(LogRecord record) {

		String message = formatMessage(record);
		StringBuffer sb = new StringBuffer(message.length() + header.length());
		sb.append(header).append(message).append(ls);

		// Print exception using JVMs default renderer.
		Throwable t = record.getThrown();
		if (t != null) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			t.printStackTrace(pw);
			pw.close();
			sb.append(sw.toString());
		}

		return sb.toString();
	}
}


text:
layout: post
title: Working with FILETIME in Ruby
---

Recently I have had to deal with the windows FILETIME struct in ruby.

MSDN defines this guy as "a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC)."

Well, the easy thing to do is add a method to the Time class that can convert to the format:

    class Time
      # Convert the time to the FILETIME format, a 64-bit value representing the
      # number of 100-nanosecond intervals since January 1, 1601 (UTC).
      def wtime
        self.to_i * 10000000 + 116444736000000000
      end

      # Create a time object from the FILETIME format, a 64-bit value representing
      # the number of 100-nanosecond intervals since January 1, 1601 (UTC).
      def self.from_wtime(wtime)
        Time.at((wtime - 116444736000000000) / 10000000)
      end
    end

Now I can do fancy things like:

    some_bindata_struct.time = Time.now.wtime


text:
<!doctype html>
<html>
  <head>
    <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
    <script>
      /*
      window.Polymer = window.Polymer || {};
      window.Polymer.dom = 'shadow';
      */
    </script>
    <link rel="import" href="icon-toggle-demo.html">
  </head>
  <body>
    <icon-toggle-demo></icon-toggle-demo>
  </body>
</html>


text:
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockFailure.h"
#include "CppUTestExt/MockExpectedCall.h"
#include "CppUTestExt/MockExpectedCallsList.h"
#include "CppUTestExt/MockNamedValue.h"

class MockFailureReporterTestTerminator : public TestTerminator
{
public:
    MockFailureReporterTestTerminator(bool crashOnFailure) : crashOnFailure_(crashOnFailure)
    {
    }

    virtual void exitCurrentTest() const _override
    {
        if (crashOnFailure_)
            UT_CRASH();

        UtestShell::getCurrentTestTerminator().exitCurrentTest();
    } // LCOV_EXCL_LINE

    virtual ~MockFailureReporterTestTerminator() _destructor_override
    {
    }
private:
    bool crashOnFailure_;

};

void MockFailureReporter::failTest(const MockFailure& failure)
{
    if (!getTestToFail()->hasFailed())
        getTestToFail()->failWith(failure, MockFailureReporterTestTerminator(crashOnFailure_));
} // LCOV_EXCL_LINE

UtestShell* MockFailureReporter::getTestToFail()
{
    return UtestShell::getCurrent();
}

MockFailure::MockFailure(UtestShell* test) : TestFailure(test, "Test failed with MockFailure without an error! Something went seriously wrong.")
{
}

void MockFailure::addExpectationsAndCallHistory(const MockExpectedCallsList& expectations)
{
    message_ += "\tEXPECTED calls that WERE NOT fulfilled:\n";
    message_ += expectations.unfulfilledCallsToString("\t\t");
    message_ += "\n\tEXPECTED calls that WERE fulfilled:\n";
    message_ += expectations.fulfilledCallsToString("\t\t");
}

void MockFailure::addExpectationsAndCallHistoryRelatedTo(const SimpleString& name, const MockExpectedCallsList& expectations)
{
    MockExpectedCallsList expectationsForFunction;
    expectationsForFunction.addExpectationsRelatedTo(name, expectations);

    message_ += "\tEXPECTED calls that WERE NOT fulfilled related to function: ";
    message_ += name;
    message_ += "\n";

    message_ += expectationsForFunction.unfulfilledCallsToString("\t\t");

    message_ += "\n\tEXPECTED calls that WERE fulfilled related to function: ";
    message_ += name;
    message_ += "\n";

    message_ += expectationsForFunction.fulfilledCallsToString("\t\t");
}

MockExpectedCallsDidntHappenFailure::MockExpectedCallsDidntHappenFailure(UtestShell* test, const MockExpectedCallsList& expectations) : MockFailure(test)
{
    message_ = "Mock Failure: Expected call WAS NOT fulfilled.\n";
    addExpectationsAndCallHistory(expectations);
}

MockUnexpectedCallHappenedFailure::MockUnexpectedCallHappenedFailure(UtestShell* test, const SimpleString& name, const MockExpectedCallsList& expectations) : MockFailure(test)
{
    unsigned int amountOfActualCalls = expectations.amountOfActualCallsFulfilledFor(name);
    if (amountOfActualCalls > 0) {
        SimpleString ordinalNumber = StringFromOrdinalNumber(amountOfActualCalls + 1);
        message_ = StringFromFormat("Mock Failure: Unexpected additional (%s) call to function: ", ordinalNumber.asCharString());
    } else {
        message_ = "Mock Failure: Unexpected call to function: ";
    }
    message_ += name;
    message_ += "\n";
    addExpectationsAndCallHistory(expectations);
}

MockCallOrderFailure::MockCallOrderFailure(UtestShell* test, const MockExpectedCallsList& expectations) : MockFailure(test)
{
    MockExpectedCallsList expectationsForOutOfOrder;
    expectationsForOutOfOrder.addExpectations(expectations);
    expectationsForOutOfOrder.onlyKeepOutOfOrderExpectations();

    message_ = "Mock Failure: Out of order calls";
    message_ += "\n";
    addExpectationsAndCallHistory(expectationsForOutOfOrder);
}

MockUnexpectedInputParameterFailure::MockUnexpectedInputParameterFailure(UtestShell* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedCallsList& expectations)  : MockFailure(test)
{
    MockExpectedCallsList expectationsForFunctionWithParameterName;
    expectationsForFunctionWithParameterName.addExpectationsRelatedTo(functionName, expectations);
    expectationsForFunctionWithParameterName.onlyKeepExpectationsWithInputParameterName(parameter.getName());

    if (expectationsForFunctionWithParameterName.isEmpty()) {
        message_ = "Mock Failure: Unexpected parameter name to function \"";
        message_ += functionName;
        message_ += "\": ";
        message_ += parameter.getName();
    }
    else {
        message_ = "Mock Failure: Unexpected parameter value to parameter \"";
        message_ += parameter.getName();
        message_ += "\" to function \"";
        message_ += functionName;
        message_ += "\": <";
        message_ += StringFrom(parameter);
        message_ += ">";
    }

    message_ += "\n";
    addExpectationsAndCallHistoryRelatedTo(functionName, expectations);

    message_ += "\n\tACTUAL unexpected parameter passed to function: ";
    message_ += functionName;
    message_ += "\n";

    message_ += "\t\t";
    message_ += parameter.getType();
    message_ += " ";
    message_ += parameter.getName();
    message_ += ": <";
    message_ += StringFrom(parameter);
    message_ += ">";
}

MockUnexpectedOutputParameterFailure::MockUnexpectedOutputParameterFailure(UtestShell* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedCallsList& expectations)  : MockFailure(test)
{
    MockExpectedCallsList expectationsForFunctionWithParameterName;
    expectationsForFunctionWithParameterName.addExpectationsRelatedTo(functionName, expectations);
    expectationsForFunctionWithParameterName.onlyKeepExpectationsWithOutputParameterName(parameter.getName());

    if (expectationsForFunctionWithParameterName.isEmpty()) {
        message_ = "Mock Failure: Unexpected output parameter name to function \"";
        message_ += functionName;
        message_ += "\": ";
        message_ += parameter.getName();
    }
    else {
        message_ = "Mock Failure: Unexpected parameter type \"";
        message_ += parameter.getType();
        message_ += "\" to output parameter \"";
        message_ += parameter.getName();
        message_ += "\" to function \"";
        message_ += functionName;
        message_ += "\"";
    }

    message_ += "\n";
    addExpectationsAndCallHistoryRelatedTo(functionName, expectations);

    message_ += "\n\tACTUAL unexpected output parameter passed to function: ";
    message_ += functionName;
    message_ += "\n";

    message_ += "\t\t";
    message_ += parameter.getType();
    message_ += " ";
    message_ += parameter.getName();
}

MockExpectedParameterDidntHappenFailure::MockExpectedParameterDidntHappenFailure(UtestShell* test, const SimpleString& functionName,
                                                                                const MockExpectedCallsList& allExpectations,
                                                                                const MockExpectedCallsList& matchingExpectations) : MockFailure(test)
{
    message_ = "Mock Failure: Expected parameter for function \"";
    message_ += functionName;
    message_ += "\" did not happen.\n";

    message_ += "\tEXPECTED calls with MISSING parameters related to function: ";
    message_ += functionName;
    message_ += "\n";
    message_ += matchingExpectations.callsWithMissingParametersToString("\t\t", "\tMISSING parameters: ");
    message_ += "\n";

    addExpectationsAndCallHistoryRelatedTo(functionName, allExpectations);
}

MockNoWayToCompareCustomTypeFailure::MockNoWayToCompareCustomTypeFailure(UtestShell* test, const SimpleString& typeName) : MockFailure(test)
{
    message_ = StringFromFormat("MockFailure: No way to compare type <%s>. Please install a MockNamedValueComparator.", typeName.asCharString());
}

MockNoWayToCopyCustomTypeFailure::MockNoWayToCopyCustomTypeFailure(UtestShell* test, const SimpleString& typeName) : MockFailure(test)
{
    message_ = StringFromFormat("MockFailure: No way to copy type <%s>. Please install a MockNamedValueCopier.", typeName.asCharString());
}

MockUnexpectedObjectFailure::MockUnexpectedObjectFailure(UtestShell* test, const SimpleString& functionName, const void* actual, const MockExpectedCallsList& expectations) : MockFailure(test)
{
    message_ = StringFromFormat ("MockFailure: Function called on an unexpected object: %s\n"
                                 "\tActual object for call has address: <%p>\n", functionName.asCharString(),actual);
    addExpectationsAndCallHistoryRelatedTo(functionName, expectations);
}

MockExpectedObjectDidntHappenFailure::MockExpectedObjectDidntHappenFailure(UtestShell* test, const SimpleString& functionName, const MockExpectedCallsList& expectations) : MockFailure(test)
{
    message_ = StringFromFormat("Mock Failure: Expected call on object for function \"%s\" but it did not happen.\n", functionName.asCharString());
    addExpectationsAndCallHistoryRelatedTo(functionName, expectations);
}


text:
@implementation ExampleAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    UINavigationController *greenVC = (UINavigationController *)[mainStoryBoard instantiateViewControllerWithIdentifier:@"greenVC"];
    //this title will be used for the menu link
    [greenVC setTitle:@"Green Link"];

    UINavigationController *blueVC = (UINavigationController *)[mainStoryBoard instantiateViewControllerWithIdentifier:@"blueVC"];
    //this title will be used for the menu link
    [blueVC setTitle:@"Blue Link"];

    UINavigationController *tableVC = (UINavigationController *)[mainStoryBoard instantiateViewControllerWithIdentifier:@"tableVC"];
    //this title will be used for the menu link
    [tableVC setTitle:@"Table Link"];

    UINavigationController *mapVC = (UINavigationController *)[mainStoryBoard instantiateViewControllerWithIdentifier:@"mapVC"];
    //this title will be used for the menu link
    [mapVC setTitle:@"Map Link"];

    UINavigationController *settingsVC = (UINavigationController *)[mainStoryBoard instantiateViewControllerWithIdentifier:@"settingsVC"];
    //this title will be used for the menu link
    [settingsVC setTitle:@"Map Link"];

    CustomMenuViewController *customMVC = (CustomMenuViewController *)[mainStoryBoard instantiateViewControllerWithIdentifier:@"CustomMenuViewController"];

    //our slidable menu controller
    CustomSlidableViewController *slidableVC = [[CustomSlidableViewController alloc] initWithViewControllers:@[greenVC, blueVC, tableVC, mapVC, settingsVC] andMenuViewController:customMVC andMenuWidth:320];

    self.window.rootViewController = slidableVC;

    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
require 'helper'

describe Crunchbase do
  it 'should have a version number' do
    Crunchbase::VERSION.wont_be_nil
  end
end


text: RpgCord est un projet en java qui nous permettre de valorisé un sprint en eduscrum.


text:
import io
import math
import os
import re
import shlex
import subprocess
from collections import deque
from threading import Thread

import eventlet
from eventlet.green.subprocess import Popen

from app import db, config, app
from app.library.formatters import duration_to_seconds
from app.models.file import File
from app.modules.mod_process.process_repository import ProcessRepository

# we need to monkey patch the threading module, see http://eventlet.net/doc/patching.html
eventlet.monkey_patch(thread=True)

# the pattern to fetch meta information of the current progress
# to match a line like
# frame=44448 fps= 14 q=-0.0 Lsize=  247192kB time=00:30:53.95 bitrate=1092.3kbits/s speed=0.577x
PROGRESS_PATTERN = re.compile(r"frame=\s*(\d+) fps=\s*(.+) q=(.+) L?size=\s*(\d+)kB time=(.+) bitrate=\s*(.+)kbits/s(?:P speed=(.+)x)?")

class Process(Thread):
    def __init__(self, file):
        Thread.__init__(self)
        self.file = file
        self.active = True

    def run(self):
        """
        run the encoding
        """
        # probe file first
        frame_count = self.ffmpeg_probe_frame_count()

        if frame_count == -1:
            app.logger.debug("Probing of " + self.file.filename + " failed - aborting...")
            ProcessRepository.file_failed(self.file)
            return

        # app.logger.debug("Probing of " + file.filename + " successful.. frame count: " + str(frame_count))
        split_path = os.path.split(self.file.filename)
        path = split_path[0]
        original_filename = split_path[1]
        filename_noext = os.path.split(os.path.splitext(original_filename)[0])[1]
        # form output filename and store it in self.file for later use
        self.file.output_filename = filename_noext + ".pyencode"

        cmd = ["ffmpeg"]
        cmd.extend(["-i", self.file.filename])
        # add parameters from config
        cmd.extend(shlex.split(config.get("encoding", "parameters")))
        cmd.extend(["-y", path + os.sep + self.file.output_filename])

        app.logger.debug("Starting encoding of " + self.file.filename + " with %s" % " ".join(cmd))

        for info in self.run_ffmpeg(cmd, frame_count):
            if info["return_code"] != -1:
                app.logger.debug("Error occured while running ffmpeg. Last lines of output: ")
                app.logger.debug("\n".join(info["last_lines"]))
                ProcessRepository.file_failed(self.file)
                return

            # store information in database
            # convert kB to bytes
            info["ffmpeg_size"] *= 1024

            # we don't need the return_code anymore (and don't want to store it)
            info.pop("return_code")

            # update file in DB
            File.query.filter_by(id=self.file.id).update(info)
            db.session.commit()

            # update self.file
            for k in info:
                setattr(self.file, k, info[k])

            # tell ProcessRepository there's some progress going on
            ProcessRepository.file_progress(self.file)

        if self.active:
            ProcessRepository.file_done(self.file)

    def ffmpeg_probe_frame_count(self):
        """
        probe self.file and return frame count
        """
        instance = Popen(["ffprobe", self.file.filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        output = ""
        for line in instance.stderr:
            output += line.decode("utf8")

            # call sleep, see https://stackoverflow.com/questions/34599578/using-popen-in-a-thread-blocks-every-incoming-flask-socketio-request
            eventlet.sleep()

        fps_reg = re.findall(r"([0-9]*\.?[0-9]+) fps|tbr", output)
        if fps_reg is None:
            return -1

        fps = float(" ".join(fps_reg))

        duration = duration_to_seconds(re.findall(r"Duration: (.*?),", output)[0])

        # calculate the amount of frames for the calculation of progress
        frame_count = int(math.ceil(duration * float(fps)))

        return frame_count

    def stop(self):
        """
        stop this process
        """
        self.active = False

    def run_ffmpeg(self, cmd, frame_count):
        """
        run ffmpeg with given cmd arguments and a frame count
        :param cmd: the command line dictionary containing all the arguments
        :param frame_count: the amount of frames of this video, necessary for the progress calculation
        :return:
        """
        instance = Popen(map(str, cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        reader = io.TextIOWrapper(instance.stderr, encoding="utf8")

        # these two variables are just needed for when the processing fails, see below
        last_lines = deque(maxlen=5)  # parameter determines how many lines to keep

        # oddly ffmpeg writes to stderr instead of stdout
        for line in reader:
            # kill ffmpeg when not being active anymore
            if not self.active:
                instance.kill()

            # call sleep, see https://stackoverflow.com/questions/34599578/using-popen-in-a-thread-blocks-every-incoming-flask-socketio-request
            eventlet.sleep()

            # append current line to last_lines
            last_lines.append(line)

            match = PROGRESS_PATTERN.match(line)

            # first few lines have no match
            if match:
                frame = int(match.group(1))  # current frame, needed for calculation of progress
                fps = float(match.group(2))  # needed for calculation of remaining time
                size = int(match.group(4))  # current size in kB
                time = duration_to_seconds(match.group(5))  # time already passed for converting, in seconds
                bitrate = float(match.group(6))  # in kbits/s
                progress = round((frame / float(frame_count)) * 100, 1)  # in %

                frames_remaining = frame_count - frame  # needed for eta
                eta = frames_remaining / fps if fps != 0 else -1  # in seconds

                yield {"return_code": -1, "ffmpeg_eta": eta, "ffmpeg_progress": progress, "ffmpeg_bitrate": bitrate,
                       "ffmpeg_time": time, "ffmpeg_size": size, "ffmpeg_fps": fps}

        return_code = instance.wait()
        if return_code != 0:
            yield {"return_code": return_code, "last_lines": last_lines}


text:
module.exports = BinaryReader;

function BinaryReader(buffer, isBigEndian) {
    this.buffer = buffer;
    this.position = 0;
    this.isBigEndian = isBigEndian || false;
}

function _read(readLE, readBE, size) {
    return function () {
        var value;

        if (this.isBigEndian)
            value = readBE.call(this.buffer, this.position);
        else
            value = readLE.call(this.buffer, this.position);

        this.position += size;

        return value;
    };
}

BinaryReader.prototype.readUInt8 = _read(Buffer.prototype.readUInt8, Buffer.prototype.readUInt8, 1);
BinaryReader.prototype.readUInt16 = _read(Buffer.prototype.readUInt16LE, Buffer.prototype.readUInt16BE, 2);
BinaryReader.prototype.readUInt32 = _read(Buffer.prototype.readUInt32LE, Buffer.prototype.readUInt32BE, 4);
BinaryReader.prototype.readInt8 = _read(Buffer.prototype.readInt8, Buffer.prototype.readInt8, 1);
BinaryReader.prototype.readInt16 = _read(Buffer.prototype.readInt16LE, Buffer.prototype.readInt16BE, 2);
BinaryReader.prototype.readInt32 = _read(Buffer.prototype.readInt32LE, Buffer.prototype.readInt32BE, 4);
BinaryReader.prototype.readFloat = _read(Buffer.prototype.readFloatLE, Buffer.prototype.readFloatBE, 4);
BinaryReader.prototype.readDouble = _read(Buffer.prototype.readDoubleLE, Buffer.prototype.readDoubleBE, 8);


text:
<?php

namespace Hydrogen\Http\Header;

class HttpHeader
{
    const HOST = 'Host';
    const CONNECTION = 'Connection';
    const CACHE_CTRL = 'Cache-Control';
    const ACCEPT = 'Accept';
    const UPGRADE_INSECURE_REQUESTS = 'Upgrade-Insecure-Requests';
    const USER_AGENT = 'User-Agent';
    const ACCEPT_ENCODING = 'Accept-Encoding';
    const ACCEPT_LANGUAGE = 'Accept-Language';
    const CONTENT_TYPE = 'Content-Type';
    const ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin';
    const ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials';
    const ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods';
    const ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers';

}


text:
namespace base {
template <typename T>
struct DefaultSingletonTraits;
}
class LastTabStandingTracker;

class LastTabStandingTrackerFactory : public BrowserContextKeyedServiceFactory {
 public:
  LastTabStandingTrackerFactory(const LastTabStandingTrackerFactory&) = delete;
  LastTabStandingTrackerFactory& operator=(
      const LastTabStandingTrackerFactory&) = delete;

  static LastTabStandingTracker* GetForBrowserContext(
      content::BrowserContext* context);
  static LastTabStandingTrackerFactory* GetInstance();

 protected:
  bool ServiceIsCreatedWithBrowserContext() const override;

 private:
  friend struct base::DefaultSingletonTraits<LastTabStandingTrackerFactory>;

  LastTabStandingTrackerFactory();
  ~LastTabStandingTrackerFactory() override;

  // BrowserContextKeyedServiceFactory:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
  content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const override;
};

#endif  // CHROME_BROWSER_PERMISSIONS_LAST_TAB_STANDING_TRACKER_FACTORY_H_


text:
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''

---

- which operating system are you using?
e.g. Windows 10, Ubuntu 18.4, etc.
- which environment is pyroSAR running in?
e.g. system-wide Python installation, Anaconda environment, virtual environment, etc.
- which version of pyroSAR are you using?
one installed via conda, pip or a clone of the GitHub repository?
-  which function of pyroSAR did you call with which parameters?
- if applicable, which version of SNAP or GAMMA are you using in pyroSAR?
- the full error message


text:
package com.encryptlang.lua.ast;

import com.encryptlang.lua.ast.expr.VarargExpr;

import java.util.List;

public class FuncBody {

    public List<String> params;

    public VarargExpr varargExpr;

    public Block block;

    public String toStringTree() {
        StringBuilder buf = new StringBuilder();
        for(int i=0; params != null && i<params.size();  i++){
            buf.append(" ");
            buf.append(params.get(i));
        }
        if(varargExpr != null){
            buf.append(" ");
            buf.append(varargExpr.toStringTree());
        }
        buf.append(" ");
        buf.append(block.toStringTree());
        return buf.toString();
    }

}