file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
AutoRoom.ts | import {setupRoomMemoryForMining} from '../../Common';
import {OperationProcess} from '../../lib/process/OperationProcess';
class OperationAutoLayoutRoom extends OperationProcess<IThaeOperationMemory> {
public run() | sourceID: s.id,
}, 11).pid);
this.missions.push(kernel.startProcess<IThaeMiningCreepMissionMemory>(MissionImageNames.MINING_CARRIER, {
creeps: [],
homeRoom: this.room.name,
room: this.room.name,
sourceID: s.id,
}, 11).pid);
... | {
this.log.debug(`Running Auto Layout Room Operation for { ${this.memory.room} }`);
if (!this.room || !this.room.controller || !this.room.controller.my) {
if (!this.memory.deadTime) {
this.memory.deadTime = Game.time;
}
if (this.memory.deadTime + OP_DEAD_LIMIT <= Game.time) {
... | identifier_body |
weather.py | from .logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot.utils.pos_tagger import POSTagger
import re
import forecastio
class WeatherLogicAdapter(LogicAdapter):
"""
A logic adapter that returns information regarding the weather and
the forecast for a specific location.... |
return ""
def get_weather(self, latitude, longitude):
"""
Returns the weather for a given latitude and longitude.
"""
# @TODO: Find some way to suppress the warnings generated by this.
forecast = forecastio.load_forecast(self.forecastio_api_key, latitude, longitude... | if "longitude=" in token:
return re.sub("longitude=", "", token) | conditional_block |
weather.py | from .logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot.utils.pos_tagger import POSTagger
import re
import forecastio
class WeatherLogicAdapter(LogicAdapter):
"""
A logic adapter that returns information regarding the weather and
the forecast for a specific location.... |
def get_longitude(self, user_input):
"""
Returns the longitude extracted from the input.
"""
for token in self.tagger.tokenize(user_input):
if "longitude=" in token:
return re.sub("longitude=", "", token)
return ""
def get_weather(self, lat... | """
Returns the latitude extracted from the input.
"""
for token in self.tagger.tokenize(user_input):
if "latitude=" in token:
return re.sub("latitude=", "", token)
return "" | identifier_body |
weather.py | from .logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot.utils.pos_tagger import POSTagger
import re
import forecastio
class WeatherLogicAdapter(LogicAdapter):
"""
A logic adapter that returns information regarding the weather and
the forecast for a specific location.... | """
Returns the forecast for a location (using latitude and longitude).
"""
user_input = statement.text.lower()
if "weather" not in user_input:
return 0, Statement("")
latitude = self.get_latitude(user_input)
longitude = self.get_longitude(user_input)... | def process(self, statement): | random_line_split |
weather.py | from .logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot.utils.pos_tagger import POSTagger
import re
import forecastio
class WeatherLogicAdapter(LogicAdapter):
"""
A logic adapter that returns information regarding the weather and
the forecast for a specific location.... | (self, latitude, longitude):
"""
Returns the weather for a given latitude and longitude.
"""
# @TODO: Find some way to suppress the warnings generated by this.
forecast = forecastio.load_forecast(self.forecastio_api_key, latitude, longitude)
return forecast.hourly().summ... | get_weather | identifier_name |
test_authentication.py | # coding=utf-8
import logging
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.conf import settings
from accounts.authentication import PersonaAuthenticationBackend, PERSONA_VERIFY_URL
__author__ = 'peter'
User = get_user_model()
@patch('a... | (self):
backend = PersonaAuthenticationBackend()
other_user = User(email='other@user.com')
other_user.username = 'otheruser'
other_user.save()
desired_user = User.objects.create(email='a@b.com')
found_user = backend.get_user('a@b.com')
self.assertEqual(found_user,... | test_gets_user_by_email | identifier_name |
test_authentication.py | # coding=utf-8
import logging
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.conf import settings
from accounts.authentication import PersonaAuthenticationBackend, PERSONA_VERIFY_URL
|
@patch('accounts.authentication.requests.post')
class AuthenticateTest(TestCase):
def setUp(self):
self.backend = PersonaAuthenticationBackend()
user = User(email='other@user.com')
user.username = 'otheruser'
user.save()
def test_sends_assertion_to_mozilla_with_domain(self, moc... | __author__ = 'peter'
User = get_user_model()
| random_line_split |
test_authentication.py | # coding=utf-8
import logging
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.conf import settings
from accounts.authentication import PersonaAuthenticationBackend, PERSONA_VERIFY_URL
__author__ = 'peter'
User = get_user_model()
@patch('a... |
class GetUserTest(TestCase):
def test_gets_user_by_email(self):
backend = PersonaAuthenticationBackend()
other_user = User(email='other@user.com')
other_user.username = 'otheruser'
other_user.save()
desired_user = User.objects.create(email='a@b.com')
found_user = b... | response_json = {
'status': 'not okay', 'reason': 'eg, audience mismatch'
}
mock_post.return_value.ok = True
mock_post.return_value.json.return_value = response_json
logger = logging.getLogger('accounts.authentication')
with patch.object(logger, 'warning') as mock_log... | identifier_body |
git.ts | import { executeCommand, assertFileExists } from './util';
import { log } from './log';
import * as fs from 'fs';
import { includes } from 'lodash';
export function setOrigin(repoPath: string, url: string): Promise<any> {
return getRemotes(repoPath)
.then((remotes: string[]) => {
log.debug(`remote repos:`,... | (path: string): Promise<boolean> {
const gitStatus = executeCommand(
'git',
['status', '--porcelain=v2'],
path
).then(stdout => {
return stdout === '';
});
return gitStatus;
}
| isClean | identifier_name |
git.ts | import { executeCommand, assertFileExists } from './util';
import { log } from './log';
import * as fs from 'fs';
import { includes } from 'lodash';
export function setOrigin(repoPath: string, url: string): Promise<any> {
return getRemotes(repoPath)
.then((remotes: string[]) => {
log.debug(`remote repos:`,... |
});
}
function gitStatus(path: string): Promise<string>;
function gitStatus(path: string, file: string): Promise<string>;
function gitStatus(path: string, file?: string): Promise<string> {
const args = ['status', '--porcelain=v2'];
if (file) {
args.push(file);
}
return executeCommand('git', args, path... | {
throw new Error(`unsupported status ${status}`);
} | conditional_block |
git.ts | import { executeCommand, assertFileExists } from './util';
import { log } from './log';
import * as fs from 'fs';
import { includes } from 'lodash';
export function setOrigin(repoPath: string, url: string): Promise<any> {
return getRemotes(repoPath)
.then((remotes: string[]) => {
log.debug(`remote repos:`,... | .then(() => gitStatus(repoPath, fileInRepo))
.then(status => {
if (!status) {
return;
}
if (status.startsWith('1') || status.startsWith('2')) {
return gitAdd(repoPath, fileInRepo).then(() =>
gitCommit(repoPath, 'backup')
);
} else {
throw new Err... | export function ensureFileIsCommited(
repoPath: string,
fileInRepo: string
): Promise<any> {
return ensureFileIsUnderVC(repoPath, fileInRepo) | random_line_split |
git.ts | import { executeCommand, assertFileExists } from './util';
import { log } from './log';
import * as fs from 'fs';
import { includes } from 'lodash';
export function setOrigin(repoPath: string, url: string): Promise<any> {
return getRemotes(repoPath)
.then((remotes: string[]) => {
log.debug(`remote repos:`,... |
function gitStatus(path: string): Promise<string>;
function gitStatus(path: string, file: string): Promise<string>;
function gitStatus(path: string, file?: string): Promise<string> {
const args = ['status', '--porcelain=v2'];
if (file) {
args.push(file);
}
return executeCommand('git', args, path).then(res... | {
return ensureFileIsUnderVC(repoPath, fileInRepo)
.then(() => gitStatus(repoPath, fileInRepo))
.then(status => {
if (!status) {
return;
}
if (status.startsWith('1') || status.startsWith('2')) {
return gitAdd(repoPath, fileInRepo).then(() =>
gitCommit(repoPath, 'bac... | identifier_body |
ParserBase.ts | ("awayjs-core/lib/events/TimerEvent");
import ParserUtils = require("awayjs-core/lib/parsers/ParserUtils");
import ResourceDependency = require("awayjs-core/lib/parsers/ResourceDependency");
import ByteArray = require("awayjs-core/lib/utils/ByteArray");
import TextureUtils = require("awayjs-core/lib/utils/Tex... | (b:boolean)
{
this._parsingFailure = b;
}
public get parsingFailure():boolean
{
return this._parsingFailure;
}
public get parsingPaused():boolean
{
return this._parsingPaused;
}
public get parsingComplete():boolean
{
return this._parsingComplete;
}
public set materialMode(newMaterialMode:number)... | parsingFailure | identifier_name |
ParserBase.ts | ("awayjs-core/lib/events/TimerEvent");
import ParserUtils = require("awayjs-core/lib/parsers/ParserUtils");
import ResourceDependency = require("awayjs-core/lib/parsers/ResourceDependency");
import ByteArray = require("awayjs-core/lib/utils/ByteArray");
import TextureUtils = require("awayjs-core/lib/utils/Tex... |
public get data():any
{
return this._data;
}
/**
* The data format of the file data to be parsed. Options are <code>URLLoaderDataFormat.BINARY</code>, <code>URLLoaderDataFormat.ARRAY_BUFFER</code>, <code>URLLoaderDataFormat.BLOB</code>, <code>URLLoaderDataFormat.VARIABLES</code> or <code>URLLoaderDataFormat.... | {
return this._materialMode;
} | identifier_body |
ParserBase.ts | ("awayjs-core/lib/events/TimerEvent");
import ParserUtils = require("awayjs-core/lib/parsers/ParserUtils");
import ResourceDependency = require("awayjs-core/lib/parsers/ResourceDependency");
import ByteArray = require("awayjs-core/lib/utils/ByteArray");
import TextureUtils = require("awayjs-core/lib/utils/Tex... | }
/**
* The data format of the file data to be parsed. Options are <code>URLLoaderDataFormat.BINARY</code>, <code>URLLoaderDataFormat.ARRAY_BUFFER</code>, <code>URLLoaderDataFormat.BLOB</code>, <code>URLLoaderDataFormat.VARIABLES</code> or <code>URLLoaderDataFormat.TEXT</code>.
*/
public get dataFormat():string... |
public get data():any
{
return this._data; | random_line_split |
connections.py | #!/usr/bin/env python
# -*- coding: iso8859-1 -*-
#
# connections.py - network connections statistics
#
# Copyright (c) 2005-2007, Carlos Rodrigues <cefrodrigues@mail.telepac.pt>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License (version 2) ... | else:
proto_other += 1
f.close()
rrdtool.update(self.database,
"--template", "proto_tcp:proto_udp:proto_other",
"N:%d:%d:%d" % (proto_tcp, proto_udp, proto_other))
def make_graphs(self):
"""G... | random_line_split | |
connections.py | #!/usr/bin/env python
# -*- coding: iso8859-1 -*-
#
# connections.py - network connections statistics
#
# Copyright (c) 2005-2007, Carlos Rodrigues <cefrodrigues@mail.telepac.pt>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License (version 2) ... | (StatsComponent):
"""Network Connections Statistics."""
def __init__(self):
self.name = "connections"
if not os.path.exists(DATA_SOURCE):
fail(self.name, "maybe the kernel module 'ip_conntrack' isn't loaded.")
raise StatsException(DATA_SOURCE + " does not exist")
... | NetworkConnections | identifier_name |
connections.py | #!/usr/bin/env python
# -*- coding: iso8859-1 -*-
#
# connections.py - network connections statistics
#
# Copyright (c) 2005-2007, Carlos Rodrigues <cefrodrigues@mail.telepac.pt>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License (version 2) ... |
def info(self):
"""Return some information about the component,
as a tuple: (name, title, description)"""
return (self.name, self.title, self.description)
def update(self):
"""Update the historical data."""
f = open(DATA_SOURCE, "r")
proto_tcp = 0
p... | refresh = properties["refresh"]
heartbeat = refresh * 2
rrdtool.create(self.database,
"--step", "%d" % refresh,
"DS:proto_tcp:GAUGE:%d:0:U" % heartbeat,
"DS:proto_udp:GAUGE:%d:0:U" % heartbeat,
... | conditional_block |
connections.py | #!/usr/bin/env python
# -*- coding: iso8859-1 -*-
#
# connections.py - network connections statistics
#
# Copyright (c) 2005-2007, Carlos Rodrigues <cefrodrigues@mail.telepac.pt>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License (version 2) ... | "--color", "BACK%s" % background,
"--color", "SHADEA%s" % border,
"--color", "SHADEB%s" % border,
"DEF:proto_tcp=%s:proto_tcp:AVERAGE" % self.database,
"DEF:proto_udp=%s:proto_udp:AVERAGE" %... | """Generate the daily, weekly and monthly graphics."""
height = str(properties["height"])
width = str(properties["width"])
refresh = properties["refresh"]
background = properties["background"]
border = properties["border"]
for interval in ("1day", "1week", "1month", "1ye... | identifier_body |
dummy.py | ax
import jax.numpy as jnp
import blackjax.rwmh as mh
import matplotlib.pyplot as plt
import pyprobml_utils as pml
from sklearn.datasets import make_biclusters
from jax import random
from jax.scipy.optimize import minimize
from jax_cosmo.scipy import integrate
from functools import partial
def sigmoid(z): return jnp.... | random_line_split | ||
dummy.py | ax_cosmo.scipy import integrate
from functools import partial
def sigmoid(z): return jnp.exp(z) / (1 + jnp.exp(z))
def log_sigmoid(z): return z - jnp.log(1 + jnp.exp(z))
def inference_loop(rng_key, kernel, initial_state, num_samples):
def one_step(state, rng_key):
state, _ = kernel(rng_key, state)
... | .errorbar(timesteps, w_online, jnp.sqrt(w_err_online), c=c, label=f"$w_{i}$ online")
ax.axhline(y=w_batch, c=lcolors[i], linestyle="--", label=f"$w_{i}$ batch (mcmc)")
ax.fill_between(timesteps, w_batch - w_batch_err, w_batch + w_batch_err, color=c, alpha=0.1)
a | conditional_block | |
dummy.py | pip install jax_cosmo
# Author: Gerardo Durán-Martín (@gerdm)
import superimport
import jax
import jax.numpy as jnp
import blackjax.rwmh as mh
import matplotlib.pyplot as plt
import pyprobml_utils as pml
from sklearn.datasets import make_biclusters
from jax import random
from jax.scipy.optimize import minimize
from ... |
# Posterior estimation
delta_m = mt - m_t_cond
delta_v = vt - v_t_cond
a = Phi_t * tau_t_cond / jnp.power(Phi_t * tau_t_cond, 2).sum()
mu_t = mu_t_cond + a * delta_m
tau_t = tau_t_cond + a ** 2 * delta_v
return (mu_t, tau_t), (mu_t, tau_t)
def plot_posterior_predictive(ax, X, Z, title, c... | _t, tau_t = state
Phi_t, y_t = xs
mu_t_cond = mu_t
tau_t_cond = tau_t + q
# prior predictive distribution
m_t_cond = (Phi_t * mu_t_cond).sum()
v_t_cond = (Phi_t ** 2 * tau_t_cond).sum()
v_t_cond_sqrt = jnp.sqrt(v_t_cond)
# Moment-matched Gaussian approximation elements
Zt = integ... | identifier_body |
dummy.py | pip install jax_cosmo
# Author: Gerardo Durán-Martín (@gerdm)
import superimport
import jax
import jax.numpy as jnp
import blackjax.rwmh as mh
import matplotlib.pyplot as plt
import pyprobml_utils as pml
from sklearn.datasets import make_biclusters
from jax import random
from jax.scipy.optimize import minimize
from ... | ): return z - jnp.log(1 + jnp.exp(z))
def inference_loop(rng_key, kernel, initial_state, num_samples):
def one_step(state, rng_key):
state, _ = kernel(rng_key, state)
return state, state
keys = jax.random.split(rng_key, num_samples)
_, states = jax.lax.scan(one_step, initial_state, keys)
... | g_sigmoid(z | identifier_name |
karma.conf.js | // Karma configuration
// Generated on Sun Jun 26 2016 14:46:31 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '../..',
// frameworks to use
// available frameworks: https://npmjs.org/browse/key... | })
} | singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity | random_line_split |
test_asg.py | import troposphere.elasticloadbalancing as elb
from amazonia.classes.asg import Asg
from amazonia.classes.asg_config import AsgConfig
from amazonia.classes.block_devices_config import BlockDevicesConfig
from amazonia.classes.simple_scaling_policy_config import SimpleScalingPolicyConfig
from network_setup import get_net... | assert_equals(
asg.lc.IamInstanceProfile,
'arn:aws:iam::123456789:instance-profile/iam-instance-profile')
assert_is(type(asg.lc.UserData), Base64)
[assert_is(type(sg), Ref) for sg in asg.lc.SecurityGroups]
assert_equals(asg.cd_app.title, title + 'Asg' + 'Cda')
... | asg = create_asg(title)
assert_equals(asg.trop_asg.title, title + 'Asg')
assert_equals(asg.trop_asg.MinSize, 1)
assert_equals(asg.trop_asg.MaxSize, 2)
assert_equals(asg.trop_asg.resource['UpdatePolicy'].AutoScalingRollingUpdate.PauseTime, 'PT10M')
[assert_is(type(subnet_id), Ref)... | conditional_block |
test_asg.py | import troposphere.elasticloadbalancing as elb
from amazonia.classes.asg import Asg
from amazonia.classes.asg_config import AsgConfig
from amazonia.classes.block_devices_config import BlockDevicesConfig
from amazonia.classes.simple_scaling_policy_config import SimpleScalingPolicyConfig
from network_setup import get_net... | assert_list_equal(asg.trop_asg.NotificationConfigurations[0].NotificationTypes,
['autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR',
'autoscaling:EC2_INSTANCE_TERMINATE', 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR'])
assert_equa... | """
Tests correct structure of autoscaling group objects.
"""
global asg_config
asg_titles = ['simple', 'hard', 'harder', 'easy']
for title in asg_titles:
asg = create_asg(title)
assert_equals(asg.trop_asg.title, title + 'Asg')
assert_equals(asg.trop_asg.MinSize, 1)
... | identifier_body |
test_asg.py | import troposphere.elasticloadbalancing as elb
from amazonia.classes.asg import Asg
from amazonia.classes.asg_config import AsgConfig
from amazonia.classes.block_devices_config import BlockDevicesConfig
from amazonia.classes.simple_scaling_policy_config import SimpleScalingPolicyConfig
from network_setup import get_net... | ():
"""
Tests that an empty userdata is correctly handled
"""
global asg_config
asg_config.userdata = None
asg = create_asg('nouserdata')
assert_equals(asg.lc.UserData, '')
def create_asg(title):
"""
Helper function to create ASG Troposhpere object.
:param title: Title of au... | test_no_userdata | identifier_name |
test_asg.py | import troposphere.elasticloadbalancing as elb
from amazonia.classes.asg import Asg
from amazonia.classes.asg_config import AsgConfig
from amazonia.classes.block_devices_config import BlockDevicesConfig
from amazonia.classes.simple_scaling_policy_config import SimpleScalingPolicyConfig
from network_setup import get_net... |
def create_asg(title):
"""
Helper function to create ASG Troposhpere object.
:param title: Title of autoscaling group to create
:return: Troposphere object for single instance, security group and output
"""
global template, load_balancer, network_config, asg_config
asg = Asg(
title... |
assert_equals(asg.lc.UserData, '') | random_line_split |
index.transform.js | 'use strict';
var BigNumber = require('../../type/BigNumber');
var Range = require('../../type/Range');
var Index = require('../../type/Index');
var isNumber = require('../../util/number').isNumber;
/**
* Attach a transform function to math.index
* Adds a property transform containing the transform function.
*
* ... |
else if (isNumber(arg)) {
arg--;
}
else if (arg instanceof BigNumber) {
arg = arg.toNumber() - 1;
}
else {
throw new TypeError('Ranges must be a Number or Range');
}
args[i] = arg;
}
var res = new Index();
Index.apply(res, args);
retur... | {
arg.start--;
arg.end -= (arg.step > 0 ? 0 : 2);
} | conditional_block |
index.transform.js | 'use strict';
var BigNumber = require('../../type/BigNumber');
var Range = require('../../type/Range');
var Index = require('../../type/Index');
var isNumber = require('../../util/number').isNumber;
/**
* Attach a transform function to math.index
* Adds a property transform containing the transform function.
*
* ... | var arg = arguments[i];
// change from one-based to zero based, and convert BigNumber to number
if (arg instanceof Range) {
arg.start--;
arg.end -= (arg.step > 0 ? 0 : 2);
}
else if (isNumber(arg)) {
arg--;
}
else if (arg instanceof BigNumber) {
... | var transform = function () {
var args = [];
for (var i = 0, ii = arguments.length; i < ii; i++) { | random_line_split |
packageDocumentHelper.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return Promise.resolve([this.newSnippetCompletionItem({
label: localize('languageSpecificEditorSettings', "Language specific editor settings"),
documentation: localize('languageSpecificEditorSettingsDescription', "Override editor settings for language"),
snippet,
range
})]);
}
if (location.... | {
range = new vscode.Range(new vscode.Position(range.start.line, range.start.character + 1), range.end);
snippet = snippet.substring(1);
} | conditional_block |
packageDocumentHelper.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
| {
const item = new vscode.CompletionItem(o.label);
item.kind = vscode.CompletionItemKind.Value;
item.documentation = o.documentation;
item.insertText = new vscode.SnippetString(o.snippet);
item.range = o.range;
return item;
} | identifier_body |
packageDocumentHelper.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | snippet = snippet.substring(1);
}
return Promise.resolve([this.newSnippetCompletionItem({
label: localize('languageSpecificEditorSettings', "Language specific editor settings"),
documentation: localize('languageSpecificEditorSettingsDescription', "Override editor settings for language"),
snippet,... | // hence exclude the starting quote from the snippet and the range
// ending quote gets replaced
if (text && text.startsWith('"')) {
range = new vscode.Range(new vscode.Position(range.start.line, range.start.character + 1), range.end); | random_line_split |
packageDocumentHelper.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (private document: vscode.TextDocument) { }
public provideCompletionItems(position: vscode.Position, token: vscode.CancellationToken): vscode.ProviderResult<vscode.CompletionItem[]> {
const location = getLocation(this.document.getText(), this.document.offsetAt(position));
if (location.path.length >= 2 && locatio... | constructor | identifier_name |
models.py | from markdown import markdown
from django.db import models
from django.core.urlresolvers import reverse
class Tag(models.Model):
"""
A subject-matter tag for blog posts
"""
slug = models.CharField(max_length=200, unique=True)
name = models.SlugField(max_length=200, unique=True)
def __str__(s... | ordering = ('title', 'date', 'body') |
def body_html( self ):
return markdown(self.body)
class Meta: | random_line_split |
models.py | from markdown import markdown
from django.db import models
from django.core.urlresolvers import reverse
class Tag(models.Model):
"""
A subject-matter tag for blog posts
"""
slug = models.CharField(max_length=200, unique=True)
name = models.SlugField(max_length=200, unique=True)
def __str__(s... | :
ordering = ('title', 'date', 'body')
| Meta | identifier_name |
models.py | from markdown import markdown
from django.db import models
from django.core.urlresolvers import reverse
class Tag(models.Model):
"""
A subject-matter tag for blog posts
"""
slug = models.CharField(max_length=200, unique=True)
name = models.SlugField(max_length=200, unique=True)
def __str__(s... |
def get_absolute_url(self):
return reverse('post', args=(self.slug,))
def teaser(self):
return ' '.join([self.body[:100], '...'])
def body_html( self ):
return markdown(self.body)
class Meta:
ordering = ('title', 'date', 'body')
| return self.title | identifier_body |
z-angular-ui-zoom.js | /**
* Created by LiYunpeng on 1/8/16.
*/
(function() {
'use strict';
angular.module("z.angular.zoom",[])
.directive('zZoom',['$timeout',function($timeout) {
return {
restrict:'A',
scope: {
},
controller:function($scope) {
},
link: function(scope,element,... | tTo + scope.gap;
//鼠标滚轮期望值大于原有大小,则以原有大小为准
if(scope.currentTo>1) {
scope.currentTo = 1;
}
zoomTo = scope.currentTo;
} else {
//缩小,推滚轮
var widthTo = 1;
var heightTo = 1;
if(element.... | scope.currentTo = scope.curren | conditional_block |
z-angular-ui-zoom.js | /**
* Created by LiYunpeng on 1/8/16.
*/
(function() {
'use strict';
angular.module("z.angular.zoom",[])
.directive('zZoom',['$timeout',function($timeout) {
return {
restrict:'A',
scope: {
},
controller:function($scope) {
},
link: function(scope,element,... | return;
}
scope.currentTo = scope.currentTo + scope.gap;
//鼠标滚轮期望值大于原有大小,则以原有大小为准
if(scope.currentTo>1) {
scope.currentTo = 1;
}
zoomTo = scope.currentTo;
} else {
//缩小,推滚轮
... | //放大最多不超过原有尺寸
if(scope.currentTo>=1) { | random_line_split |
ScrewTurnPageFile.js | var path = require('path')
ScrewTurnPageFile.LATEST = -1
ScrewTurnPageFile.compare = compare
ScrewTurnPageFile.prototype.isLatest = isLatest
ScrewTurnPageFile.prototype.compareTo = compareTo
function ScrewTurnPageFile(filename) {
var revision = getRevision(filename)
, title = getTitle(filename)
this.__... | , title = offset >= 0 ? basename.substr(0, offset) : basename
return title
}
function isLatest() {
return this.revision === ScrewTurnPageFile.LATEST
}
function compareTo(item) {
return compare(this, item)
}
function compare(a, b) {
if(a.title < b.title)
return -1
else if(a.title > ... | function getTitle(filename) {
var basename = path.basename(filename, 'cs')
, offset = basename.indexOf('.') | random_line_split |
ScrewTurnPageFile.js | var path = require('path')
ScrewTurnPageFile.LATEST = -1
ScrewTurnPageFile.compare = compare
ScrewTurnPageFile.prototype.isLatest = isLatest
ScrewTurnPageFile.prototype.compareTo = compareTo
function ScrewTurnPageFile(filename) {
var revision = getRevision(filename)
, title = getTitle(filename)
this.__... |
function isLatest() {
return this.revision === ScrewTurnPageFile.LATEST
}
function compareTo(item) {
return compare(this, item)
}
function compare(a, b) {
if(a.title < b.title)
return -1
else if(a.title > b.title)
return 1
else if(a.revision === ScrewTurnPageFile.LATEST)
... | {
var basename = path.basename(filename, 'cs')
, offset = basename.indexOf('.')
, title = offset >= 0 ? basename.substr(0, offset) : basename
return title
} | identifier_body |
ScrewTurnPageFile.js | var path = require('path')
ScrewTurnPageFile.LATEST = -1
ScrewTurnPageFile.compare = compare
ScrewTurnPageFile.prototype.isLatest = isLatest
ScrewTurnPageFile.prototype.compareTo = compareTo
function ScrewTurnPageFile(filename) {
var revision = getRevision(filename)
, title = getTitle(filename)
this.__... | (filename) {
var basename = path.basename(filename, '.cs')
, offset = basename.indexOf('.')
, revision = offset >= 0 ? parseInt(basename.substr(offset + 1), 10) : ScrewTurnPageFile.LATEST
return revision
}
function getTitle(filename) {
var basename = path.basename(filename, 'cs')
, offse... | getRevision | identifier_name |
test_lightgbm.py | import unittest
import lightgbm as lgb
import pandas as pd
from common import gpu_test
class TestLightgbm(unittest.TestCase):
# Based on the "simple_example" from their documentation:
# https://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/simple_example.py
def test_cpu(self):
l... | 'boosting_type': 'gbdt',
'objective': 'regression',
'metric': {'l2', 'auc'},
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'force_row_wise': True,
... | params = {
'task': 'train', | random_line_split |
test_lightgbm.py | import unittest
import lightgbm as lgb
import pandas as pd
from common import gpu_test
class TestLightgbm(unittest.TestCase):
# Based on the "simple_example" from their documentation:
# https://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/simple_example.py
def test_cpu(self):
| valid_sets=lgb_eval,
early_stopping_rounds=1)
self.assertEqual(1, gbm.best_iteration)
@gpu_test
def test_gpu(self):
lgb_train, lgb_eval = self.load_datasets()
params = {
'boosting_type': 'gbdt',
'objectiv... | lgb_train, lgb_eval = self.load_datasets()
params = {
'task': 'train',
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': {'l2', 'auc'},
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9,
'... | identifier_body |
test_lightgbm.py | import unittest
import lightgbm as lgb
import pandas as pd
from common import gpu_test
class TestLightgbm(unittest.TestCase):
# Based on the "simple_example" from their documentation:
# https://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/simple_example.py
def | (self):
lgb_train, lgb_eval = self.load_datasets()
params = {
'task': 'train',
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': {'l2', 'auc'},
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.... | test_cpu | identifier_name |
util.rs | use std::io::{Read, Seek, SeekFrom};
use std::str;
use error::Result;
pub static APE_PREAMBLE: &'static [u8] = b"APETAGEX";
static ID3V1_HEADER: &'static [u8] = b"TAG";
static LYRICS3V2_HEADER: &'static [u8] = b"LYRICS200";
/// Position of ID3v1 tag
pub const ID3V1_OFFSET: i64 = -128;
/// Number of bytes, which are... |
/// Returns the size of the Lyrics3 v2.00 tag or -1 if the tag does not exists.
/// See http://id3.org/Lyrics3v2 for more details.
pub fn probe_lyrics3v2<R: Read + Seek>(reader: &mut R) -> Result<i64> {
let capacity = LYRICS3V2_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek... | {
let capacity = ID3V1_HEADER.len();
let mut header = Vec::<u8>::with_capacity(capacity);
reader.seek(SeekFrom::End(ID3V1_OFFSET))?;
reader.take(capacity as u64).read_to_end(&mut header)?;
Ok(header == ID3V1_HEADER)
} | identifier_body |
util.rs | use std::io::{Read, Seek, SeekFrom};
use std::str;
use error::Result;
pub static APE_PREAMBLE: &'static [u8] = b"APETAGEX";
static ID3V1_HEADER: &'static [u8] = b"TAG";
static LYRICS3V2_HEADER: &'static [u8] = b"LYRICS200";
/// Position of ID3v1 tag
pub const ID3V1_OFFSET: i64 = -128;
/// Number of bytes, which are... | Ok(int_size + LYRICS3V2_SIZE + capacity as i64)
} else {
Ok(-1)
}
} | reader.take(LYRICS3V2_SIZE as u64).read_to_end(&mut buf)?;
let raw_size = str::from_utf8(&buf)?;
let int_size = raw_size.parse::<i64>()?; | random_line_split |
util.rs | use std::io::{Read, Seek, SeekFrom};
use std::str;
use error::Result;
pub static APE_PREAMBLE: &'static [u8] = b"APETAGEX";
static ID3V1_HEADER: &'static [u8] = b"TAG";
static LYRICS3V2_HEADER: &'static [u8] = b"LYRICS200";
/// Position of ID3v1 tag
pub const ID3V1_OFFSET: i64 = -128;
/// Number of bytes, which are... | <R: Read + Seek>(reader: &mut R, pos: SeekFrom) -> Result<bool> {
let capacity = APE_PREAMBLE.len();
let mut preamble = Vec::<u8>::with_capacity(capacity);
reader.seek(pos)?;
reader.take(capacity as u64).read_to_end(&mut preamble)?;
Ok(preamble == APE_PREAMBLE)
}
/// Whether ID3v1 tag exists
pub fn... | probe_ape | identifier_name |
util.rs | use std::io::{Read, Seek, SeekFrom};
use std::str;
use error::Result;
pub static APE_PREAMBLE: &'static [u8] = b"APETAGEX";
static ID3V1_HEADER: &'static [u8] = b"TAG";
static LYRICS3V2_HEADER: &'static [u8] = b"LYRICS200";
/// Position of ID3v1 tag
pub const ID3V1_OFFSET: i64 = -128;
/// Number of bytes, which are... | else {
Ok(-1)
}
}
| {
let mut buf = Vec::<u8>::with_capacity(LYRICS3V2_SIZE as usize);
reader.seek(SeekFrom::Current(-LYRICS3V2_SIZE))?;
reader.take(LYRICS3V2_SIZE as u64).read_to_end(&mut buf)?;
let raw_size = str::from_utf8(&buf)?;
let int_size = raw_size.parse::<i64>()?;
Ok(int_size + LYR... | conditional_block |
inputtext.cjs.js | primereact/utils');
var keyfilter = require('primereact/keyfilter');
var tooltip = require('primereact/tooltip');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
function _extends() {
... | else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.pro... | { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } | conditional_block |
inputtext.cjs.js | ereact/utils');
var keyfilter = require('primereact/keyfilter');
var tooltip = require('primereact/tooltip');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
function _extends() {
_ext... |
var InputTextComponent = /*#__PURE__*/function (_Component) {
_inherits(InputTextComponent, _Component);
var _super = _createSuper(InputTextComponent);
function InputTextComponent(props) {
var _this;
_classCallCheck(this, InputTextComponent);
_this = _super.call(this, props);
_this.onInput =... | { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } | identifier_body |
inputtext.cjs.js | primereact/utils');
var keyfilter = require('primereact/keyfilter');
var tooltip = require('primereact/tooltip');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
function | () {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};... | _extends | identifier_name |
inputtext.cjs.js | ': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, ... | forwardRef: ref
}, props));
}); | random_line_split | |
mappers.py | # Copyright 2011 OpenStack Foundation
# 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 requ... |
orm.mapper(models['instance'], Table('instances', meta, autoload=True))
orm.mapper(models['root_enabled_history'],
Table('root_enabled_history', meta, autoload=True))
orm.mapper(models['datastore'],
Table('datastores', meta, autoload=True))
orm.mapper(models['datastore_ve... | return | conditional_block |
mappers.py | # Copyright 2011 OpenStack Foundation
# 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 requ... | (model):
try:
orm.class_mapper(model)
return True
except orm_exc.UnmappedClassError:
return False
| mapping_exists | identifier_name |
mappers.py | # Copyright 2011 OpenStack Foundation
# 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 requ... | orm.mapper(models['agent_heartbeats'],
Table('agent_heartbeats', meta, autoload=True))
orm.mapper(models['quotas'],
Table('quotas', meta, autoload=True))
orm.mapper(models['quota_usages'],
Table('quota_usages', meta, autoload=True))
orm.mapper(models['reserva... | meta = MetaData()
meta.bind = engine
if mapping_exists(models['instance']):
return
orm.mapper(models['instance'], Table('instances', meta, autoload=True))
orm.mapper(models['root_enabled_history'],
Table('root_enabled_history', meta, autoload=True))
orm.mapper(models['datasto... | identifier_body |
mappers.py | # Copyright 2011 OpenStack Foundation
# 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 requ... | Table('capability_overrides', meta, autoload=True))
orm.mapper(models['service_statuses'],
Table('service_statuses', meta, autoload=True))
orm.mapper(models['dns_records'],
Table('dns_records', meta, autoload=True))
orm.mapper(models['agent_heartbeats'],
... | Table('capabilities', meta, autoload=True))
orm.mapper(models['capability_overrides'], | random_line_split |
find-less-files.js | const findLayoutDirectories = require('prefab/MaxBucknell_Prefab/lib/find-layout-directories');
const glob = require('glob');
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const magentoData = require('prefab/MaxBucknell_Prefab/lib/magento-data');
const cssPattern = /<css\s+src="(... | () {
return _.map(
findLayoutDirectories(),
(directory) => `${directory}/*.xml`
)
}
function findLessFiles()
{
const files = _.flatMap(
getGlobs(),
(g) => glob.sync(g)
);
const contents = _.map(
files,
(file) => fs.readFileSync(file, { encoding: 'ut... | getGlobs | identifier_name |
find-less-files.js | const findLayoutDirectories = require('prefab/MaxBucknell_Prefab/lib/find-layout-directories');
const glob = require('glob');
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const magentoData = require('prefab/MaxBucknell_Prefab/lib/magento-data');
const cssPattern = /<css\s+src="(... |
function findLessFiles()
{
const files = _.flatMap(
getGlobs(),
(g) => glob.sync(g)
);
const contents = _.map(
files,
(file) => fs.readFileSync(file, { encoding: 'utf-8' })
).join('\n');
const cssDeclarations = _.map(
contents.match(new RegExp(cssPattern, ... | {
return _.map(
findLayoutDirectories(),
(directory) => `${directory}/*.xml`
)
} | identifier_body |
find-less-files.js | const findLayoutDirectories = require('prefab/MaxBucknell_Prefab/lib/find-layout-directories');
const glob = require('glob');
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const magentoData = require('prefab/MaxBucknell_Prefab/lib/magento-data');
const cssPattern = /<css\s+src="(... | findLayoutDirectories(),
(directory) => `${directory}/*.xml`
)
}
function findLessFiles()
{
const files = _.flatMap(
getGlobs(),
(g) => glob.sync(g)
);
const contents = _.map(
files,
(file) => fs.readFileSync(file, { encoding: 'utf-8' })
).join('\n')... | const removePattern = /<remove\s+src="([^"]+)\.css"/;
function getGlobs () {
return _.map( | random_line_split |
keyboardmanager.ts | ': 67, 'd': 68, 'e': 69, 'f': 70, 'g': 71, 'h': 72, 'i': 73,
// 'j': 74, 'k': 75, 'l': 76, 'm': 77, 'n': 78, 'o': 79, 'p': 80, 'q': 81, 'r': 82,
// 's': 83, 't': 84, 'u': 85, 'v': 86, 'w': 87, 'x': 88, 'y': 89, 'z': 90,
// '1 !': 49, '2 @': 50, '3 #': 51, '4 $': 52, '5 %': 53, '6 ^': 54,
// '7 &': 55, '... | {
var that = this;
document.addEventListener("keydown", function(event: KeyboardEvent) {
var key = <number>(event.keyCode);
var isCtrl = <boolean>(event.ctrlKey);
var isAlt = <boolean>(event.altKey);
var isShift = <boolean>(event.shiftKey);
var keyStr = that._getKey(key);
... | identifier_body | |
keyboardmanager.ts | 59, '= +': 61, '- _': 173, 'meta': 224, 'minus': 173 };
var IE_MODIFIERS = {'; :': 186, '= +': 187, '- _': 189, 'minus': 189 };
/**
* A simple, concrete implementation of the keyboard manager interface.
*
* This takes a single argument 'keycodes', which should either be a string
* 'mozilla' or 'ie', to represent ... | (key: string): boolean {
if(key in this._keySequences) {
delete this._keySequences[key];
if(key in this._disabled) {
delete this._disabled[key];
}
return true;
}
return false;
}
/**
* TODO : clean this up, it's a bit too specific.
* 'shortcut adder' isn't a very go... | unregister | identifier_name |
keyboardmanager.ts | 59, '= +': 61, '- _': 173, 'meta': 224, 'minus': 173 };
var IE_MODIFIERS = {'; :': 186, '= +': 187, '- _': 189, 'minus': 189 };
/**
* A simple, concrete implementation of the keyboard manager interface.
*
* This takes a single argument 'keycodes', which should either be a string
* 'mozilla' or 'ie', to represent... | /**
* TODO!
*
*/
private _registerInputFromSignal(sender: IShortcutAdder, value: IKeySequence): void {
console.log | obj.shortcutAdded.connect(this._registerInputFromSignal, this);
return true;
}
| random_line_split |
mdquery.py | """
pybufrkit.mdquery
~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import
from __future__ import print_function
import logging
from pybufrkit.errors import MetadataExprParsingError
__all__ = ['MetadataExprParser', 'MetadataQuerent', 'METADATA_QUERY_INDICATOR_CHAR']
log = logging.getLogger(__file__)
METADA... | section_index, metadata_name = self.metadata_expr_parser.parse(metadata_expr)
sections = [s for s in bufr_message.sections
if s.get_metadata('index') == section_index or section_index is None]
for section in sections:
for parameter in section:
if parameter... | identifier_body | |
mdquery.py | """
pybufrkit.mdquery
~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import
from __future__ import print_function
import logging
from pybufrkit.errors import MetadataExprParsingError
__all__ = ['MetadataExprParser', 'MetadataQuerent', 'METADATA_QUERY_INDICATOR_CHAR']
log = logging.getLogger(__file__)
METADA... |
return None
| return parameter.value | conditional_block |
mdquery.py | """
pybufrkit.mdquery
~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import
from __future__ import print_function
import logging
from pybufrkit.errors import MetadataExprParsingError
__all__ = ['MetadataExprParser', 'MetadataQuerent', 'METADATA_QUERY_INDICATOR_CHAR']
log = logging.getLogger(__file__)
METADA... | (self, metadata_expr):
"""
:param str metadata_expr: The metadata expression string to parse
:return: A 2-element tuple of section index and metadata name
:rtype: (int, str)
"""
metadata_expr = metadata_expr.strip()
if metadata_expr[0] != METADATA_QUERY_INDICATOR... | parse | identifier_name |
mdquery.py | """
pybufrkit.mdquery | from __future__ import absolute_import
from __future__ import print_function
import logging
from pybufrkit.errors import MetadataExprParsingError
__all__ = ['MetadataExprParser', 'MetadataQuerent', 'METADATA_QUERY_INDICATOR_CHAR']
log = logging.getLogger(__file__)
METADATA_QUERY_INDICATOR_CHAR = '%'
class Metada... | ~~~~~~~~~~~~~~~~~
""" | random_line_split |
sentry_activity.py | """
sentry.templatetags.sentry_activity
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from django import template
from django.utils.html import esca... | else:
assignee_name = assignee.get_display_name()
action_str = action_str.format(user=assignee_name)
output = ''
if item.user:
user = item.user
name = user.name or user.email
output += '<span class="avatar"><img src="%s"></span> ' % (get_gravatar_url... | if not item.group:
# not implemented
return
try:
action_str = ACTIVITY_ACTION_STRINGS[item.type]
except KeyError:
logging.warning('Unknown activity type present: %s', item.type)
return
if item.type == Activity.CREATE_ISSUE:
action_str = action_str.format(**i... | identifier_body |
sentry_activity.py | """
sentry.templatetags.sentry_activity
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from django import template
from django.utils.html import esca... | if item.data['assignee'] == item.user_id:
assignee_name = 'themselves'
else:
try:
assignee = User.objects.get(id=item.data['assignee'])
except User.DoesNotExist:
assignee_name = 'unknown'
else:
assignee_name ... | random_line_split | |
sentry_activity.py | """
sentry.templatetags.sentry_activity
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from django import template
from django.utils.html import esca... |
output += ' <span class="sep">—</span> <span class="time">%s</span>' % (timesince(item.datetime),)
if item.type == Activity.NOTE:
output += linebreaks(urlize(escape(item.data['text'])))
return mark_safe(output)
| output += '<span class="avatar sentry"></span> '
output += 'The system %s' % (action_str,) | conditional_block |
sentry_activity.py | """
sentry.templatetags.sentry_activity
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from django import template
from django.utils.html import esca... | (item):
if not item.group:
# not implemented
return
try:
action_str = ACTIVITY_ACTION_STRINGS[item.type]
except KeyError:
logging.warning('Unknown activity type present: %s', item.type)
return
if item.type == Activity.CREATE_ISSUE:
action_str = action_st... | render_activity | identifier_name |
helpers.py | import datetime
import json
import time
import urllib
import urlparse
from django.contrib.humanize.templatetags import humanize
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template import defaultfilters
from django.utils.encoding import smart_str
from django.utils.html import strip_t... |
@register.function
def displayname(user):
"""Returns the best display name for the user"""
return user.first_name or user.email
| """Converts date/datetime to '%Y-%m-%d'"""
return dt.strftime('%Y-%m-%d') | identifier_body |
helpers.py | import datetime
import json
import time
import urllib
import urlparse
from django.contrib.humanize.templatetags import humanize
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template import defaultfilters
from django.utils.encoding import smart_str
from django.utils.html import strip_t... |
@register.function
def date_ago(days=0):
now = datetime.datetime.now()
diff = datetime.timedelta(days=days)
return (now - diff).date()
@register.function
def to_datetime_string(dt):
"""Converts date/datetime to '%Y-%m-%dT%H:%M:%S'"""
return dt.strftime('%Y-%m-%dT%H:%M:%S')
@register.function
... | return default | conditional_block |
helpers.py | import datetime
import json
import time
import urllib
import urlparse
from django.contrib.humanize.templatetags import humanize
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template import defaultfilters
from django.utils.encoding import smart_str
from django.utils.html import strip_t... | @register.function
def static(path):
return staticfiles_storage.url(path)
@register.filter
def naturaltime(*args):
return humanize.naturaltime(*args)
def json_handle_datetime(obj):
"""Convert a datetime obj to a number of milliseconds since epoch.
This uses milliseconds since this is probably going... | random_line_split | |
helpers.py | import datetime
import json
import time
import urllib
import urlparse
from django.contrib.humanize.templatetags import humanize
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template import defaultfilters
from django.utils.encoding import smart_str
from django.utils.html import strip_t... | (viewname, *args, **kwargs):
"""Helper for Django's ``reverse`` in templates."""
return reverse(viewname, args=args, kwargs=kwargs)
@register.filter
def urlparams(url_, hash=None, **query):
"""Add a fragment and/or query paramaters to a URL.
New query params will be appended to exising parameters, ex... | url | identifier_name |
index.tsx | import React, { HTMLProps } from 'react';
import Link from '@docusaurus/Link';
import CodeBlock from '@theme/CodeBlock';
import useThemeContext from '@theme/hooks/useThemeContext';
import Tabs from '@theme/Tabs';
import Heading from '@theme/Heading';
import TabItem from '@theme/TabItem';
import Zoom from 'react-medium-... | (e) {
console.error(e);
image = '';
}
} else {
image = src;
}
const withZoom = (children: React.ReactNode) => <Zoom>{children}</Zoom>;
return (
<figure className={styles.figure}>
{zoom && withZoom(<img src={image} alt={alt || 'No alt text.'} style={style} />)... | catch | identifier_name |
index.tsx | import React, { HTMLProps } from 'react';
import Link from '@docusaurus/Link';
import CodeBlock from '@theme/CodeBlock';
import useThemeContext from '@theme/hooks/useThemeContext';
import Tabs from '@theme/Tabs';
import Heading from '@theme/Heading';
import TabItem from '@theme/TabItem';
import Zoom from 'react-medium-... |
} else {
image = src;
}
const withZoom = (children: React.ReactNode) => <Zoom>{children}</Zoom>;
return (
<figure className={styles.figure}>
{zoom && withZoom(<img src={image} alt={alt || 'No alt text.'} style={style} />)}
{!zoom && <img src={image} alt={alt || 'No alt tex... | {
console.error(e);
image = '';
} | identifier_body |
index.tsx | import React, { HTMLProps } from 'react';
import Link from '@docusaurus/Link';
import CodeBlock from '@theme/CodeBlock';
import useThemeContext from '@theme/hooks/useThemeContext';
import Tabs from '@theme/Tabs';
import Heading from '@theme/Heading';
import TabItem from '@theme/TabItem';
import Zoom from 'react-medium-... | const entity = reference[name];
if (entity) {
return (
<a
{...props}
target="_blank"
rel="noreferrer"
href={`https://pub.dev/documentation/${entity.plugin}/${entity.version}/${entity.href}`}
/>
);
} else {
ret... |
export default {
a: (props: HTMLProps<HTMLAnchorElement>): JSX.Element => {
if (props.href && props.href.startsWith('!')) {
const name = props.href.replace('!', ''); | random_line_split |
index.tsx | import React, { HTMLProps } from 'react';
import Link from '@docusaurus/Link';
import CodeBlock from '@theme/CodeBlock';
import useThemeContext from '@theme/hooks/useThemeContext';
import Tabs from '@theme/Tabs';
import Heading from '@theme/Heading';
import TabItem from '@theme/TabItem';
import Zoom from 'react-medium-... |
return children as JSX.Element;
},
h1: Heading('h1'),
h2: Heading('h2'),
h3: Heading('h3'),
h4: Heading('h4'),
h5: Heading('h5'),
h6: Heading('h6'),
table: (props: HTMLProps<HTMLTableElement>): JSX.Element => (
<div style={{ overflowX: 'auto' }}>
<table {...props} />
</div>
),
... | {
return <CodeBlock {...props}>{getVersion(children)}</CodeBlock>;
} | conditional_block |
reaction.py | status = 0
msg = QApplication.translate("pychemqt", "undefined")
error = 0
kwargs = {"comp": [],
"coef": [],
"tipo": 0,
"fase": 0,
"key": 0,
"base": 0,
"customHr": False,
"Hr": 0.0,
"formula"... |
else:
self.Hr = unidades.MolarEnthalpy(calor_reaccion/abs(
self.coef[self.base]), "Jkmol")
self.error = round(check_estequiometria, 1)
self.state = self.error == 0
self.text = self._txt(self.formulas)
def conversion(self, corriente, T):
"""Calcul... | self.Hr = self.kwargs.get("Hr", 0) | conditional_block |
reaction.py | """
status = 0
msg = QApplication.translate("pychemqt", "undefined")
error = 0
kwargs = {"comp": [],
"coef": [],
"tipo": 0,
"fase": 0,
"key": 0,
"base": 0,
"customHr": False,
"Hr": 0.0,
"for... | avance = self.coef[indice]*corriente.caudalunitariomolar[indice]
Q_out = [corriente.caudalunitariomolar[i]+avance*self.coef[i] /
self.coef[indice] for i in range(len(self.componentes))]
h = unidades.Power(self.Hr*self.coef[self.base] /
... | self.coef[self.base] for i in range(len(self.componentes))]
minimo = min(Q_out)
if minimo < 0:
# The key component is not correct, redo the result
indice = Q_out.index(minimo) | random_line_split |
reaction.py | status = 0
msg = QApplication.translate("pychemqt", "undefined")
error = 0
kwargs = {"comp": [],
"coef": [],
"tipo": 0,
"fase": 0,
"key": 0,
"base": 0,
"customHr": False,
"Hr": 0.0,
"formula"... | (self, corriente, T):
"""Calculate reaction conversion
corriente: Corriente instance for reaction
T: Temperature of reaction"""
if self.tipo == 0:
# Material balance without equilibrium or kinetics considerations
alfa = self.kwargs["conversion"]
elif self... | conversion | identifier_name |
reaction.py | """
status = 0
msg = QApplication.translate("pychemqt", "undefined")
error = 0
kwargs = {"comp": [],
"coef": [],
"tipo": 0,
"fase": 0,
"key": 0,
"base": 0,
"customHr": False,
"Hr": 0.0,
"for... | conversion: conversion value for reaction with tipo=0
keq: equilibrium constant for reation with tipo=1
-it is float if it don't depend with temperature
-it is array if it depends with temperature
"""
self.kwargs = Reaction.kwargs.copy()
if... | """constructor, kwargs keys can be:
comp: array with index of reaction components
coef: array with stequiometric coefficient for each component
fase: Phase where reaction work
0 - Global
1 - Liquid
2 - Gas
key: I... | identifier_body |
abstract_label.ts | /*
The MIT License (MIT)
Copyright (c) 2015 University of East Anglia, Norwich, UK
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to ... |
compute_centroid(): Vector2 {
return null;
}
compute_bounding_box(): AABox {
return null;
};
contains_pointer_position(point: Vector2): boolean {
return false;
}
distance_to_point(point: Vector2): number {
retur... | {
if (this._selected) {
if (this._hover) {
return new Colour4(255, 0, 128, 1.0);
}
else {
return new Colour4(255, 0, 0, 1.0);
}
}
else {
if (this._hover) {
... | identifier_body |
abstract_label.ts | /*
The MIT License (MIT)
Copyright (c) 2015 University of East Anglia, Norwich, UK
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to ... |
}
else {
if (this._hover) {
return new Colour4(0, 255, 128, 1.0);
}
else {
return new Colour4(255, 255, 0, 1.0);
}
}
}
compute_centroid(): Vector2 {
r... | {
return new Colour4(255, 0, 0, 1.0);
} | conditional_block |
abstract_label.ts | /*
The MIT License (MIT)
Copyright (c) 2015 University of East Anglia, Norwich, UK
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to ... | () {
this.root_view._register_entity(this);
this._attached = true;
}
detach() {
this._attached = false;
this.root_view._unregister_entity(this);
}
destroy() {
if (this.parent_entity !== null) {
this.parent_enti... | attach | identifier_name |
abstract_label.ts | /*
The MIT License (MIT)
Copyright (c) 2015 University of East Anglia, Norwich, UK
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to ... | };
_outline_colour(): Colour4 {
if (this._selected) {
if (this._hover) {
return new Colour4(255, 0, 128, 1.0);
}
else {
return new Colour4(255, 0, 0, 1.0);
}
}
els... | random_line_split | |
login.component.ts | import { Component, ViewEncapsulation } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router, Route } from '@angular/router';
@Component({
selector: 'login',
encapsulation: ViewEncapsulation.None,
styles: [require('./login.scss')],
template:... | {
if (this.email.value == 'amc_lap@163.com') {
console.log("登陆成功!");
localStorage.setItem("userName", this.email.value);
// this.router.navigateByUrl('/cloudlink');
this.router.navigateByUrl('/cloudlink');
console.log(this.router);
console.log("转向成功!");
}
... | conditional_block | |
login.component.ts | import { Component, ViewEncapsulation } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router, Route } from '@angular/router';
@Component({
selector: 'login',
encapsulation: ViewEncapsulation.None,
styles: [require('./login.scss')],
template:... | (fb: FormBuilder, public router: Router) {
this.form = fb.group({
'email': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
});
this.email = this.form.controls['email'];
this.passwo... | constructor | identifier_name |
login.component.ts | import { Component, ViewEncapsulation } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router, Route } from '@angular/router';
@Component({
selector: 'login',
encapsulation: ViewEncapsulation.None,
styles: [require('./login.scss')],
template:... | this.form = fb.group({
'email': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
});
this.email = this.form.controls['email'];
this.password = this.form.controls['password'];
}
... | public password: AbstractControl;
public submitted: boolean = false;
constructor(fb: FormBuilder, public router: Router) { | random_line_split |
dotfiles.py | import logging
import tarfile
import tempfile
import os
import fabric.api
import fabric.operations
import cloudenvy.envy
class Dotfiles(cloudenvy.envy.Command):
def _build_subparser(self, subparsers):
help_str = 'Upload dotfiles from your local machine to an Envy.'
subparser = subparsers.add_pa... |
fabric.operations.put(temp_tar, '~/dotfiles.tar')
fabric.operations.run('tar -xvf ~/dotfiles.tar')
else:
logging.error('Could not determine IP.')
| path = os.path.expanduser('~/%s' % dotfile)
if os.path.exists(path):
if not os.path.islink(path):
archive.add(path, arcname=dotfile) | conditional_block |
dotfiles.py | import logging
import tarfile
import tempfile
import os
import fabric.api
import fabric.operations
import cloudenvy.envy
class Dotfiles(cloudenvy.envy.Command):
def _build_subparser(self, subparsers):
|
def run(self, config, args):
envy = cloudenvy.envy.Envy(config)
if envy.ip():
host_string = '%s@%s' % (envy.remote_user, envy.ip())
temp_tar = tempfile.NamedTemporaryFile(delete=True)
with fabric.api.settings(host_string=host_string):
if args.... | help_str = 'Upload dotfiles from your local machine to an Envy.'
subparser = subparsers.add_parser('dotfiles', help=help_str,
description=help_str)
subparser.set_defaults(func=self.run)
subparser.add_argument('-n', '--name', action='store', default='',
... | identifier_body |
dotfiles.py | import logging
import tarfile
import tempfile
import os
import fabric.api
import fabric.operations
import cloudenvy.envy
class Dotfiles(cloudenvy.envy.Command):
def _build_subparser(self, subparsers):
help_str = 'Upload dotfiles from your local machine to an Envy.'
subparser = subparsers.add_pa... | with fabric.api.settings(host_string=host_string):
if args.files:
dotfiles = args.files.split(',')
else:
dotfiles = config['defaults']['dotfiles'].split(',')
dotfiles = [dotfile.strip() for dotfile in dotfiles]
... | random_line_split | |
dotfiles.py | import logging
import tarfile
import tempfile
import os
import fabric.api
import fabric.operations
import cloudenvy.envy
class Dotfiles(cloudenvy.envy.Command):
def | (self, subparsers):
help_str = 'Upload dotfiles from your local machine to an Envy.'
subparser = subparsers.add_parser('dotfiles', help=help_str,
description=help_str)
subparser.set_defaults(func=self.run)
subparser.add_argument('-n', '--name', a... | _build_subparser | identifier_name |
index.tsx | import * as React from 'react';
import { cloneElement } from 'react';
import { polyfill } from 'react-lifecycles-compat';
import RcTooltip from 'rc-tooltip';
import classNames from 'classnames';
import getPlacements, { AdjustOverflow, PlacementsConfig } from './placements';
import Button from '../button/index';
export... |
getPlacements() {
const { builtinPlacements, arrowPointAtCenter, autoAdjustOverflow } = this.props;
return builtinPlacements || getPlacements({
arrowPointAtCenter,
verticalArrowShift: 8,
autoAdjustOverflow,
});
}
isHoverTrigger() {
const { trigger } = this.props;
if (!trig... | {
return this.tooltip.getPopupDomNode();
} | identifier_body |
index.tsx | import * as React from 'react';
import { cloneElement } from 'react';
import { polyfill } from 'react-lifecycles-compat';
import RcTooltip from 'rc-tooltip';
import classNames from 'classnames';
import getPlacements, { AdjustOverflow, PlacementsConfig } from './placements';
import Button from '../button/index';
export... |
private tooltip: typeof RcTooltip;
constructor(props: TooltipProps) {
super(props);
this.state = {
visible: !!props.visible || !!props.defaultVisible,
};
}
onVisibleChange = (visible: boolean) => {
const { onVisibleChange } = this.props;
if (!('visible' in this.props)) {
this... | random_line_split | |
index.tsx | import * as React from 'react';
import { cloneElement } from 'react';
import { polyfill } from 'react-lifecycles-compat';
import RcTooltip from 'rc-tooltip';
import classNames from 'classnames';
import getPlacements, { AdjustOverflow, PlacementsConfig } from './placements';
import Button from '../button/index';
export... | { prefixCls, title, overlay, openClassName, getPopupContainer, getTooltipContainer } = props;
const children = props.children as React.ReactElement<any>;
let visible = state.visible;
// Hide tooltip when there is no title
if (!('visible' in props) && this.isNoTitle()) {
visible = false;
}
... | const | identifier_name |
index.js | import React, { Component, PropTypes } from 'react';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import flow from 'lodash.flow';
function isNullOrUndefined(o) {
return o == null;
}
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: pr... | else {
// use index
if (dragIndex !== hoverIndex) {
props.moveCard(dragIndex, hoverIndex);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searc... | {
// use id
if (dragId !== hoverId) {
props.moveCard(dragId, hoverIndex);
}
} | conditional_block |
index.js | import React, { Component, PropTypes } from 'react';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import flow from 'lodash.flow';
function isNullOrUndefined(o) {
return o == null;
}
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: pr... |
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().index = hoverIndex;
}
}
}
};
const propTypes = {
index: PropTypes.... | // use index
if (dragIndex !== hoverIndex) {
props.moveCard(dragIndex, hoverIndex); | random_line_split |
index.js | import React, { Component, PropTypes } from 'react';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import flow from 'lodash.flow';
function isNullOrUndefined(o) {
return o == null;
}
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: pr... | () {
const {
id,
index,
source,
createItem,
noDropOutside, // remove from restProps
moveCard, // remove from restProps
endDrag, // remove from restProps
isDragging,
connectDragSource,
connectDropTarget,
...restProps
} = this.props;
... | render | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.