text:
import logging
from tg import tmpl_context as c
from datetime import datetime

from allura.app import Application, SitemapEntry
from allura.lib import helpers as h
from allura import model as M
from allura.eventslistener import EventsListener
from .model.stats import UserStats
from .controllers.userstats import ForgeUserStatsController

from forgeuserstats import version

from ming.orm import session

log = logging.getLogger(__name__)

class UserStatsListener(EventsListener):

    def newArtifact(self, art_type, art_datetime, project, user):
        stats = user.stats
        if not stats:
            stats = UserStats.create(user)
        stats.addNewArtifact(art_type, art_datetime, project)

    def modifiedArtifact(self, art_type, art_datetime, project, user):
        stats = user.stats
        if not stats:
            stats = UserStats.create(user)

        stats.addModifiedArtifact(art_type, art_datetime, project)

    def newUser(self, user):
        UserStats.create(user)

    def ticketEvent(self, event_type, ticket, project, user):
        if user is None:
            return
        stats = user.stats
        if not stats:
            stats = UserStats.create(user)

        if event_type == "assigned":
            stats.addAssignedTicket(ticket.mod_date, project)
        elif event_type == "revoked":
            stats.addRevokedTicket(ticket.mod_date, project)
        elif event_type == "closed":
            stats.addClosedTicket(
                ticket.created_date, ticket.mod_date, project)

    def newCommit(self, newcommit, project, user):
        stats = user.stats
        if not stats:
            stats = UserStats.create(user)

        stats.addCommit(newcommit, datetime.utcnow(), project)

    def addUserLogin(self, user):
        stats = user.stats
        if not stats:
            stats = UserStats.create(user)

        stats.addLogin(datetime.utcnow())

    def newOrganization(self, organization):
        pass

class ForgeUserStatsApp(Application):
    __version__ = version.__version__
    tool_label = 'UserStats'
    default_mount_label = 'Stats'
    default_mount_point = 'stats'
    permissions = ['configure', 'read', 'write',
                   'unmoderated_post', 'post', 'moderate', 'admin']
    permissions_desc = {
        'read': 'View user stats.',
        'admin': 'Toggle stats visibility.',
    }
    max_instances = 0
    has_notifications = False
    ordinal = 15
    config_options = Application.config_options
    default_external_feeds = []
    icons = {
        24: 'userstats/images/stats_24.png',
        32: 'userstats/images/stats_32.png',
        48: 'userstats/images/stats_48.png'
    }
    root = ForgeUserStatsController()

    def __init__(self, project, config):
        Application.__init__(self, project, config)
        role_admin = M.ProjectRole.by_name('Admin', project)._id
        role_anon = M.ProjectRole.by_name('*anonymous', project)._id
        self.config.acl = [
            M.ACE.allow(role_anon, 'read'),
            M.ACE.allow(role_admin, 'admin')]

    def main_menu(self):
        return [SitemapEntry(self.config.options.mount_label, '.')]

    def is_visible_to(self, user):
        # we don't work with user subprojects
        return c.project.is_root

    @property
    @h.exceptionless([], log)
    def sitemap(self):
        menu_id = self.config.options.mount_label
        with h.push_config(c, app=self):
            return [
                SitemapEntry(menu_id, '.')[self.sidebar_menu()]]

    @property
    def show_discussion(self):
        if 'show_discussion' in self.config.options:
            return self.config.options['show_discussion']
        else:
            return True

    @h.exceptionless([], log)
    def sidebar_menu(self):
        base = c.app.url
        links = [SitemapEntry('Overview', base),
                 SitemapEntry('Commits', base + 'commits'),
                 SitemapEntry('Artifacts', base + 'artifacts'),
                 SitemapEntry('Tickets', base + 'tickets')]
        return links

    def admin_menu(self):
        links = [SitemapEntry(
            'Settings', c.project.url() + 'userstats/settings')]
        return links

    def install(self, project):
        # It doesn't make any sense to install the tool twice on the same
        # project therefore, if it already exists, it doesn't install it
        # a second time.
        for tool in project.app_configs:
            if tool.tool_name == 'userstats':
                if self.config.options.mount_point != tool.options.mount_point:
                    project.uninstall_app(self.config.options.mount_point)
                    return

    def uninstall(self, project):
        self.config.delete()
        session(self.config).flush()


