text:
// cudamatrix/cu-sp-matrix-test.cc
//
// Copyright 2013  Ehsan Variani
//                 Lucas Ondel

// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//  http://www.apache.org/licenses/LICENSE-2.0

// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
//
// UnitTests for testing cu-sp-matrix.h methods.
//

#include <iostream>
#include <vector>
#include <cstdlib>

#include "base/kaldi-common.h"
#include "cudamatrix/cu-device.h"
#include "cudamatrix/cu-tp-matrix.h"
#include "cudamatrix/cu-vector.h"
#include "cudamatrix/cu-math.h"
#include "cudamatrix/cu-sp-matrix.h"

using namespace kaldi;

namespace kaldi {

template <typename Real>
static void AssertEqual(const CuPackedMatrix<Real> &A,
                        const CuPackedMatrix<Real> &B, float tol = 0.001) {
  KALDI_ASSERT(A.NumRows() == B.NumRows());
  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
    for (MatrixIndexT j = 0; j <= i; j++)
      KALDI_ASSERT(
          std::abs(A(i, j) - B(i, j)) <
          tol * std::max(1.0, (double)(std::abs(A(i, j)) + std::abs(B(i, j)))));
}

template <typename Real>
static void AssertEqual(const PackedMatrix<Real> &A,
                        const PackedMatrix<Real> &B, float tol = 0.001) {
  KALDI_ASSERT(A.NumRows() == B.NumRows());
  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
    for (MatrixIndexT j = 0; j <= i; j++)
      KALDI_ASSERT(
          std::abs(A(i, j) - B(i, j)) <
          tol * std::max(1.0, (double)(std::abs(A(i, j)) + std::abs(B(i, j)))));
}

template <typename Real>
static void AssertEqual(const PackedMatrix<Real> &A,
                        const CuPackedMatrix<Real> &B, float tol = 0.001) {
  KALDI_ASSERT(A.NumRows() == B.NumRows());
  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
    for (MatrixIndexT j = 0; j <= i; j++)
      KALDI_ASSERT(
          std::abs(A(i, j) - B(i, j)) <
          tol * std::max(1.0, (double)(std::abs(A(i, j)) + std::abs(B(i, j)))));
}

/*
 * Unit Tests
 */
template <typename Real>
static void UnitTestCuTpMatrixInvert() {
  for (MatrixIndexT i = 1; i < 10; i++) {
    MatrixIndexT dim = 5 * i + Rand() % 10;

    TpMatrix<Real> A(dim);
    A.SetRandn();
    CuTpMatrix<Real> B(A);

    AssertEqual<Real>(A, B, 0.005);
    A.Invert();
    B.Invert();
    AssertEqual<Real>(A, B, 0.005);
  }
}

template <typename Real>
static void UnitTestCuTpMatrixCopyFromTp() {
  for (MatrixIndexT i = 1; i < 10; i++) {
    MatrixIndexT dim = 5 * i + Rand() % 10;

    TpMatrix<Real> A(dim);
    A.SetRandn();
    CuTpMatrix<Real> B(dim);
    B.CopyFromTp(A);
    CuTpMatrix<Real> C(dim);
    C.CopyFromTp(B);

    AssertEqual<Real>(A, B);
    AssertEqual<Real>(B, C);
  }
}

template <typename Real>
static void UnitTestCuTpMatrixCopyFromMat() {
  for (MatrixIndexT i = 1; i < 10; i++) {
    MatrixTransposeType trans = (i % 2 == 0 ? kNoTrans : kTrans);

    MatrixIndexT dim = 10 * i + Rand() % 5;
    CuMatrix<Real> A(dim, dim);
    A.SetRandn();
    Matrix<Real> A2(A);

    CuTpMatrix<Real> B(dim);
    B.CopyFromMat(A, trans);
    TpMatrix<Real> B2(dim);
    B2.CopyFromMat(A2, trans);
    TpMatrix<Real> B3(B);
    AssertEqual(B2, B3);
    KALDI_ASSERT(B3.Trace() != 0);
  }
}

template <typename Real>
static void UnitTestCuTpMatrixCholesky() {
  for (MatrixIndexT i = 1; i < 10; i++) {
    MatrixIndexT dim = 1 + Rand() % 10;
    if (i > 4) {
      dim += 32 * (Rand() % 5);
    }

    Matrix<Real> M(dim, dim + 2);
    M.SetRandn();
    SpMatrix<Real> A(dim);
    A.AddMat2(1.0, M, kNoTrans, 0.0);  // sets A to random almost-surely +ve
                                       // definite matrix.
    CuSpMatrix<Real> B(A);

    TpMatrix<Real> C(dim);
    C.SetRandn();
    CuTpMatrix<Real> D(C);
    C.Cholesky(A);
    D.Cholesky(B);

    AssertEqual<Real>(C, D);
  }
}

template <class Real>
static void UnitTestCuTpMatrixIO() {
  for (int32 i = 0; i < 3; i++) {
    int32 dimM = Rand() % 255 + 10;
    if (i % 5 == 0) {
      dimM = 0;
    }
    CuTpMatrix<Real> mat(dimM);
    mat.SetRandn();
    std::ostringstream os;
    bool binary = (i % 4 < 2);
    mat.Write(os, binary);

    CuTpMatrix<Real> mat2;
    std::istringstream is(os.str());
    mat2.Read(is, binary);
    AssertEqual(mat, mat2);
  }
}

template <typename Real>
void CudaTpMatrixUnitTest() {
  UnitTestCuTpMatrixIO<Real>();
  UnitTestCuTpMatrixInvert<Real>();
  UnitTestCuTpMatrixCopyFromTp<Real>();
  UnitTestCuTpMatrixCholesky<Real>();
  UnitTestCuTpMatrixCopyFromMat<Real>();
}

}  // namespace kaldi

int main() {
  using namespace kaldi;

  for (int32 loop = 0; loop < 2; loop++) {
#if HAVE_CUDA == 1
    if (loop == 0)
      CuDevice::Instantiate().SelectGpuId("no");  // -1 means no GPU
    else
      CuDevice::Instantiate().SelectGpuId("yes");  // -2 .. automatic selection
#endif
    kaldi::CudaTpMatrixUnitTest<float>();
#if HAVE_CUDA == 1
    if (CuDevice::Instantiate().DoublePrecisionSupported()) {
      kaldi::CudaTpMatrixUnitTest<double>();
    } else {
      KALDI_WARN << "Double precision not supported";
    }
#else
    kaldi::CudaTpMatrixUnitTest<double>();
#endif

    if (loop == 0)
      KALDI_LOG << "Tests without GPU use succeeded.";
    else
      KALDI_LOG << "Tests with GPU use (if available) succeeded.";
  }
#if HAVE_CUDA == 1
  CuDevice::Instantiate().PrintProfile();
#endif
  return 0;
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1"/>

  <title>Fargo</title>
  <meta name="author" content="" />
  <meta name="description"
        content="É muito simples entrar em uma comédia-thriller dos irmãos Coen. Há dois princípios extremamente eficazes em Fargo: os diálogos que expõem desde o início o caráter de seus caricatos personagens — como..."/>

  <meta name="yandex-verification" content="48a8210fc043c5e8" />

  <meta name="generator" content="Hugo 0.54.0" />

  <meta itemprop="name" content="Fargo"/>
  <meta itemprop="description"
        content="É muito simples entrar em uma comédia-thriller dos irmãos Coen. Há dois princípios extremamente eficazes em Fargo: os diálogos que expõem desde o início o caráter de seus caricatos personagens — como..."/>
  <meta itemprop="image"
        content="/img/logo.svg"/>

  <meta property="og:title" content="Fargo"/>
  <meta property="og:type"
        content="article"/>
  <meta property="og:url" content="http://www.cinetenisverde.com.br/fargo/"/>
  <meta property="og:image"
        content="/img/logo.svg"/>
  <meta property="og:description"
        content="É muito simples entrar em uma comédia-thriller dos irmãos Coen. Há dois princípios extremamente eficazes em Fargo: os diálogos que expõem desde o início o caráter de seus caricatos personagens — como..."/>
  <meta property="og:site_name" content="Cine Tênis Verde"/>
  <meta property="article:published_time"
        content="2012-08-16T00:00:00+00:00"/>
  <meta property="article:section" content="post"/>

  <meta name="twitter:card" content="summary"/>
  <meta name="twitter:site"
        content=""/>
  <meta name="twitter:title" content="Fargo"/>
  <meta name="twitter:description"
        content="É muito simples entrar em uma comédia-thriller dos irmãos Coen. Há dois princípios extremamente eficazes em Fargo: os diálogos que expõem desde o início o caráter de seus caricatos personagens — como..."/>
  <meta name="twitter:creator"
        content=""/>
  <meta name="twitter:image:src"
        content="/img/logo.svg"/>

  <link rel="stylesheet" type="text/css" href="/css/capsule.min.css"/>
  <link rel="stylesheet" type="text/css" href="/css/custom.css"/>

  <link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
  <link rel="icon" href="/img/favicon.ico"/>

 Cine Tênis Verde

    <input type="checkbox" id="navbar-burger-state"/>

      search

      twitter

      rss

Fargo

    ★★★★★

 Wanderley Caloni, August 16, 2012

É muito simples entrar em uma comédia-thriller dos irmãos Coen. Há dois princípios extremamente eficazes em Fargo: os diálogos que expõem desde o início o caráter de seus caricatos personagens — como ao apresentar em uma inspirada conversa a maneira com que os dois capangas (Steve Buscemi e Peter Stormare) contratados pelo hesitante Jerry Lundegaard (William H. Macy) irão efetuar o sequestro de sua mulher — e os ângulos inusitados de câmera escolhidos por Joel Coen que exaltam o clima surreal dos fatos que irão se sucedendo aos poucos — e para isso há tomadas belíssimas sobre uma neve que ofusca o resto da paisagem e dá preferência para que vejamos o que está de fato ocorrendo na pacata cidadezinha.

Tão pacata, parece, que a heroína acidental da história, a icônica policial Marge Gunderson (Frances McDormand), aparece quase no final do primeiro ato, com uma sonolência típica da região fria (e que é pontuada pelos vários momentos em que a vemos acordando), mas com uma persistência e sagacidade dignas de um dos melhores detetives que o Cinema já viu: o que, de fato, poderia existir. Aliás, todas as circunstâncias em torno de Fargo, ainda que absurdas, são factíveis, e é o poder da direção dos Coen que transforma tudo em algo mais… cinematográfico.

A presença espirituosa de McDormand é o que nos dá um divertido contraponto, uma vez que, inserida em um filme de teor cômico, a protagonista participa desse universo, mas ao mesmo tempo as ações que são desempenhadas para ir ao encalço de um assassino brutal são factíveis e é o que dá a força motriz para continuarmos acompanhando a história. Por outro lado, se não houvesse as risadas eventuais — e apesar de parecerem muitas, fazem parte intrínseca da narrativa do gênero — não haveria fôlego para acompanharmos tantos acontecimentos de embrulhar o estômago.

E embrulhar estômagos sem partir para o humor escatológico é a maior virtude do trabalho dos Coen, um trabalho que já vai contando décadas de Cinema sadio e com um estilo próprio que sempre parece trazer novidades.

           Imagens e créditos no IMDB.

    ★★★★★

 Fargo ● Fargo. Fargo (USA, 1996). Dirigido por Joel Coen, Ethan Coen. Escrito por Ethan Coen, Joel Coen. Com William H. Macy, Steve Buscemi, Peter Stormare, Kristin Rudrüd, Harve Presnell, Tony Denman, Gary Houston, Sally Wingert, Kurt Schweickhardt. ● Nota: 5/5. Categoria: movies.  Publicado em 2012-08-16.  Texto escrito por Wanderley Caloni.

Quer comentar?

      Share

redpajama_set_name: RedPajamaGithub


text:
package me.moxun.dreamcatcher.connector.server.http;

import android.support.annotation.Nullable;

import java.util.ArrayList;

public class LightHttpMessage {
  public final ArrayList<String> headerNames = new ArrayList<>();
  public final ArrayList<String> headerValues = new ArrayList<>();

  public void addHeader(String name, String value) {
    headerNames.add(name);
    headerValues.add(value);
  }

  @Nullable
  public String getFirstHeaderValue(String name) {
    for (int i = 0, N = headerNames.size(); i < N; i++) {
      if (name.equals(headerNames.get(i))) {
        return headerValues.get(i);
      }
    }
    return null;
  }

  public void reset() {
    headerNames.clear();
    headerValues.clear();
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cladonia coniocraea f. coniocraea

### Remarks
null


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding model 'ScoreSettings'
        db.create_table('score_mgr_scoresettings', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('setup_points', self.gf('django.db.models.fields.IntegerField')(default=5)),
            ('referral_bonus_points', self.gf('django.db.models.fields.IntegerField')(default=10)),
            ('active_threshold_points', self.gf('django.db.models.fields.IntegerField')(default=50)),
            ('signup_bonus_points', self.gf('django.db.models.fields.IntegerField')(default=2)),
            ('quest_bonus_points', self.gf('django.db.models.fields.IntegerField')(default=0)),
            ('noshow_penalty_points', self.gf('django.db.models.fields.IntegerField')(default=4)),
        ))
        db.send_create_signal('score_mgr', ['ScoreSettings'])

        # Adding model 'ScoreboardEntry'
        db.create_table('score_mgr_scoreboardentry', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('profile', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['player_mgr.Profile'])),
            ('round_name', self.gf('django.db.models.fields.CharField')(max_length='30')),
            ('points', self.gf('django.db.models.fields.IntegerField')(default=0)),
            ('last_awarded_submission', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
        ))
        db.send_create_signal('score_mgr', ['ScoreboardEntry'])

        # Adding unique constraint on 'ScoreboardEntry', fields ['profile', 'round_name']
        db.create_unique('score_mgr_scoreboardentry', ['profile_id', 'round_name'])

        # Adding model 'PointsTransaction'
        db.create_table('score_mgr_pointstransaction', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('points', self.gf('django.db.models.fields.IntegerField')()),
            ('transaction_date', self.gf('django.db.models.fields.DateTimeField')()),
            ('message', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True)),
            ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True)),
        ))
        db.send_create_signal('score_mgr', ['PointsTransaction'])

        # Adding unique constraint on 'PointsTransaction', fields ['user', 'transaction_date', 'message']
        db.create_unique('score_mgr_pointstransaction', ['user_id', 'transaction_date', 'message'])

    def backwards(self, orm):

        # Removing unique constraint on 'PointsTransaction', fields ['user', 'transaction_date', 'message']
        db.delete_unique('score_mgr_pointstransaction', ['user_id', 'transaction_date', 'message'])

        # Removing unique constraint on 'ScoreboardEntry', fields ['profile', 'round_name']
        db.delete_unique('score_mgr_scoreboardentry', ['profile_id', 'round_name'])

        # Deleting model 'ScoreSettings'
        db.delete_table('score_mgr_scoresettings')

        # Deleting model 'ScoreboardEntry'
        db.delete_table('score_mgr_scoreboardentry')

        # Deleting model 'PointsTransaction'
        db.delete_table('score_mgr_pointstransaction')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 6, 8, 0, 43, 18, 449372)'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 6, 8, 0, 43, 18, 449194)'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'player_mgr.profile': {
            'Meta': {'object_name': 'Profile'},
            'completion_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'contact_carrier': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'contact_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
            'contact_text': ('django.contrib.localflavor.us.models.PhoneNumberField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
            'daily_visit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'last_visit_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}),
            'referrer_awarded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'referring_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'referred_profiles'", 'null': 'True', 'to': "orm['auth.User']"}),
            'setup_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'setup_profile': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'team': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['team_mgr.Team']", 'null': 'True', 'blank': 'True'}),
            'theme': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"})
        },
        'score_mgr.pointstransaction': {
            'Meta': {'ordering': "('-transaction_date',)", 'unique_together': "(('user', 'transaction_date', 'message'),)", 'object_name': 'PointsTransaction'},
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'message': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),
            'points': ('django.db.models.fields.IntegerField', [], {}),
            'transaction_date': ('django.db.models.fields.DateTimeField', [], {}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'score_mgr.scoreboardentry': {
            'Meta': {'ordering': "('round_name',)", 'unique_together': "(('profile', 'round_name'),)", 'object_name': 'ScoreboardEntry'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_awarded_submission': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'points': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'profile': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['player_mgr.Profile']"}),
            'round_name': ('django.db.models.fields.CharField', [], {'max_length': "'30'"})
        },
        'score_mgr.scoresettings': {
            'Meta': {'object_name': 'ScoreSettings'},
            'active_threshold_points': ('django.db.models.fields.IntegerField', [], {'default': '50'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'noshow_penalty_points': ('django.db.models.fields.IntegerField', [], {'default': '4'}),
            'quest_bonus_points': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'referral_bonus_points': ('django.db.models.fields.IntegerField', [], {'default': '10'}),
            'setup_points': ('django.db.models.fields.IntegerField', [], {'default': '5'}),
            'signup_bonus_points': ('django.db.models.fields.IntegerField', [], {'default': '2'})
        },
        'team_mgr.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'db_index': 'True'})
        },
        'team_mgr.team': {
            'Meta': {'object_name': 'Team'},
            'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['team_mgr.Group']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '1024', 'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'db_index': 'True'})
        }
    }

    complete_apps = ['score_mgr']


text:
package org.olat.login;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.fullWebApp.BaseFullWebappControllerParts;
import org.olat.core.extensions.ExtManager;
import org.olat.core.extensions.Extension;
import org.olat.core.extensions.sitescreator.SitesCreator;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.creator.ControllerCreator;
import org.olat.core.gui.control.generic.dtabs.DTabs;
import org.olat.core.gui.control.navigation.SiteDefinition;
import org.olat.core.gui.control.navigation.SiteDefinitions;
import org.olat.core.gui.control.navigation.SiteInstance;

/**
 * Description:

 * OLAT Sites, Topnavigation (search etc.), Footer and no Header for the authenticated user.
 *

 * Initial Date: 29.01.2008

 *
 * @author patrickb
 */
public class AuthBFWCParts implements BaseFullWebappControllerParts {

	/**
	 * @see org.olat.core.commons.fullWebApp.BaseFullWebappControllerParts#createFooterController(org.olat.core.gui.UserRequest, org.olat.core.gui.control.WindowControl)
	 */
	@Override
	public Controller createFooterController(final UserRequest ureq, final WindowControl wControl) {
		Controller footerCtr = null;
		// ----------- footer, optional (e.g. for copyright, powerd by) ------------------
		if (CoreSpringFactory.containsBean("fullWebApp.FooterControllerCreator")) {
			final ControllerCreator footerCreator = (ControllerCreator) CoreSpringFactory.getBean("fullWebApp.FooterControllerCreator");
			footerCtr = footerCreator.createController(ureq, wControl);
		}
		return footerCtr;
	}

	/**
	 * @see org.olat.core.commons.fullWebApp.BaseFullWebappControllerParts#createHeaderController(org.olat.core.gui.UserRequest, org.olat.core.gui.control.WindowControl)
	 */
	@Override
	public Controller createHeaderController(final UserRequest ureq, final WindowControl wControl) {
		Controller headerCtr = null;
		// ----------- header, optional (e.g. for logo, advertising ) ------------------
		if (CoreSpringFactory.containsBean("fullWebApp.HeaderControllerCreator")) {
			final ControllerCreator headerControllerCreator = (ControllerCreator) CoreSpringFactory.getBean("fullWebApp.HeaderControllerCreator");
			headerCtr = headerControllerCreator.createController(ureq, wControl);
		}
		return headerCtr;
	}