text:
package by.vorokhobko.arrays;

import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
* Test.
*
* @author Evgeny Vorokhobko (vorokhobko2011@yandex.ru).
* @since 28.12.2016.
* @version 1.
*/

public class Duplicate2Test {
    /**
     * @Test.
     */
    @Test
	public void whenTheArrayOfTwoDuplicate() {
		final Duplicate2 d = new Duplicate2();
		final String[] values = new String[]{"Привет", "Привет", "Мир", "Мир"};
		final String[] result = d.deleteDuplicate(values);
		final String[] expect = new String[]{"Привет", "Мир"};
		assertThat(result, is(expect));
	}
}

redpajama_set_name: RedPajamaGithub


text:
const chaiAsPromised = require('chai-as-promised');
const chai = require('chai');
chai.use(chaiAsPromised);

global.sinon = require('sinon');
global.expect = chai.expect;
global.should = chai.should();
global.Promise = require('bluebird');


text:
def vertical(hfile):

    """Reads psipred output .ss2 file.
    @param  hfile   psipred .ss2 file
    @return secondary structure string.
    """

    result = ''
    for l in hfile:
        if l.startswith('#'):
            continue
        if not l.strip():
            continue
        l_arr = l.strip().split()
        result += l_arr[2]
    return result

def horizontal(hfile):

    """Reads psipred output .horiz file.
    @param  hfile   psipred .horiz file
    @return secondary structure string.
    """

    result = ''
    for line in hfile:
        line_arr = line.strip().split(' ')
        if line_arr[0] == 'Pred:' and len(line_arr) > 1:
            result += line_arr[1]
    return result

def horizontal_conf(hfile):

    """Reads psipred output .horiz file.
    @param  hfile   psipred .horiz file
    @return secondary structure string.
    """

    result = ''
    for line in hfile:
        line_arr = line.strip().split(' ')
        if line_arr[0] == 'Conf:' and len(line_arr) > 1:
            result += line_arr[1]
    return result

def horizontal_seq(hfile):

    """Reads psipred output .horiz file.
    @param  hfile   psipred .horiz file
    @return amino acid sequence.
    """

    result = ''
    for line in hfile:
        line_arr = line.strip().split(' ')
        if line_arr[0] == 'AA:':
            result += line_arr[1]
    return result


text: package webskins


text:
package me.chanjar.weixin.mp.bean;

import lombok.Data;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

import java.io.Serializable;

/**
 * 语义理解查询用对象
 * <p>
 * http://mp.weixin.qq.com/wiki/index.php?title=语义理解
 *
 * @author Daniel Qian
 */
@Data
public class WxMpSemanticQuery implements Serializable {
  private static final long serialVersionUID = 7685873048199870690L;

  private String query;
  private String category;
  private Float latitude;
  private Float longitude;
  private String city;
  private String region;
  private String appid;
  private String uid;

  public String toJson() {
    return WxMpGsonBuilder.create().toJson(this);
  }

}


text:
#include "InstancedShader.h"
#include "Renderer.h"

InstancedShader::InstancedShader(const ShaderPtr& sharedShader)
        : Shader(sharedShader->getAttributes(), sharedShader->getUniformNames()),
          mSharedShader(sharedShader) {
}

InstancedShader::~InstancedShader() {
}

void InstancedShader::begin() {
    assert(mSharedShader && !mCurrentShader);
    if (!mSharedShader || mCurrentShader) {
        return;
    }
    mCurrentShader = true;
    mSharedShader->begin();
    updateState();
}

void InstancedShader::end() {
    assert(mSharedShader && mCurrentShader);
    if (!mSharedShader || !mCurrentShader) {
        return;
    }
    mCurrentShader = false;
    mSharedShader->end();
}

bool InstancedShader::isCurrent() const {
    return mCurrentShader;
}

bool InstancedShader::isValid() const {
    return mSharedShader->isValid();
}

bool InstancedShader::isCompiled() const {
    return mSharedShader->isCompiled();
}

GLuint InstancedShader::getProgramId() const {
    assert(mSharedShader && mSharedShader->isValid());
    return mSharedShader->getProgramId();
}