	/**
	 * @see org.olat.core.commons.fullWebApp.BaseFullWebappControllerParts#createTopNavController(org.olat.core.gui.UserRequest, org.olat.core.gui.control.WindowControl)
	 */
	@Override
	public Controller createTopNavController(final UserRequest ureq, final WindowControl wControl) {
		Controller topnavCtr = null;
		// ----------- topnav, optional (e.g. for imprint, logout) ------------------
		if (CoreSpringFactory.containsBean("fullWebApp.TopNavControllerCreator")) {
			final ControllerCreator topnavControllerCreator = (ControllerCreator) CoreSpringFactory.getBean("fullWebApp.TopNavControllerCreator");
			topnavCtr = topnavControllerCreator.createController(ureq, wControl);
		}
		return topnavCtr;
	}

	/**
	 * @see org.olat.core.commons.fullWebApp.BaseFullWebappControllerParts#getSiteInstances(org.olat.core.gui.UserRequest, org.olat.core.gui.control.WindowControl)
	 */
	@Override
	public List<SiteInstance> getSiteInstances(final UserRequest ureq, final WindowControl wControl) {
		final List<SiteInstance> sites = new ArrayList<SiteInstance>();
		final SiteDefinitions sitedefs = (SiteDefinitions) CoreSpringFactory.getBean("olatsites");
		final List<SiteDefinition> sitedeflist = sitedefs.getSiteDefList();

		for (final Iterator<SiteDefinition> it_sites = sitedeflist.iterator(); it_sites.hasNext();) {
			final SiteDefinition sitedef = it_sites.next();
			final SiteInstance site = sitedef.createSite(ureq, wControl);
			if (site != null) {
				// site == null means that site is not visible to the current user
				sites.add(site);
			}
		}

		// let all extensions add sitedefinitions
		final ExtManager extm = ExtManager.getInstance();
		final Class extensionPointSites = DTabs.class;
		final int cnt = extm.getExtensionCnt();
		for (int i = 0; i < cnt; i++) {
			final Extension anExt = extm.getExtension(i);
			// check for sites
			final SitesCreator sc = (SitesCreator) anExt.getExtensionFor(extensionPointSites.getName());
			if (sc != null) {
				final List extsitedefs = sc.createSiteDefinitions();
				for (final Iterator it_extsites = extsitedefs.iterator(); it_extsites.hasNext();) {
					final SiteDefinition sdef = (SiteDefinition) it_extsites.next();
					final SiteInstance si = sdef.createSite(ureq, wControl);
					sites.add(si);
					extm.inform(extensionPointSites, anExt, "added sitedefinition " + sdef.getClass().getName());
				}
			}
		}

		return sites;
	}

	@Override
	public Controller getContentController(final UserRequest ureq, final WindowControl control) {
		// could be used for first time information, or to start a workflow to set
		// language etc.
		// not working as overlay, but as a content-replacement
		return null;
	}

}


text:
import { expect, expectAsync, tap } from '@pushrocks/tapbundle';
import * as smartdelay from '@pushrocks/smartdelay';

import * as early from '../ts/index.js';

tap.test('.start()', async () => {
  process.env.CLI_CALL_MODULENAME = 'early';
  early.start('early');
  await smartdelay.delayFor(2000);
});

tap.test('.stop()', async () => {
  await early.stop();
});

tap.test('hrTime Measurement', async () => {
  let earlyHr = new early.HrtMeasurement();
  earlyHr.start();
  await smartdelay.delayFor(1000);
  let measuredTime = earlyHr.stop();
  console.log(measuredTime);
  return expect(measuredTime.milliSeconds).toBeGreaterThan(999);
});

tap.start();


text:
//-----------------------------------------------------------------------
// <copyright file="CanvasListCell.cs" company="Google">
//
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using UnityEngine;
using UnityEngine.UI;

namespace SIS {
    public class CanvasListCell<D> : MonoBehaviour {
        [HideInInspector] public D datum { get; private set; }

        protected bool _isSelected = false;
        public bool isSelected { get { return _isSelected; } }

        public Text titleLabel;
        public Text subtitleLabel;
        public Image iconImage;
        public Button button;

        public virtual void ReloadUI() {

        }

        public virtual void SetDatum(D newDatum) {
            datum = newDatum;

            if (titleLabel != null) { titleLabel.color = ColorThemeData.Instance.interactionColor; }
            if (subtitleLabel != null) { subtitleLabel.color = ColorThemeData.Instance.interactionColor; }
            if (iconImage != null) { iconImage.color = ColorThemeData.Instance.interactionColor; }

            UnityEngine.UI.ColorBlock buttonCols = button.colors;
            buttonCols.pressedColor = ColorThemeData.Instance.interactionColor.ColorWithBrightness(0.8f);
            button.colors = buttonCols;
        }

        protected void SetContentUIColor(Color contentCol, Color bgCol) {
            if (titleLabel != null) { titleLabel.color = contentCol; }
            if (subtitleLabel != null) { subtitleLabel.color = contentCol; }
            if (iconImage != null) { iconImage.color = contentCol; }

            ColorBlock colors = button.colors;
            colors.normalColor = bgCol;
            colors.highlightedColor = bgCol;
            button.colors = colors;
        }

        public virtual void CellWasSelected(CanvasListBase<D> parentList) {
            _isSelected = true;
            SetContentUIColor(Color.white, ColorThemeData.Instance.interactionColor);
        }

        public virtual void CellWasDeselected(CanvasListBase<D> parentList) {
            _isSelected = false;
            SetContentUIColor(ColorThemeData.Instance.interactionColor, Color.white);
        }
    }
}


text:
package org.neo4j.server.preflight;

import org.neo4j.logging.Log;
import org.neo4j.logging.LogProvider;

/**
 * These are tasks that are run on server startup that may take a long time
 * to execute, such as recovery, upgrades and so on.
 *
 * This implementation still needs some work, because of some of the refactoring
 * done regarding the NeoServer. Specifically, some of these tasks verify that
 * properties files exist and are valid. Other preflight tasks we might want to
 * add could be auto-generating config files if they don't exist and creating required
 * directories.
 *
 * All of these (including auto-generating neo4j.properties and creating directories)
 * except validating and potentially generating neo4j-server.properties depend on having
 * the server configuration available. Eg. we can't both ensure that file exists within these
 * tests, while at the same time depending on that file existing.
 *
 * The validation is not a problem, because we will refactor the server config to use the
 * new configuration system from the kernel, which automatically validates itself.
 *
 * Ensuring the config file exists (and potentially auto-generating it) is a problem.
 * Either this need to be split into tasks that have dependencies, and tasks that don't.
 *
 * Although, it seems it is only this one edge case, so perhaps accepting that and adding
 * code to the bootstrapper to ensure the config file exists is acceptable.
 */
public class PreFlightTasks
{
    private final PreflightTask[] tasks;
    private final Log log;

    private PreflightTask failedTask = null;

    public PreFlightTasks( LogProvider logProvider, PreflightTask... tasks )
    {
        this.tasks = tasks;
        this.log = logProvider.getLog( getClass() );
    }

    public boolean run()
    {
        if ( tasks == null || tasks.length < 1 )
        {
            return true;
        }

        for ( PreflightTask r : tasks )
        {
            if ( !r.run() )
            {
                log.error( r.getFailureMessage() );
                failedTask = r;
                return false;
            }
        }

        return true;
    }

    public PreflightTask failedTask()
    {
        return failedTask;
    }
}


text:
package alluxio.master.file.meta;

import alluxio.AlluxioURI;
import alluxio.conf.Configuration;
import alluxio.conf.PropertyKey;
import alluxio.exception.InvalidPathException;
import alluxio.file.options.DescendantType;
import alluxio.grpc.FileSystemMasterCommonPOptions;
import alluxio.master.file.meta.InodeTree.LockPattern;

import com.google.common.base.MoreObjects;

import javax.annotation.concurrent.ThreadSafe;

/**
 * This class represents information about how a path should be locked.
 */
@ThreadSafe
public final class LockingScheme {
  private final AlluxioURI mPath;
  private final LockPattern mDesiredLockPattern;
  private final SyncCheck mShouldSync;

  /**
   * Constructs a {@link LockingScheme}.
   *
   * @param path the path to lock
   * @param desiredLockPattern the desired lock mode
   * @param shouldSync true if the path should be synced
   */
  public LockingScheme(AlluxioURI path, LockPattern desiredLockPattern, boolean shouldSync) {
    mPath = path;
    mDesiredLockPattern = desiredLockPattern;
    mShouldSync = shouldSync ? SyncCheck.SHOULD_SYNC : SyncCheck.SHOULD_NOT_SYNC;
  }

  /**
   * Create a new {@link LockingScheme}.
   *
   * Thi constructor computes the value of {@link #mShouldSync} with the extra argument provided.
   *
   * @param path the path to lock
   * @param desiredPattern the desired lock mode
   * @param options the common options provided in an RPC
   * @param pathCache the {@link alluxio.master.file.DefaultFileSystemMaster}'s path cache
   * @param descendantType the descendant type
   */
  public LockingScheme(AlluxioURI path, LockPattern desiredPattern,
      FileSystemMasterCommonPOptions options, UfsSyncPathCache pathCache,
      DescendantType descendantType) throws InvalidPathException {
    mPath = path;
    mDesiredLockPattern = desiredPattern;
    // If client options didn't specify the interval, fallback to whatever the server has
    // configured to prevent unnecessary syncing due to the default value being 0
    long syncInterval = options.hasSyncIntervalMs() ? options.getSyncIntervalMs() :
        Configuration.getMs(PropertyKey.USER_FILE_METADATA_SYNC_INTERVAL);
    mShouldSync = pathCache.shouldSyncPath(path, syncInterval, descendantType);
  }

  /**
   * @return the desired mode for the locking
   */
  public LockPattern getDesiredPattern() {
    return mDesiredLockPattern;
  }