void InstancedShader::compile() {
    mSharedShader->compile();
}

std::string InstancedShader::getErrorLog() const {
    return mSharedShader->getErrorLog();
}

int InstancedShader::getAttributeLocation(int index) const {
    assert(mSharedShader && mSharedShader->isValid());
    return mSharedShader->getAttributeLocation(index);
}

int InstancedShader::getUniformLocation(int index) const {
    assert(mSharedShader && mSharedShader->isValid());
    return mSharedShader->getUniformLocation(index);
}

void InstancedShader::updateState() {
}

void InstancedShader::setIndexedTexture(int index, int stage, const TexturePtr& value,
        TexturePtr* stateValue) {
    setIndexedUniform1i(index, false, stage, nullptr);
    if (stateValue) {
        *stateValue = value;
    }
    if (!isCurrent()) {
        return;
    }
    Renderer::getCurrent()->selectTexture(value, stage);
}


text:
using System.Text.RegularExpressions;

static class Extensions
{
    public static bool ContainsWholeWord(this string str, string word)
        => Regex.IsMatch(str, $@"\b{Regex.Escape(word)}\b", RegexOptions.CultureInvariant);
}


text:
$(document).ready(function() {
	var current = new Date();
	var month = current.getMonth() + 1;
	var day = current.getDate();
	var year = current.getFullYear();
	var date_str = month + "/" + day + "/" + year;
	$('#id_date').attr('value', date_str);
});


text:
package egovframework.com.sym.mnu.stm.service.impl;

import egovframework.com.cmm.ComDefaultVO;
import egovframework.com.cmm.service.impl.EgovComAbstractDAO;
import egovframework.com.sym.mnu.stm.service.SiteMapngVO;

import org.springframework.stereotype.Repository;
/**
 * 사이트맵 조회에 대한 DAO 클래스를 정의한다.
 * @author 개발환경 개발팀 이용
 * @since 2009.06.01
 * @version 1.0
 * @see
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자           수정내용
 *  -------    --------    ---------------------------
 *   2009.03.20  이  용          최초 생성
 *
 * </pre>
 */
@Repository("siteMapngDAO")
public class SiteMapngDAO extends EgovComAbstractDAO{

	/**
	 * 사이트맵 조회
	 * @param vo ComDefaultVO
	 * @return SiteMapngVO
	 * @exception Exception
	 */
	public SiteMapngVO selectSiteMapng(ComDefaultVO vo)throws Exception{
		return (SiteMapngVO)select("siteMapngDAO.selectSiteMapng_D", vo);
	}

	/**
	 * MapCreatId 조회
	 * @param vo ComDefaultVO
	 * @return String
	 * @exception Exception
	 */
	public String selectSiteMapngByMapCreatID(ComDefaultVO vo)throws Exception{
		return (String)select("siteMapngDAO.selectSiteMapngByMapCreatID", vo);
	}

}


text:
import scrapy

class SzuspiderItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass


text:
<!--
  Copyright 2016 Google Inc.

  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.
-->
<project>
  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <groupId>com.example.flexible</groupId>
  <artifactId>flexible-cloudsql</artifactId>

  <!--
    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>

<!-- [START gae_flex_mysql_properties] -->
  <properties>
<!--
    INSTANCE_CONNECTION_NAME from Cloud Console > SQL > Instance Details > Properties
    or `gcloud sql instances describe <instance> | grep connectionName`
-->
    <INSTANCE_CONNECTION_NAME>Project:Region:Instance</INSTANCE_CONNECTION_NAME>
    <user>root</user>
    <password>myPassword</password>
    <database>sqldemo</database>
<!-- [START_EXCLUDE] -->
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>

    <failOnMissingWebXml>false</failOnMissingWebXml> <!-- REQUIRED -->

    <jetty>9.4.44.v20210927</jetty>
<!-- [END_EXCLUDE] -->
    <sqlURL>jdbc:mysql://google/${database}?cloudSqlInstance=${INSTANCE_CONNECTION_NAME}&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=${user}&password=${password}&useSSL=false</sqlURL>
  </properties>