  /**
   * @return the mode that should be used to lock the path, considering if ufs sync should occur
   */
  public LockPattern getPattern() {
    if (mShouldSync.isShouldSync()) {
      // Syncing needs to be able to delete the inode if it was deleted in the UFS.
      return LockPattern.WRITE_EDGE;
    }
    return mDesiredLockPattern;
  }

  /**
   * @return the path for this locking scheme
   */
  public AlluxioURI getPath() {
    return mPath;
  }

  /**
   * @return true if the path should be synced with ufs
   */
  public SyncCheck shouldSync() {
    return mShouldSync;
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this)
        .add("path", mPath)
        .add("desiredLockPattern", mDesiredLockPattern)
        .add("shouldSync", mShouldSync)
        .toString();
  }
}


text:
package com.facebook.soloader.nativeloader;

/** Class which connects system's native library loader to NativeLoader */
public class SystemDelegate implements NativeLoaderDelegate {
  @Override
  public boolean loadLibrary(String shortName, int flags) {
    // System.loadLibrary don't support flags so ignore them.
    System.loadLibrary(shortName);
    // System.loadLibrary doesn't indicate whether this was a first-time load,
    // so let's just always assume it was.
    return true;
  }

  @Override
  public String getLibraryPath(String libName) {
    return null;
  }

  @Override
  public int getSoSourcesVersion() {
    return 0;
  }
}


text:
using namespace std;

template <class TSolver>
class MGSolver
{
	typedef RegularGrid<2> Grid;

private:
	const Configuration& config;
	vector<shared_ptr<Grid>> grids;
	vector<shared_ptr<TSolver>> solvers;

public:
	MGSolver(const Configuration& config, const Grid& baseGrid, const vector<Ray<2>>& data,
		const function<double(const Vector<2>&)>& baseModel = [](const Vector<2>&){return 0.0;}): config(config)
	{
		int resX = baseGrid.getNodeCount(0);
		int resY = baseGrid.getNodeCount(1);
		for (int layer = 0; layer < config.Layers; layer++)
		{
			shared_ptr<Grid> currentGrid(new Grid(baseGrid));
			currentGrid->setNodeCount(vector2(resX, resY));
			grids.push_back(currentGrid);

			shared_ptr<TSolver> currentSolver(new TSolver(currentGrid->getTotalNodeCount()));
			solvers.push_back(currentSolver);

			MatrixBuilder<2> mb(currentGrid);
			for (int i = 0; i < (int)data.size(); i++)
			{
				mb.addRay(data[i]);
			}

			currentSolver->addConstraint(mb.getConstraint());
			if (config.UseAA)
				currentSolver->addConstraint(new LaplaceConstraint(*currentGrid));
			if (layer == config.Layers-1)
				currentSolver->addConstraint(new PositiveConstraint());

			if (config.UseWeights)
			{
				int nmax = currentGrid->getNodeCount(0);
				double e1 = 15. * nmax / 128.;
				double e2 = 20. * nmax / 128.;
				double e3 = 60. * nmax / 128.;
				double e4 = 80. * nmax / 128.;
				auto weightFunc = [e1, e2, e3, e4](double nx, double)
				{
					if (nx < e1 || nx > e4) return 0.0;
					if (nx > e2 && nx < e3) return 1.0;
					double t = 0.0;
					if (nx >= e1 && nx <= e2)
						t = (nx - e1) / (e2 - e1);
					if (nx >= e3 && nx <= e4)
						t = (e4 - nx) / (e4 - e3);
					return 3*t*t - 2*t*t*t;
				};
				vector<double> weights(currentGrid->getTotalNodeCount());
				currentGrid->forEachNode([weightFunc, &weights, currentGrid](const Vector<2, int>& v)
				{
					weights[currentGrid->getNodeID(v)] = weightFunc(v[0], v[1]);
				});
				currentSolver->setWeights(weights);
			}

			if (layer == config.Layers-1)
				currentGrid->forEachNode([baseModel, currentSolver, currentGrid](const Vector<2, int>& n)
				{
					auto v = currentGrid->getNodeCoords(n);
					currentSolver->getResult()[currentGrid->getNodeID(n)] = baseModel(v);
				});

			resX /= 2;
			resY /= 2;
		}
	}

	void solve()
	{
		// Coarse >> fine
		for (auto it = solvers.rbegin(); it != solvers.rend(); it++)
		{
			auto solver = *it;
			//Correct the error from previous layer, if present
			if (it != solvers.rbegin())
			{
				// Compute the error on previous layer
				auto prevSolver = *(it-1);
				LinearConstraint* constraint = (LinearConstraint*)prevSolver->getConstraint(0);
				auto A = constraint->getMatrix();
				auto b = constraint->getRightSide();
				auto err = A.transform(prevSolver->getResult());
				for (int k = 0; k < (int)b.size(); k++)
				{
					err[k] = b[k] - err[k];
				}

				// And solve it instead in current layer
				((LinearConstraint*)solver->getConstraint(0))->setRightSide(err);
			}

			// Calculate the correction
			for (int iter = 0; iter < config.MaxIter; iter++) solver->iterate();
		}
	}

	vector<vector<double>> getResult()
	{
		return getResult(-1);
	}

	vector<vector<double>> getResult(int layer)
	{
		vector<vector<double>> result(grids.front()->getNodeCount(0), vector<double>(grids.front()->getNodeCount(1)));
		for (int i = 0; i < (int)grids.front()->getNodeCount(0); i++)
		{
			for (int j = 0; j < (int)grids.front()->getNodeCount(1); j++)
			{
				auto v = grids.front()->getNodeCoords(vector2(i, j));
				double value = 0.0;
				if (layer == -1)
					for (int l = 0; l < (int)solvers.size(); l++)
						value += grids[l]->getValueAtLocal(v, solvers[l]->getResult());
				else
					value = grids[layer]->getValueAtLocal(v, solvers[layer]->getResult());
				result[i][j] = value;
			}
		}
		return result;
	}
};


text:
package org.apache.sqoop.lib;

import java.io.IOException;

import com.cloudera.sqoop.lib.FieldMappable;
import com.cloudera.sqoop.lib.ProcessingException;

/**
 * Interface implemented by classes that process FieldMappable objects.
 */
public interface FieldMapProcessor {

  /**
   * Allow arbitrary processing of a FieldMappable object.
   * @param record an object which can emit a map of its field names to values.
   * @throws IOException if the processor encounters an IO error when
   * operating on this object.
   * @throws ProcessingException if the FieldMapProcessor encounters
   * a general processing error when operating on this object.
   */
  void accept(FieldMappable record) throws IOException, ProcessingException;
}


text:
.. code-block:: csharp

  IEnumerable<Snapshot> snapshots = cbsProvider.ListSnapshots(region: "{region}");

.. code-block:: java

  SnapshotApi snapshotApi = cinderApi.getSnapshotApiForZone("{region}");

  List<Snapshot> snapshots = snapshotApi.listInDetail().toList();

.. code-block:: javascript

  client.getSnapshots(function(err, snapshots) {
    if (err) {
      // TODO handle as appropriate
    }

    // TODO use your list of snapshots
  });

.. code-block:: php

  $snapshots = $volumeService->snapshotList(array(
    'volume_id' => $volume->id()
  ));

.. code-block:: python

  snapshots = vol.list_snapshots()

.. code-block:: ruby

  snapshots = @client.snapshots.all

  # To fetch only snapshots associated with a given volume:
  volume.snapshots

.. code-block:: sh

  curl -X GET $ENDPOINT/snapshots \
    -H "X-Auth-Token: $TOKEN" \
    -H "Content-Type: application/json" | python -m json.tool


text:
namespace TeamSpark.AzureDay.WebSite.Notification.Email.Model
{
	public sealed class RestorePasswordMessage : MessageBase
	{
		public string Token { get; set; }
	}
}


text:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by Administrator on 2014/8/9 0009.
 */