<!-- [END gae_flex_mysql_properties] -->

  <dependencies>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>2.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client-appengine</artifactId>
      <version>2.0.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client-servlet</artifactId>
      <version>2.0.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <type>jar</type>
      <scope>provided</scope>
    </dependency>
    <!-- [START gae_flex_mysql_dependencies] -->
    <dependency>                        <!-- http://dev.mysql.com/doc/connector-j/en/ -->
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.29</version>
    </dependency>
    <dependency>
      <groupId>com.google.cloud.sql</groupId>
      <artifactId>mysql-socket-factory-connector-j-6</artifactId>
      <version>1.2.1</version>
    </dependency>
    <!-- [END gae_flex_mysql_dependencies] -->
  </dependencies>
  <build>
    <!-- [START gae_flex_mysql_resources] -->
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
    <!-- [END gae_flex_mysql_resources] -->
    <!-- for hot reload of the web application -->
    <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.3.2</version>
      </plugin>
      <plugin>
        <groupId>com.google.cloud.tools</groupId>
        <artifactId>appengine-maven-plugin</artifactId>
        <version>2.4.4</version>
        <configuration>
          <projectId>GCLOUD_CONFIG</projectId>
          <version>GCLOUD_CONFIG</version>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>${jetty}</version>
      </plugin>
    </plugins>
  </build>
</project>


text:
@implementation oneView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        UILabel *orderLabel = [[UILabel alloc]init];
        orderLabel.text = @"我的订单";
        orderLabel.font = [UIFont systemFontOfSize:14];
        orderLabel.textColor = [UIColor blackColor];

        UILabel *fullLabel = [[UILabel alloc]init];
        fullLabel.text = @"查看全部订单";
        fullLabel.font = [UIFont systemFontOfSize:14];
        fullLabel.textColor = [UIColor colorWithRed:150/255.0 green:150/255.0 blue:150/255.0 alpha:1.0];;

        UIImageView *arrowsImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_go"]];
        arrowsImg.userInteractionEnabled = YES;
        [self addSubview:orderLabel];
        [self addSubview:fullLabel];
        [self addSubview:arrowsImg];

        [orderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self).offset(20);
            make.centerY.equalTo(self);
        }];
        [arrowsImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self).offset(-5);
            make.centerY.equalTo(self);
        }];
        [fullLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(arrowsImg).offset(-10);
            make.centerY.equalTo(self);
        }];
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clikOne)];
        [self addGestureRecognizer:tap1];

    }
    return self;
}
-(void)clikOne{

    NSNotification *oneview = [NSNotification notificationWithName:@"oneview" object:nil];

    [[NSNotificationCenter defaultCenter] postNotification:oneview];

    if ([self.delegate respondsToSelector:@selector(oneView:)]) {

        [self.delegate oneView:self];
    }

}
@end


text:
import tests.model_control.test_ozone_custom_models_enabled as testmod

testmod.build_model( ['RelativeDifference'] , ['ConstantTrend'] , ['Seasonal_Hour'] , ['NoAR'] );


text:
<?php declare(strict_types=1);

namespace Darvin\AdminBundle\Event\Crud\Controller;

/**
 * CRUD controller events
 */
final class CrudControllerEvents
{
    public const STARTED = 'darvin_admin.crud.controller.started';
}


text:
package de.bitdroid.academy.server.utils;

import org.apache.commons.lang.exception.ExceptionUtils;

public final class Log {

	public static void info(String msg) {
		log("INFO", msg);
	}

	public static void info(String msg, Throwable throwable) {
		info(format(msg, throwable));
	}

	public static void warn(String msg) {
		log("WARN", msg);
	}

	public static void warn(String msg, Throwable throwable) {
		warn(format(msg, throwable));
	}

	public static void error(String msg) {
		log("ERROR", msg);
	}

	public static void error(String msg, Throwable throwable) {
		error(format(msg, throwable));
	}

	private static String format(String msg, Throwable throwable) {
		return msg + " -- " + ExceptionUtils.getStackTrace(throwable);
	}

	private static void log(String tag, String msg) {
		System.out.println(tag + ": " + msg);
	}
}


text:
using System;
using Microsoft.VisualStudio.Text;