public class Majority_Number {
    /**http://lintcode.com/accounts/login/
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        if (null == nums || nums.size() == 0) {
            return 0;
        }

        if (nums.size() < 3) {
            return nums.get(0);
        }

        // write your code
        Queue<Integer> q = new LinkedList<Integer>();
        q.add(nums.get(0));

        for (int i = 1; i < nums.size(); ++i) {
            Integer cur = nums.get(i);
            if (q.peek() != cur) {
                q.poll();
            } else {
                q.add(cur);
            }
        }

        return q.peek();
    }

    public static void main(String[] args) {
        System.out.println(new Majority_Number().majorityNumber(new ArrayList<Integer>(Arrays.asList(1, 1, 1, 1, 2, 2, 2))));
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>PHP Stream: phpstream\operators\PeekOperator Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

PHP Stream

phpstream

operators

PeekOperator

Public Member Functions |
List of all members

phpstream\operators\PeekOperator Class Reference

Inheritance diagram for phpstream\operators\PeekOperator:

  <map id="phpstream_5Coperators_5CPeekOperator_map" name="phpstream_5Coperators_5CPeekOperator_map">
<area href="interfacephpstream_1_1operators_1_1StreamOperator.html" alt="phpstream\operators\StreamOperator" shape="rect" coords="0,0,222,24"/>
  </map>

Public Member Functions

 	__construct (callable|UnaryFunction|PeekOperator $fn)

 	execute (iterable $values)

Detailed Description

A peek operator is used to call a function over ech element of the collection without altering it (i.e. display the actual value of the list.)

Constructor & Destructor Documentation

◆ __construct()

          phpstream\operators\PeekOperator::__construct
          (
          callable|UnaryFunction|PeekOperator
          $fn	)

Creates a new peek operator enclosing the given function.

If parameter is a callable, the function should take one argument (value in the collection) and returns nothing (function(mixed $value): void). If parameter is an UnaryFunction, the implemented UnaryFunction::apply should return nothing.

The potential returned value of the "peeking" function will be ignored.

Parameters

callable | UnaryFunction | PeekOperator	$fn	The "do nothing" function.

Member Function Documentation

◆ execute()

          phpstream\operators\PeekOperator::execute
          (
          iterable
          $values	)

The method call the "picking" function and returns an iterable of the initial elements.

Parameters

iterable	$values	Values to process.

Returns

iterable The processed values.

Implements phpstream\operators\StreamOperator.

The documentation for this class was generated from the following file:

src/phpstream/operators/PeekOperator.php

<address class="footer">
Generated by  1.9.1
</address>


text:
/*--------------------------------------------------------*\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: https://hprose.com                     |
|                                                          |
|  FieldsAccessor.cs                                       |
|                                                          |
|  FieldsAccessor class for C#.                            |
|                                                          |
|  LastModified: Feb 21, 2019                              |
|  Author: Ma Bingyao <andot@hprose.com>                   |
|                                                          |
\*________________________________________________________*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;

using static System.Reflection.BindingFlags;

namespace Hprose.IO {
    internal static class FieldsAccessor {
        public static Dictionary<string, MemberInfo> GetFields(Type type) {
            var members = new Dictionary<string, MemberInfo>();
#if !NET35_CF
            if (!type.IsSerializable) {
#else
            if ((type.Attributes & TypeAttributes.Serializable) != TypeAttributes.Serializable) {
#endif
                return members;
            }
            var flags = Public | NonPublic | DeclaredOnly | Instance;
            var ignoreDataMember = typeof(IgnoreDataMemberAttribute);
            while (type != typeof(object)
#if !NET35_CF
                && type.IsSerializable) {
#else
                && (type.Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable) {
#endif
                var fields = type.GetFields(flags);
                foreach (var field in fields) {
                    var dataMember = Attribute.GetCustomAttribute(field, typeof(DataMemberAttribute), false) as DataMemberAttribute;
                    string name;
                    if (!field.IsDefined(ignoreDataMember, false) &&
                        !field.IsNotSerialized &&
                        !members.ContainsKey(name = Accessor.UnifiedName(dataMember?.Name ?? field.Name))) {
                        members[name] = field;
                    }
                }
                type = type.BaseType;
            }
            return (from entry in members
                    orderby (Attribute.GetCustomAttribute(entry.Value, typeof(DataMemberAttribute), false) as DataMemberAttribute)?.Order ?? 0
                    select entry).ToDictionary(
                        pair => pair.Key,
                        pair => pair.Value,
                        StringComparer.OrdinalIgnoreCase
                    );
        }
    }
    public static class FieldsAccessor<T> {
        public static Dictionary<string, MemberInfo> Fields { get; } = FieldsAccessor.GetFields(typeof(T));
    }
}


text:
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier:  Apache-2.0

global using Xunit;
global using Amazon.S3;
global using Amazon.S3.Transfer;
global using TransferUtilityBasics;
global using Microsoft.Extensions.Configuration;


text:
from django.template.response import TemplateResponse
from django.contrib.auth.models import User
from api.models import Account
import json

def base_view(request):
    if not request.user.is_authenticated():
        return TemplateResponse(request, 'login.html', {})
    account = Account.objects.get(user_id=request.user.id)

    return TemplateResponse(request, 'hello.html', {'user': json.dumps(account.id)})

def outfit_view(request):
    if not request.user.is_authenticated():
        return TemplateResponse(request, 'login.html', {})
    account = Account.objects.get(user_id=request.user.id)

    return TemplateResponse(request, 'outfit.html', {'user': json.dumps(account.id)})


text:
import * as eyes from 'eyes.it';
import { browser } from 'protractor';
import {
  createStoryUrl,
  waitForVisibilityOf,
} from 'wix-ui-test-utils/protractor';
import { stripCardTestkitFactory } from '../../testkit/protractor';
import { StoryCategory } from '../../../stories/storyHierarchy';

describe('stripCard', () => {
  const storyUrl = createStoryUrl({
    kind: StoryCategory.BOOKINGS,
    story: 'StripCard',
    withExamples: true,
  });
  const dataHook = 'storybook-StripCard';

  beforeEach(() => browser.get(storyUrl));

  eyes.it('should render', async () => {
    const driver = stripCardTestkitFactory({ dataHook });
    await waitForVisibilityOf(await driver.element(), 'Cannot find StripCard');
    expect((await driver.element()).isDisplayed()).toBe(true);
  });
});


text:
Kunstmaan CMS
=====================

The Kunstmaan CMS is an advanced yet user-friendly content management system, based on the full stack Symfony framework combined with a whole host of community bundles. It provides a full featured, multi-language CMS system with
an innovative page and form assembling process, versioning, workflow, translation and media managers and much much more.

Please refer to the documentation at [https://kunstmaancms.be/documentation](https://kunstmaancms.be/documentation) to get your CMS up and running.

![Screenshot](https://kunstmaancms.be/assets/content-management-system-kunstmaan.jpg)

### Contributing

We love contributions! We've provide you with a [Contribution Guide](./contributing/index.md) to get you started.
If you're submitting a pull request, please follow the guidelines in the [Submitting pull requests](./contributing/pull-requests.md)
documentation and be sure to read our [Coding Standards](./contributing/coding-standards.md) as well.

### Browser support

We support at least the 2 last versions of Chrome / Firefox / Safari and IE9 or up. We also support the most current mobile browsers.

Enjoy!

[![Build Status](https://github.com/Kunstmaan/KunstmaanBundlesCMS/actions/workflows/ci.yml/badge.svg)](https://github.com/Kunstmaan/KunstmaanBundlesCMS/actions)
[![Latest Stable Version](https://poser.pugx.org/kunstmaan/bundles-cms/v/stable)](https://packagist.org/packages/kunstmaan/bundles-cms)
[![Latest Unstable Version](https://poser.pugx.org/kunstmaan/bundles-cms/v/unstable)](https://packagist.org/packages/kunstmaan/bundles-cms)
[![Total Downloads](https://poser.pugx.org/kunstmaan/bundles-cms/downloads)](https://packagist.org/packages/kunstmaan/bundles-cms)
[![Monthly Downloads](https://poser.pugx.org/kunstmaan/bundles-cms/d/monthly)](https://packagist.org/packages/kunstmaan/bundles-cms)
[![Crowdin](https://d322cqt584bo4o.cloudfront.net/kunstmaanbundlescms/localized.svg)](https://kunstmaancms.be/translate-ui)
[![License](https://poser.pugx.org/kunstmaan/bundles-cms/license)](https://packagist.org/packages/kunstmaan/bundles-cms)


text:
Its.Cqrs
========

[![Join the chat at https://gitter.im/jonsequitur/Its.Cqrs](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/jonsequitur/Its.Cqrs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[![Build Status](https://ci.appveyor.com/api/projects/status/github/jonsequitur/Its.Cqrs?svg=true&branch=master)](https://ci.appveyor.com/project/jonsequitur/its-cqrs)

A set of libraries for CQRS and Event Sourcing, with a Domain-Driven Design flavor.

Here are some useful definitions:
---------------------------------

[CQRS](http://martinfowler.com/bliki/CQRS.html)

[Domain Driven Design](http://en.wikipedia.org/wiki/Domain-driven_design)

[Event Sourcing](http://martinfowler.com/eaaDev/EventSourcing.html)

Ok, why?
--------

Systems built using these patterns can offer some improvements over the "traditional" approach where a single model, generally stored in a relational database, is used for both reads and writes. These improvements include:

* More cohesive business logic. Commands sent to your domain model are the entry point for all changes to its state. This provides a clear pattern for implementing validation and authorization.
* Better control over concurrency. The source of truth for your domain model is an incrementing event stream, making concurrency easier to detect and respond to in scenario-specific ways, as well as removing the need for pessimistic locks and explicit transactions.
* Improved scalability. By decoupling reads and writes, the read and write sides of the application can be scaled independently.
* Simplified partitioning. Event streams partition naturally on a single key, and there is no partitioning or replication of related data needed.
* Simplified deployments. Read model databases are projections from one or more event streams. These databases can be treated as disposable, queryable caches. This allows multiple versions of an application with different data schema needs to run at the same time, each with their own read model database.
* Improved auditability. The event stream is append-only, and captures the important steps in the process you've modeled in your domain. This improves diagnosability, allows you to "debug history" when something unexpected happens, and can provide insights into how the system is being used that are lost in traditional systems where data is being overwritten.


text:
package org.apache.druid.indexing.common.task;

import org.apache.curator.shaded.com.google.common.base.Verify;
import org.apache.druid.java.util.common.JodaUtils;
import org.apache.druid.java.util.common.guava.Comparators;
import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
import org.apache.druid.server.coordinator.duty.CompactSegments;
import org.joda.time.Interval;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;

public class Tasks
{
  public static final int DEFAULT_REALTIME_TASK_PRIORITY = 75;
  public static final int DEFAULT_BATCH_INDEX_TASK_PRIORITY = 50;
  public static final int DEFAULT_MERGE_TASK_PRIORITY = 25;

  static {
    Verify.verify(DEFAULT_MERGE_TASK_PRIORITY == DataSourceCompactionConfig.DEFAULT_COMPACTION_TASK_PRIORITY);
  }

  public static final int DEFAULT_TASK_PRIORITY = 0;
  public static final long DEFAULT_LOCK_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(5);
  public static final boolean DEFAULT_FORCE_TIME_CHUNK_LOCK = true;
  public static final boolean DEFAULT_STORE_COMPACTION_STATE = false;

  public static final String PRIORITY_KEY = "priority";
  public static final String LOCK_TIMEOUT_KEY = "taskLockTimeout";
  public static final String FORCE_TIME_CHUNK_LOCK_KEY = "forceTimeChunkLock";
  /**
   * This context is used in compaction. When it is set in the context, the segments created by the task
   * will fill 'lastCompactionState' in its metadata. This will be used to track what segments are compacted or not.
   * See {@link org.apache.druid.timeline.DataSegment} and {@link
   * org.apache.druid.server.coordinator.duty.NewestSegmentFirstIterator} for more details.
   */
  public static final String STORE_COMPACTION_STATE_KEY = "storeCompactionState";

  static {
    Verify.verify(STORE_COMPACTION_STATE_KEY.equals(CompactSegments.STORE_COMPACTION_STATE_KEY));
  }