namespace CoCo.Test.Common
{
    internal class TextVersion : ITextVersion2
    {
        private readonly TextImageVersion _textImageVersion;

        public TextVersion(ITextBuffer textBuffer, TextImageVersion imageVersion)
        {
            TextBuffer = textBuffer ?? throw new ArgumentNullException(nameof(textBuffer));
            _textImageVersion = imageVersion ?? throw new ArgumentNullException(nameof(imageVersion));
        }

        public int VersionNumber => ImageVersion.VersionNumber;

        public int ReiteratedVersionNumber => _textImageVersion.ReiteratedVersionNumber;

        public ITextVersion Next { get; }

        public INormalizedTextChangeCollection Changes => ImageVersion.Changes;

        public int Length => ImageVersion.Length;

        public ITextBuffer TextBuffer { get; }

        public ITextImageVersion ImageVersion => _textImageVersion;

        // TODO: isn't completed
        public ITrackingPoint CreateTrackingPoint(int position, PointTrackingMode trackingMode) =>
            CreateTrackingPoint(position, trackingMode, TrackingFidelityMode.UndoRedo);

        public ITrackingPoint CreateTrackingPoint(int position, PointTrackingMode trackingMode, TrackingFidelityMode trackingFidelity)
        {
            throw new NotImplementedException();
        }

        public ITrackingSpan CreateTrackingSpan(int start, int length, SpanTrackingMode trackingMode) =>
            CreateTrackingSpan(new Span(start, length), trackingMode);

        public ITrackingSpan CreateTrackingSpan(int start, int length, SpanTrackingMode trackingMode, TrackingFidelityMode trackingFidelity) =>
            CreateTrackingSpan(new Span(start, length), trackingMode, trackingFidelity);

        public ITrackingSpan CreateTrackingSpan(Span span, SpanTrackingMode trackingMode)
        {
            throw new NotImplementedException();
        }

        public ITrackingSpan CreateTrackingSpan(Span span, SpanTrackingMode trackingMode, TrackingFidelityMode trackingFidelity)
        {
            throw new NotImplementedException();
        }

        public ITrackingSpan CreateCustomTrackingSpan(Span span, TrackingFidelityMode trackingFidelity, object customState, CustomTrackToVersion behavior)
        {
            if (behavior == null) throw new ArgumentNullException(nameof(behavior));
            throw new NotImplementedException();
        }
    }
}


text:
package version

import (
	"testing"

	"github.com/cloudflare/cfssl/cli"
)

func TestVersionString(t *testing.T) {
	version := versionString()
	if version != "1.2.0" {
		t.Fatal("version string is not returned correctly")
	}
}

func TestVersionMain(t *testing.T) {
	args := []string{"cfssl", "version"}
	err := versionMain(args, cli.Config{})
	if err != nil {
		t.Fatal("version main failed")
	}
}


text:
/**
 * Created by rtorres on 9/25/16.
 */
import * as Q from 'q';
import * as Cookies from 'js-cookie';

import Deferred = Q.Deferred;

import {IArea} from 'areaInterfaces';
import {UrlSingleton} from '../singletons/urlSingleton';
import {AuthSingleton} from '../singletons/authSingleton';

export function getCookie(cname: string): string {
    return Cookies.get(cname);
}

export function deleteCookie(cname: string): void {
    Cookies.remove(cname);
}

export function getSession(name: string): string {
    return sessionStorage.getItem(name);
}

export function setSession(name: string, value: string): void{
    return sessionStorage.setItem(name, value);
}

export function deleteSession(name: string): void {
    return sessionStorage.removeItem(name);
}

export function clearSession(): void {
    return sessionStorage.clear();
}

export function getAreas():  Promise<IArea[]> {
    let deferred: Deferred<IArea[]> = Q.defer<IArea[]>(),
        user: any = {},
        ajaxSettings: any = {
        'url': UrlSingleton.getInstance().getApiAreas(),
        'method': 'GET',
        'headers': {
            'Authorization': AuthSingleton.getInstance().getToken()
        }};

        $.ajax(ajaxSettings)
        .then((response: any) => {
            deferred.resolve(response);
        })
        .fail((error: Error) => {
            deferred.reject(error);
        });

    return deferred.promise;
}