  public static SortedSet<Interval> computeCondensedIntervals(SortedSet<Interval> intervals)
  {
    final SortedSet<Interval> condensedIntervals = new TreeSet<>(Comparators.intervalsByStartThenEnd());
    List<Interval> toBeAccumulated = new ArrayList<>();
    for (Interval interval : intervals) {
      if (toBeAccumulated.size() == 0) {
        toBeAccumulated.add(interval);
      } else {
        if (toBeAccumulated.get(toBeAccumulated.size() - 1).abuts(interval)) {
          toBeAccumulated.add(interval);
        } else {
          condensedIntervals.add(JodaUtils.umbrellaInterval(toBeAccumulated));
          toBeAccumulated.clear();
          toBeAccumulated.add(interval);
        }
      }
    }
    if (toBeAccumulated.size() > 0) {
      condensedIntervals.add(JodaUtils.umbrellaInterval(toBeAccumulated));
    }
    return condensedIntervals;
  }
}


text:
namespace Microsoft.Azure.Management.WorkloadMonitor.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Error response
    /// </summary>
    public partial class ErrorResponse
    {
        /// <summary>
        /// Initializes a new instance of the ErrorResponse class.
        /// </summary>
        public ErrorResponse()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ErrorResponse class.
        /// </summary>
        /// <param name="error">Error info.</param>
        public ErrorResponse(ErrorResponseError error = default(ErrorResponseError))
        {
            Error = error;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets error info.
        /// </summary>
        [JsonProperty(PropertyName = "error")]
        public ErrorResponseError Error { get; set; }

    }
}


text:
import { commitMutation, graphql } from 'react-relay';

const mutation = graphql`
  mutation updateCarMutation($input: UpdateCarInput!) {
    updateCar(input: $input) {
      viewer {
        id
      }
      car {
        id
        make
        model
        year
        color
        price
      }
    }
  }
`;

const getOptimisticResponse = (car) => ({ updateCar: { car } });

let clientMutationId = 0;

export const updateCar = (environment, car) => {
    return commitMutation(
        environment,
        {
            mutation,
            variables: { input: {
                car,
                clientMutationId: String(clientMutationId++),
            } },
            optimisticResponse: getOptimisticResponse(car),
        }
    );
};


text:
/**
 * Using the template engine render the values into the template
 */
module.exports = function (objectRepository, viewName) {

    return function (req, res) {
        res.tpl['viewName'] = viewName;
        return res.render(viewName, res.tpl);
    };

};


text:
import React from 'react';
import PropTypes from 'prop-types';
// eslint-disable-next-line import/no-extraneous-dependencies
import { drawSelectedElement } from '@storybook/addon-measure/dist/cjs/box-model/visualizer';
// eslint-disable-next-line import/no-extraneous-dependencies
import { init, destroy } from '@storybook/addon-measure/dist/cjs/box-model/canvas';

export const ShadowRoot = ({ label = 'Hello from shadow DOM', drawMode = 'ROOT' }) => {
  const ref = React.useRef();

  React.useEffect(() => {
    if (!ref.current.attachShadow) return;

    ref.current.attachShadow({ mode: 'open' });

    ref.current.shadowRoot.innerHTML = `
      <style>
        button {
          font-family: "Nunito Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
          font-weight: 700;
          border: 0;
          border-radius: 3em;
          cursor: pointer;
          display: inline-block;
          line-height: 1;
          color: white;
          background-color: tomato;
          font-size: 14px;
          padding: 11px 20px;
        }
        button:hover {
          text-decoration: underline;
        }
        button:focus {
          box-shadow: inset 0 0 0 2px maroon;
          outline: 0;
        }
        button:active {
          background-color: firebrick;
        }
      </style>
      <button>${label}</button>
    `;

    init();
    drawSelectedElement(drawMode === 'ROOT' ? ref.current : ref.current.shadowRoot.children[1]);

    // eslint-disable-next-line consistent-return
    return () => {
      destroy();
    };
  }, []);

  return <div ref={ref} />;
};

ShadowRoot.propTypes = {
  label: PropTypes.string,
  drawMode: PropTypes.oneOf(['ROOT', 'NESTED']),
};

ShadowRoot.defaultProps = {
  label: 'Hello from shadow DOM',
  drawMode: 'ROOT',
};


text:
package org.codehaus.groovy.grails.web.taglib;

import grails.util.GrailsUtil;

import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException;

/**
 * Allows defining of variables within the page context.
 *
 * @author Graeme Rocher
 */
public class GroovyDefTag extends GroovySyntaxTag {

    public static final String TAG_NAME = "def";
    private static final String ATTRIBUTE_VALUE = "value";

    public void doStartTag() {
        String expr = attributes.get(ATTRIBUTE_VALUE);
        if (StringUtils.isBlank(expr)) {
            throw new GrailsTagException("Tag [" + TAG_NAME + "] missing required attribute [" + ATTRIBUTE_VALUE + "]", parser.getPageName(), parser.getCurrentOutputLineNumber());
        }

        String var = attributes.get(ATTRIBUTE_VAR);
        if (StringUtils.isBlank(var)) {
            throw new GrailsTagException("Tag [" + TAG_NAME + "] missing required attribute [" + ATTRIBUTE_VAR + "]", parser.getPageName(), parser.getCurrentOutputLineNumber());
        }

        GrailsUtil.deprecated("The tag <g:def> is deprecated and will be removed in a future release. Use <g:set> instead.");
        out.print("def ");
        out.print(var.substring(1,var.length() -1));
        out.print('=');
        out.println(expr);
    }

    public void doEndTag() {
        // do nothing
    }

    public String getName() {
        return TAG_NAME;
    }

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

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


text:
ActiveAdmin.register Package do
  menu :parent => "Config"
end


text:
/*
 * \brief
 * \author Sylvain Jaume, Francois Huguet
 */

# ifndef SO_VTK_GREEDYTERRAINDECIMATION_H_
# define SO_VTK_GREEDYTERRAINDECIMATION_H_

# include <Inventor/engines/SoSubEngine.h>

# include "xip/inventor/vtk/SoSFVtkAlgorithmOutput.h"
# include "xip/inventor/vtk/SoSFVtkObject.h"

# include "vtkGreedyTerrainDecimation.h"

# include "Inventor/fields/SoSFFloat.h"
# include "vtkType.h"
# include "Inventor/fields/SoSFInt32.h"

class SoVtkGreedyTerrainDecimation : public SoEngine
{
	SO_ENGINE_HEADER( SoVtkGreedyTerrainDecimation );

public:

	/// Constructor
	SoVtkGreedyTerrainDecimation();

	/// Class Initialization
	static void initClass();

	// Inputs
	/// AbsoluteError
	SoSFFloat AbsoluteError;
	/// NumberOfTriangles of type vtkIdType
	SoSFVtkObject NumberOfTriangles;
	/// ErrorMeasure
	SoSFInt32 ErrorMeasure;
	/// RelativeError
	SoSFFloat RelativeError;
	/// Reduction
	SoSFFloat Reduction;
	/// BoundaryVertexDeletion
	SoSFInt32 BoundaryVertexDeletion;
	/// ComputeNormals
	SoSFInt32 ComputeNormals;
	/// Input connection
	SoSFVtkAlgorithmOutput InputConnection;

	// Outputs
	/// SoSFVtkObject of type vtkPolyData
	SoEngineOutput Output;
	/// SoSFVtkAlgorithmOutput
	SoEngineOutput OutputPort;

protected:

	/// Destructor
	~SoVtkGreedyTerrainDecimation();

	/// Evaluate Function
	virtual void evaluate();

	/// inputChanged Function
	virtual void inputChanged(SoField *);

	/// reset Function
	virtual void reset();

	/// vtkPolyData
	SoVtkObject *mOutput;

	/// vtkAlgorithm
	SoVtkAlgorithmOutput *mOutputPort;

private:

	vtkGreedyTerrainDecimation* mObject;
	/// addCalled checks if the Add*() method has been called
	bool addCalled;
};

#endif // SO_VTK_GREEDYTERRAINDECIMATION_H_


text:
$(function() {
  var sessid, sock, updateProgress;
  sock = new WebSocket("wss" + (location.href.substring(5, location.href.lastIndexOf('/'))));
  sock.onopen = function() {
    sock.send("\"" + sessid + "\"");
    $(".contentlink[href='" + location.hash + "']").click();
    sock.onclose = function() {
      if (!window.preventSocketAlert) {
        alert('the websocket has been disconnected, reloading the page');
        return document.location.reload();
      }
    };
    return sock.onmessage = function(event) {
      var current, i, len, msg, msgData, ref, self, subject, user;
      msg = JSON.parse(event.data);
      if (msg.type === 'done') {
        self = $("input[data-chalid='" + msg.subject + "']");
        self.prop('checked', msg.data);
        self.parent().next().css('text-decoration', msg.data ? 'line-through' : 'none');
        if (msg.data) {
          self.parent().parent().addClass('done');
        } else {
          self.parent().parent().removeClass('done');
        }
        return updateProgress();
      } else if (msg.type === 'assign') {
        self = $(".labels[data-chalid='" + msg.subject + "']");
        if (msg.data[1]) {
          self.append($("
").append($("").addClass("label").attr("data-name", msg.data[0].name).text(msg.data[0].name)));
        } else {
          self.find(".label[data-name='" + msg.data[0].name + "']").parent().remove();
        }
        return $(".assignment-count[data-chalid='" + msg.subject + "']").text(self.first().find('.label').length);
      } else if (msg.type === 'ctfmodification') {
        return $('#ctfmodification').fadeIn(500);
      } else if (msg.type === 'login') {
        $('#userlist').append($("
").text(msg.data));
        return $('#usercount').text($('#userlist').children('li').length);
      } else if (msg.type === 'logout') {
        $("#userlist li:contains('" + msg.data + "')").remove();
        $('#usercount').text($('#userlist').children('li').length);
        return $(".active-user[data-name='" + msg.name + "']").remove;
      } else if (msg.type === 'fileupload' || msg.type === 'filedeletion') {
        if ((msg.data + "files") === window.currentPage) {
          current = window.currentPage;
          window.currentPage = null;
          $(".contentlink[href='#" + current + "']").click();
        }
        subject = $(".contentlink[href='#" + msg.data + "files']");
        if (msg.filecount > 0) {
          subject.children('i').removeClass('icon-folder-close').addClass('icon-folder-open');
        } else {
          subject.children('i').removeClass('icon-folder-open').addClass('icon-folder-close');
        }
        return subject.nextAll('sup').text(msg.filecount);
      } else if (msg.type === 'setactive') {
        $(".active-user[data-name='" + msg.name + "']").remove();
        if (msg.challenge !== void 0) {
          return $("#activeUsers" + msg.challenge).append($('').addClass('active-user').css('background-color', msg.color).attr('data-name', msg.name).text(msg.name));
        }
      } else if (msg.type === 'chat') {
        self = $('#chats');
        ref = msg.data;
        for (i = 0, len = ref.length; i < len; i++) {
          msgData = ref[i];
          user = msgData.name ? msgData.name : msgData.user;
          self.append($("
").css("width", "100%").append($("").css("width", "100%").append($("").addClass("label label-default").css("background-color", msgData.color).text(user)).append($("
").css("display", "inline").text(" " + msgData.message))).append($("").attr("valign", "top").css("padding-right", "1px").append($("").text(msgData.time.substring(11, 19)))));
        }
        if ($("#chat-scroll").prop('checked')) {
          return $(".chat-body").animate({
            scrollTop: $(".chat-body").prop("scrollHeight")
          });
        }
      } else {
        return alert(event.data);
      }
    };
  };
  window.onbeforeunload = function() {
    window.preventSocketAlert = true;
  };
  sessid = $.cookie('ctfpad');
  if ($.cookie('ctfpad_hide') === void 0) {
    $.cookie('ctfpad_hide', 'false');
  }
  updateProgress = function() {
    var d, score, totalScore;
    d = $('.challenge.done').length / $('.challenge').length;
    $('#progress').css('width', (d * 100) + "%");
    $('#progress').siblings('span').text(($('.challenge.done').length) + " / " + ($('.challenge').length));
    totalScore = 0;
    score = 0;
    $('.challenge').each(function() {
      totalScore += parseInt($(this).attr('data-chalpoints'));
      if ($(this).hasClass('done')) {
        return score += parseInt($(this).attr('data-chalpoints'));
      }
    });
    $('#scoreprogress').css('width', ((score / totalScore) * 100) + "%");
    $('#scoreprogress').siblings('span').text(score + " / " + totalScore);
    return $('.category').each(function() {
      var cat, done;
      cat = $(this).attr('data-category');
      done = $(this).siblings(".done[data-category='" + cat + "']").length;
      return $(this).find('.done-count').text(done);
    });
  };
  updateProgress();
  window.uploads = [];
  window.upload_refresh = function(remove) {
    var i, len, progress, ref, total_prog, total_size, upload;
    if (remove) {
      window.uploads.splice(window.uploads.indexOf(remove), 1);
      if (window.uploads.length === 0) {
        $('#uploadbutton').hide();
        return;
      }
    }
    total_size = total_prog = 0;
    ref = window.uploads;
    for (i = 0, len = ref.length; i < len; i++) {
      upload = ref[i];
      total_size += upload.file.size;
      total_prog += upload.progress;
    }
    progress = parseInt(total_prog / total_size * 100, 10);
    return $('#uploadprogress').text(progress + "% / " + window.uploads.length + " files");
  };
  window.upload_handler_send = function(e, data) {
    if (window.uploads.length === 0) {
      $('#uploadbutton').show();
    }
    data.context = {
      file: data.files[0],
      progress: 0
    };
    window.uploads.push(data.context);
    return window.upload_refresh();
  };
  window.upload_handler_done = function(e, data) {
    return window.upload_refresh(data.context);
  };
  window.upload_handler_fail = function(e, data) {
    window.upload_refresh(data.context);
    return alert("Upload failed: " + data.errorThrown);
  };
  window.upload_handler_progress = function(e, data) {
    data.context.progress = data.loaded;
    return window.upload_refresh();
  };
  $('.contentlink').click(function() {
    var chalid, m, page;
    page = $(this).attr('href').replace('#', '');
    if (window.currentPage !== page) {
      if (m = /^(ctf|challenge)(.+)files$/.exec(page)) {
        $('#content').html("");
        $.get("/files/" + m[1] + "/" + m[2], function(data) {
          var ref, url;
          $('#content').html(data);
          url = "/upload/" + m[1] + "/" + m[2];
          return $('#fileupload').fileupload({
            url: url,
            dataType: 'json',
            send: window.upload_handler_send,
            done: window.upload_handler_done,
            fail: window.upload_handler_fail,
            progress: window.upload_handler_progress
          }).prop('disabled', !$.support.fileInput).parent().addClass((ref = $.support.fileInput) != null ? ref : {
            undefined: 'disabled'
          });
        });
      } else {
        $('#content').pad({
          'padId': page,
          color: window.user.color
        });
      }
      $(".highlighted").removeClass("highlighted");
      $(this).parents(".highlightable").addClass("highlighted");
      chalid = $(this).parents(".highlightable").attr("data-challengeid");
      if (chalid !== void 0) {
        sock.send(JSON.stringify({
          type: 'setactive',
          subject: parseInt(chalid)
        }));
      }
      return window.currentPage = page;
    }
  });
  $("input[type='checkbox']").change(function() {
    $(this).parent().next().css('text-decoration', this.checked ? 'line-through' : 'none');
    return sock.send(JSON.stringify({
      type: 'done',
      subject: parseInt($(this).attr('data-chalid')),
      data: this.checked
    }));
  });
  $('.assignments').popover({
    html: true,
    content: function() {
      return $(this).parent().find('.popover-content').html();
    }
  }).click(function(e) {
    $('.assignments').not(this).popover('hide');
    $(this).popover('toggle');
    return e.stopPropagation();
  });
  $('html').click(function() {
    return $('.assignments').popover('hide');
  });
  $('.scoreboard-toggle').popover({
    html: true,
    content: function() {
      $.get('/scoreboard', function(ans) {
        return $('#scoreboard').html(ans);
      }, 'html');
      return 'loading...';
    }
  });
  $('body').delegate('.btn-assign', 'click', function() {
    return sock.send(JSON.stringify({
      type: 'assign',
      subject: parseInt($(this).attr('data-chalid'))
    }));
  });
  $('body').delegate('.add-challenge', 'click', function() {
    var a;
    a = $(this).parent().clone();
    a.find('input').val('').removeClass('hide');
    $(this).parent().after(a);
    if (a.hasClass('dummy')) {
      a.removeClass('dummy');
      return $(this).parent().remove();
    }
  });
  $('body').delegate('.remove-challenge', 'click', function() {
    if ($('.category-formgroup').length > 1) {
      return $(this).parent().remove();
    }
  });
  $('body').delegate('.deletefile', 'click', function() {
    var fileid, filename;
    fileid = $(this).attr('data-id');
    filename = $(this).attr('data-name');
    $('#deletefilemodal .alert').removeClass('alert-success alert-error').hide();
    $('#deletefilename').text(filename);
    $('#deletefilebtnno').text('no');
    $('#deletefilebtnyes').show();
    $('#deletefilemodal').data('fileid', fileid).modal('show');
    return false;
  });
  $('body').delegate('.btn-chat', 'click', function() {
    var mymessage;
    mymessage = $('.form-chat-send').val();
    $('.form-chat-send').val("");
    return sock.send(JSON.stringify({
      type: 'chat',
      message: mymessage
    }));
  });
  $('body').delegate('.form-chat-send', 'keypress', function(event) {
    var keycode, mymessage;
    keycode = event.keyCode ? event.keyCode : event.which;
    if (keycode === 13 || keycode === '13') {
      mymessage = $('.form-chat-send').val();
      $('.form-chat-send').val("");
      return sock.send(JSON.stringify({
        type: 'chat',
        message: mymessage
      }));
    }
  });
  $('#hidefinished').click(function() {
    if (!$(this).hasClass('active')) {
      $('head').append('');
      return $.cookie('ctfpad_hide', 'true');
    } else {
      $('#hidefinishedcss').remove();
      return $.cookie('ctfpad_hide', 'false');
    }
  });
  if ($.cookie('ctfpad_hide') === 'true') {
    $('#hidefinished').click();
  }
  window.newctf = function() {
    var l, newctf;
    l = $('#ctfform').serializeArray();
    newctf = {
      title: l.shift().value,
      challenges: []
    };
    while (l.length !== 0) {
      newctf.challenges.push({
        'title': l.shift().value,
        'category': l.shift().value,
        'points': parseInt(l.shift().value)
      });
    }
    sock.send(JSON.stringify({
      type: 'newctf',
      data: newctf
    }));
    $('#ctfmodal').modal('hide');
    $('#ctfform').find('input').val('');
    return document.location = '/scope/latest';
  };
  window.ajaxPost = function(url, data, cb) {
    if (data == null) {
      data = null;
    }
    return $.ajax;
  };
  window.changepw = function() {
    return $.ajax({
      url: '/changepassword',
      type: 'post',
      data: $('#passwordform').serialize(),
      dataType: 'json',
      headers: {
        'x-session-id': $.cookie('ctfpad')
      },
      success: function(ans) {
        $('#passwordmodal .alert').removeClass('alert-success alert-error');
        if (ans.success) {
          $('#passwordmodal .alert').addClass('alert-success').text('your password has been changed');
        } else {
          $('#passwordmodal .alert').addClass('alert-error').text(ans.error);
        }
        return $('#passwordmodal .alert').show();
      }
    });
  };
  window.newapikey = function() {
    return $.ajax({
      url: '/newapikey',
      type: 'post',
      dataType: 'text',
      headers: {
        'x-session-id': $.cookie('ctfpad')
      },
      success: function(apikey) {
        if (apikey) {
          return $('#apikey').text(apikey);
        }
      }
    });
  };
  window.modifyctf = function() {
    var ctf, l;
    l = $('#ctfmodifyform').serializeArray();
    ctf = {
      ctf: window.current.id,
      challenges: []
    };
    while (l.length !== 0) {
      ctf.challenges.push({
        'id': parseInt(l.shift().value),
        'title': l.shift().value,
        'category': l.shift().value,
        'points': parseInt(l.shift().value)
      });
    }
    sock.send(JSON.stringify({
      type: 'modifyctf',
      data: ctf
    }));
    $('#ctfmodifymodal').modal('hide');
    return setTimeout(function() {
      return document.location.reload();
    }, 500);
  };
  return window.delete_file_confirmed = function() {
    return $.get('/delete_file/' + $('#deletefilemodal').data('fileid'), function(ans) {
      $('#deletefilemodal .alert').removeClass('alert-success alert-error');
      if (ans.success) {
        $('#deletefilemodal .alert').addClass('alert-success').text('file has been deleted');
      } else {
        $('#deletefilemodal .alert').addClass('alert-error').text(ans.error);
      }
      $('#deletefilemodal .alert').show();
      $('#deletefilebtnno').text('close');
      return $('#deletefilebtnyes').hide();
    }, 'json');
  };
});


text:
FROM nginx

MAINTAINER Evan Brown <evanbrown@google.com>

RUN rm /etc/nginx/conf.d/*.conf

WORKDIR /usr/src

ADD start.sh /usr/src/
ADD nginx/nginx.conf /etc/nginx/
ADD nginx/proxy*.conf /usr/src/

ENTRYPOINT ./start.sh


text:
class Endereco < ActiveRecord::Base
  belongs_to :enderecavel, :polymorphic => true
  belongs_to :municipio

  accepts_nested_attributes_for :municipio

  validates :logradouro, :presence => true
  validates :bairro,     :presence => true
  validates :cep,        :presence => true
  validates :municipio,  :presence => true

  def token_municipio
    if self.municipio
      Array(self.municipio).collect { |m| { :id => m.id, :name => "#{m.nome} - #{m.uf.sigla}" } }.to_json
    else
      nil
    end
  end

  def to_s
    complemento = !self.complemento.blank? ? "#{self.complemento}, " : ''
    municipio = self.municipio ? "#{self.municipio.nome} - #{self.municipio.uf.sigla}" : ''
    "#{self.logradouro} #{complemento}, #{self.bairro}, #{municipio}"
  end

end


text:
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/watchdog.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/of.h>
#include <mach/hardware.h>

/* WatchDog Timer - Chapter 23 Page 207 */

#define DEFAULT_HEARTBEAT 19
#define MAX_HEARTBEAT     60

/* Watchdog timer register set definition */
#define WDTIM_INT(p)     ((p) + 0x0)
#define WDTIM_CTRL(p)    ((p) + 0x4)
#define WDTIM_COUNTER(p) ((p) + 0x8)
#define WDTIM_MCTRL(p)   ((p) + 0xC)
#define WDTIM_MATCH0(p)  ((p) + 0x10)
#define WDTIM_EMR(p)     ((p) + 0x14)
#define WDTIM_PULSE(p)   ((p) + 0x18)
#define WDTIM_RES(p)     ((p) + 0x1C)

/* WDTIM_INT bit definitions */
#define MATCH_INT      1

/* WDTIM_CTRL bit definitions */
#define COUNT_ENAB     1
#define RESET_COUNT    (1 << 1)
#define DEBUG_EN       (1 << 2)

/* WDTIM_MCTRL bit definitions */
#define MR0_INT        1
#undef  RESET_COUNT0
#define RESET_COUNT0   (1 << 2)
#define STOP_COUNT0    (1 << 2)
#define M_RES1         (1 << 3)
#define M_RES2         (1 << 4)
#define RESFRC1        (1 << 5)
#define RESFRC2        (1 << 6)

/* WDTIM_EMR bit definitions */
#define EXT_MATCH0      1
#define MATCH_OUTPUT_HIGH (2 << 4)	/*a MATCH_CTRL setting */

/* WDTIM_RES bit definitions */
#define WDOG_RESET      1	/* read only */

#define WDOG_COUNTER_RATE 13000000	/*the counter clock is 13 MHz fixed */

static bool nowayout = WATCHDOG_NOWAYOUT;
static unsigned int heartbeat = DEFAULT_HEARTBEAT;

static DEFINE_SPINLOCK(io_lock);
static void __iomem	*wdt_base;
struct clk		*wdt_clk;

static int pnx4008_wdt_start(struct watchdog_device *wdd)
{
	spin_lock(&io_lock);

	/* stop counter, initiate counter reset */
	writel(RESET_COUNT, WDTIM_CTRL(wdt_base));
	/*wait for reset to complete. 100% guarantee event */
	while (readl(WDTIM_COUNTER(wdt_base)))
		cpu_relax();
	/* internal and external reset, stop after that */
	writel(M_RES2 | STOP_COUNT0 | RESET_COUNT0, WDTIM_MCTRL(wdt_base));
	/* configure match output */
	writel(MATCH_OUTPUT_HIGH, WDTIM_EMR(wdt_base));
	/* clear interrupt, just in case */
	writel(MATCH_INT, WDTIM_INT(wdt_base));
	/* the longest pulse period 65541/(13*10^6) seconds ~ 5 ms. */
	writel(0xFFFF, WDTIM_PULSE(wdt_base));
	writel(wdd->timeout * WDOG_COUNTER_RATE, WDTIM_MATCH0(wdt_base));
	/*enable counter, stop when debugger active */
	writel(COUNT_ENAB | DEBUG_EN, WDTIM_CTRL(wdt_base));

	spin_unlock(&io_lock);
	return 0;
}

static int pnx4008_wdt_stop(struct watchdog_device *wdd)
{
	spin_lock(&io_lock);

	writel(0, WDTIM_CTRL(wdt_base));	/*stop counter */

	spin_unlock(&io_lock);
	return 0;
}

static int pnx4008_wdt_set_timeout(struct watchdog_device *wdd,
				    unsigned int new_timeout)
{
	wdd->timeout = new_timeout;
	return 0;
}

static const struct watchdog_info pnx4008_wdt_ident = {
	.options = WDIOF_CARDRESET | WDIOF_MAGICCLOSE |
	    WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
	.identity = "PNX4008 Watchdog",
};

static const struct watchdog_ops pnx4008_wdt_ops = {
	.owner = THIS_MODULE,
	.start = pnx4008_wdt_start,
	.stop = pnx4008_wdt_stop,
	.set_timeout = pnx4008_wdt_set_timeout,
};

static struct watchdog_device pnx4008_wdd = {
	.info = &pnx4008_wdt_ident,
	.ops = &pnx4008_wdt_ops,
	.timeout = DEFAULT_HEARTBEAT,
	.min_timeout = 1,
	.max_timeout = MAX_HEARTBEAT,
};

static int pnx4008_wdt_probe(struct platform_device *pdev)
{
	struct resource *r;
	int ret = 0;

	watchdog_init_timeout(&pnx4008_wdd, heartbeat, &pdev->dev);

	r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	wdt_base = devm_ioremap_resource(&pdev->dev, r);
	if (IS_ERR(wdt_base))
		return PTR_ERR(wdt_base);

	wdt_clk = devm_clk_get(&pdev->dev, NULL);
	if (IS_ERR(wdt_clk))
		return PTR_ERR(wdt_clk);

	ret = clk_enable(wdt_clk);
	if (ret)
		return ret;

	pnx4008_wdd.bootstatus = (readl(WDTIM_RES(wdt_base)) & WDOG_RESET) ?
			WDIOF_CARDRESET : 0;
	pnx4008_wdd.parent = &pdev->dev;
	watchdog_set_nowayout(&pnx4008_wdd, nowayout);

	pnx4008_wdt_stop(&pnx4008_wdd);	/* disable for now */

	ret = watchdog_register_device(&pnx4008_wdd);
	if (ret < 0) {
		dev_err(&pdev->dev, "cannot register watchdog device\n");
		goto disable_clk;
	}

	dev_info(&pdev->dev, "PNX4008 Watchdog Timer: heartbeat %d sec\n",
		 pnx4008_wdd.timeout);

	return 0;

disable_clk:
	clk_disable(wdt_clk);
	return ret;
}

static int pnx4008_wdt_remove(struct platform_device *pdev)
{
	watchdog_unregister_device(&pnx4008_wdd);

	clk_disable(wdt_clk);

	return 0;
}

#ifdef CONFIG_OF
static const struct of_device_id pnx4008_wdt_match[] = {
	{ .compatible = "nxp,pnx4008-wdt" },
	{ }
};
MODULE_DEVICE_TABLE(of, pnx4008_wdt_match);
#endif

static struct platform_driver platform_wdt_driver = {
	.driver = {
		.name = "pnx4008-watchdog",
		.of_match_table = of_match_ptr(pnx4008_wdt_match),
	},
	.probe = pnx4008_wdt_probe,
	.remove = pnx4008_wdt_remove,
};

module_platform_driver(platform_wdt_driver);

MODULE_AUTHOR("MontaVista Software, Inc. <source@mvista.com>");
MODULE_AUTHOR("Wolfram Sang <kernel@pengutronix.de>");
MODULE_DESCRIPTION("PNX4008 Watchdog Driver");

module_param(heartbeat, uint, 0);
MODULE_PARM_DESC(heartbeat,
		 "Watchdog heartbeat period in seconds from 1 to "
		 __MODULE_STRING(MAX_HEARTBEAT) ", default "
		 __MODULE_STRING(DEFAULT_HEARTBEAT));

module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout,
		 "Set to 1 to keep watchdog running after device release");

MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pnx4008-watchdog");