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 |
|---|---|---|---|---|
poxliff.py | .xliffunit(s)
# newunit.namespace = self.namespace #XXX?necessary?
self.units.append(newunit)
self.xmlelement.append(newunit.xmlelement)
self.target = target
# We don't support any rich strings yet
multistring_to_rich = base.Translation... | random_line_split | ||
create-space.ts | /*
Copyright 2021 The Matrix.org Foundation C.I.C.
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... | else {
for (let i = 0; i < 2; i++) {
const continueButton = await session.query('.mx_SpaceRoomView_buttons .mx_AccessibleButton_kind_primary');
await continueButton.click();
}
}
session.log.done();
}
export async function inviteSpace(session: ElementSession, spaceName:... | {
const justMeButton = await session.query('.mx_SpaceRoomView_privateScope_justMeButton');
await justMeButton.click();
const continueButton = await session.query('.mx_AddExistingToSpace_footer .mx_AccessibleButton_kind_primary');
await continueButton.click();
} | conditional_block |
create-space.ts | /*
Copyright 2021 The Matrix.org Foundation C.I.C.
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... |
session.log.done();
}
export async function inviteSpace(session: ElementSession, spaceName: string, userId: string): Promise<void> {
session.log.step(`invites "${userId}" to space "${spaceName}"`);
const spaceButton = await session.query(`.mx_SpaceButton[aria-label="${spaceName}"]`);
await spaceButto... | random_line_split | |
create-space.ts | /*
Copyright 2021 The Matrix.org Foundation C.I.C.
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... | await continueButton.click();
} else {
for (let i = 0; i < 2; i++) {
const continueButton = await session.query('.mx_SpaceRoomView_buttons .mx_AccessibleButton_kind_primary');
await continueButton.click();
}
}
session.log.done();
}
export async function inv... | {
session.log.step(`creates space "${name}"`);
await openSpaceCreateMenu(session);
const className = isPublic ? ".mx_SpaceCreateMenuType_public" : ".mx_SpaceCreateMenuType_private";
const visibilityButton = await session.query(className);
await visibilityButton.click();
const nameInput = await... | identifier_body |
create-space.ts | /*
Copyright 2021 The Matrix.org Foundation C.I.C.
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... | (session: ElementSession, spaceName: string, userId: string): Promise<void> {
session.log.step(`invites "${userId}" to space "${spaceName}"`);
const spaceButton = await session.query(`.mx_SpaceButton[aria-label="${spaceName}"]`);
await spaceButton.click({
button: 'right',
});
const inviteB... | inviteSpace | identifier_name |
task.ts | import { Lobby } from "./lobby";
import * as Change from "./lobby/change";
import { GameCode } from "./lobby/game-code";
import { ServerState } from "./server-state";
/**
* A good base implementation of a task.
*/
export abstract class TaskBase<T> implements Task {
private readonly gameCode: GameCode;
protected... | (server: ServerState): Promise<void> {
let work: T;
try {
work = await this.begin(server);
} catch (e) {
const error = e as Error;
await Change.apply(server, this.gameCode, (lobby) =>
this.resolveError(lobby, error, server)
);
return;
}
await Change.apply(server... | handle | identifier_name |
task.ts | import { Lobby } from "./lobby";
import * as Change from "./lobby/change";
import { GameCode } from "./lobby/game-code";
import { ServerState } from "./server-state";
/**
* A good base implementation of a task.
*/
export abstract class TaskBase<T> implements Task {
private readonly gameCode: GameCode;
protected... |
public async handle(server: ServerState): Promise<void> {
let work: T;
try {
work = await this.begin(server);
} catch (e) {
const error = e as Error;
await Change.apply(server, this.gameCode, (lobby) =>
this.resolveError(lobby, error, server)
);
return;
}
awa... | throw error;
} | random_line_split |
task.ts | import { Lobby } from "./lobby";
import * as Change from "./lobby/change";
import { GameCode } from "./lobby/game-code";
import { ServerState } from "./server-state";
/**
* A good base implementation of a task.
*/
export abstract class TaskBase<T> implements Task {
private readonly gameCode: GameCode;
protected... |
protected abstract begin(server: ServerState): Promise<T>;
protected abstract resolve(
lobby: Lobby,
work: T,
server: ServerState
): Change.Change;
protected resolveError(
lobby: Lobby,
error: Error,
server: ServerState
): Change.Change {
throw error;
}
public async handle(... | {
this.gameCode = gameCode;
} | identifier_body |
Solution.py | # Problem: Search for a Range
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
#
# Your algorithm's runtime complexity must be in the order of O(log n).
# | # Given [5, 7, 7, 8, 8, 10] and target value 8,
#
# return [3, 4].
#
################################################################################
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
""... | # If the target is not found in the array, return [-1, -1].
#
# For example,
# | random_line_split |
Solution.py | # Problem: Search for a Range
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
#
# Your algorithm's runtime complexity must be in the order of O(log n).
#
# If the target is not found in the array, return [-1, -1].
#
# For example,
#
# Given [5, 7, 7, 8, 8, 10] and ta... |
return [-1, -1]
| start, end = mid, mid
while start - 1 >= 0 and nums[start - 1] == nums[mid]:
start -= 1
while end + 1 <= (len(nums) - 1) and nums[end + 1] == nums[mid]:
end += 1
return [start, end] | conditional_block |
Solution.py | # Problem: Search for a Range
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
#
# Your algorithm's runtime complexity must be in the order of O(log n).
#
# If the target is not found in the array, return [-1, -1].
#
# For example,
#
# Given [5, 7, 7, 8, 8, 10] and ta... |
while end + 1 <= (len(nums) - 1) and nums[end + 1] == nums[mid]:
end += 1
return [start, end]
return [-1, -1]
| """
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) / 2
if nums[mid] < target:
low = mid + 1
elif nums[mid] > target:
hi... | identifier_body |
Solution.py | # Problem: Search for a Range
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
#
# Your algorithm's runtime complexity must be in the order of O(log n).
#
# If the target is not found in the array, return [-1, -1].
#
# For example,
#
# Given [5, 7, 7, 8, 8, 10] and ta... | (object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) / 2
if nums[mid] < target:
low = mid ... | Solution | identifier_name |
energy-breakdown-chart.ts | /* Copyright 2016 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 ... |
} | {
return energySource.fixedCost + energySource.variableCost;
} | identifier_body |
energy-breakdown-chart.ts | /* Copyright 2016 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 ... |
});
this._chart.load({
columns: columns
});
}
/**
* Gets the representative value for a given energy source.
*
* @param energySource The outcome contributions for a single energy source.
* @returns A representative numeric value for the energy source; e.g., cost.
*/
_getEnergyS... | {
columns.push(
[key].concat(<any[]>[
this._getEnergySourceValue(view.summary.breakdown[key])
])
);
} | conditional_block |
energy-breakdown-chart.ts | /* Copyright 2016 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 ... | import * as style from '../style';
/**
* Contribution breakdown by energy source chart.
*/
class EnergyBreakdownChart implements SummaryDataComponent {
_container: HTMLElement;
_chart: c3.ChartAPI;
// Defines the deterministic ordering of data series within the chart.
_dataOrder = ['nuclear', 'solar', 'win... | random_line_split | |
energy-breakdown-chart.ts | /* Copyright 2016 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 ... | (title: string): c3.ChartConfiguration {
return {
bindto: this._container,
data: {
columns: [],
type: 'donut',
order: null,
names: {
solar: 'Solar',
wind: 'Wind',
nuclear: 'Nuclear',
ng: 'Natural Gas',
storage: 'Storage',
... | _getChartConfig | identifier_name |
mine.js | exports.login = function* (ctx) {
const result = yield ctx.service.mine.login(ctx.request.body);
if (!result) {
ctx.status = 400;
ctx.body = {
status: 400,
msg: `please check your username and password`,
}
return;
}
ctx.body = {
access_token: result.access_token,
msg: 'login ... |
ctx.body = info;
ctx.status = 200;
}
exports.accounts = function* (ctx) {
const accounts = yield ctx.service.mine.accounts(ctx.auth.user_id);
ctx.body = accounts;
ctx.status = 200;
}
exports.update = function* (ctx) {
let profile = ctx.request.body;
profile.id = ctx.auth.user_id;
const result = yield... | {
ctx.status = 200;
ctx.body = {
shares_count: 0,
friends_count: 0,
helpful_count: 0,
};
return;
} | conditional_block |
mine.js | exports.login = function* (ctx) {
const result = yield ctx.service.mine.login(ctx.request.body);
if (!result) {
ctx.status = 400;
ctx.body = {
status: 400,
msg: `please check your username and password`,
}
return;
}
ctx.body = {
access_token: result.access_token,
msg: 'login ... | const accounts = yield ctx.service.mine.accounts(ctx.auth.user_id);
ctx.body = accounts;
ctx.status = 200;
}
exports.update = function* (ctx) {
let profile = ctx.request.body;
profile.id = ctx.auth.user_id;
const result = yield ctx.service.mine.update(profile);
if (result) {
ctx.status = 204;
ret... |
exports.accounts = function* (ctx) { | random_line_split |
backup_config_modal.tsx | /*
* Copyright 2020 ThoughtWorks, 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 agr... | isSaving: Stream<boolean>,
onsave: MouseEventHandler) {
super(Size.medium);
this.backupConfig = backupConfig;
this.showSpinner = showSpinner;
this.errorMessage = errorMessage;
this.isSaving = isSaving;
this.onsave = onsave;
}
title(): string {
retu... | constructor(backupConfig: Stream<BackupConfig>,
showSpinner: Stream<boolean>,
errorMessage: Stream<string>, | random_line_split |
backup_config_modal.tsx | /*
* Copyright 2020 ThoughtWorks, 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 agr... | (): string {
return "Configure backup settings";
}
body() {
return [
<FlashMessage message={this.errorMessage()} type={MessageType.alert}/>,
[<BackupConfigWidget backupConfig={this.backupConfig} key={"backup config"}/>]
];
}
buttons() {
if (this.isLoading()) {
return [<Primar... | title | identifier_name |
backup_config_modal.tsx | /*
* Copyright 2020 ThoughtWorks, 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 agr... |
body() {
return [
<FlashMessage message={this.errorMessage()} type={MessageType.alert}/>,
[<BackupConfigWidget backupConfig={this.backupConfig} key={"backup config"}/>]
];
}
buttons() {
if (this.isLoading()) {
return [<Primary data-test-id="button-ok" onclick={this.close.bind(this... | {
return "Configure backup settings";
} | identifier_body |
sketch.js | var FRAME_RATE = 50;
var MY_RADIUS = 10;
var MAX_SPEED = 10;
var walkerManagers = [];
function Walker(x, y, radius, index) {
this.x = x;
this.y = y;
this.radius = radius;
this.index = index;
}
Walker.prototype.update = function(time) {
this.x += (sin(this.index + time) + map(noise(time, this.index), 0, 1, -... | {
background(255);
walkerManagers.forEach(function(walkerManager) {
walkerManager.walk(frameCount * 0.1);
walkerManager.render();
walkerManager.update(frameCount * 0.1);
});
} | identifier_body | |
sketch.js | var FRAME_RATE = 50;
var MY_RADIUS = 10;
var MAX_SPEED = 10;
var walkerManagers = [];
function Walker(x, y, radius, index) {
this.x = x;
this.y = y;
this.radius = radius;
this.index = index;
}
Walker.prototype.update = function(time) {
this.x += (sin(this.index + time) + map(noise(time, this.index), 0, 1, -... |
}.bind(this));
}
WalkerManager.prototype.render = function () {
this.history.forEach(function(walker, index) {
walker.render();
});
var lastWalker = this.history[this.history.length - 1];
var radius = Math.min(lastWalker.radius + 6, MY_RADIUS * 2);
fill(206, 33, 89, 90);
ellipse(lastWalker.x, lastWa... | {
this.history.splice(index, 1);
} | conditional_block |
sketch.js | var FRAME_RATE = 50;
var MY_RADIUS = 10;
var MAX_SPEED = 10;
var walkerManagers = [];
function Walker(x, y, radius, index) {
this.x = x;
this.y = y;
this.radius = radius;
this.index = index;
}
Walker.prototype.update = function(time) {
this.x += (sin(this.index + time) + map(noise(time, this.index), 0, 1, -... | () {
background(255);
walkerManagers.forEach(function(walkerManager) {
walkerManager.walk(frameCount * 0.1);
walkerManager.render();
walkerManager.update(frameCount * 0.1);
});
} | draw | identifier_name |
sketch.js | var FRAME_RATE = 50;
var MY_RADIUS = 10;
var MAX_SPEED = 10;
var walkerManagers = [];
function Walker(x, y, radius, index) {
this.x = x;
this.y = y;
this.radius = radius;
this.index = index;
}
Walker.prototype.update = function(time) {
this.x += (sin(this.index + time) + map(noise(time, this.index), 0, 1, -... | }
}
function draw() {
background(255);
walkerManagers.forEach(function(walkerManager) {
walkerManager.walk(frameCount * 0.1);
walkerManager.render();
walkerManager.update(frameCount * 0.1);
});
} | random_line_split | |
remote.py | """Support for the Roku remote."""
import requests.exceptions
from homeassistant.components import remote
from homeassistant.const import CONF_HOST
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Roku remote platform."""
if not discovery_info:
retu... |
def __init__(self, host):
"""Initialize the Roku device."""
from roku import Roku
self.roku = Roku(host)
self._device_info = {}
def update(self):
"""Retrieve latest state."""
try:
self._device_info = self.roku.device_info
except (requests.ex... |
class RokuRemote(remote.RemoteDevice):
"""Device that sends commands to an Roku.""" | random_line_split |
remote.py | """Support for the Roku remote."""
import requests.exceptions
from homeassistant.components import remote
from homeassistant.const import CONF_HOST
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Roku remote platform."""
if not discovery_info:
retu... |
def send_command(self, command, **kwargs):
"""Send a command to one device."""
for single_command in command:
if not hasattr(self.roku, single_command):
continue
getattr(self.roku, single_command)()
| """No polling needed for Roku."""
return False | identifier_body |
remote.py | """Support for the Roku remote."""
import requests.exceptions
from homeassistant.components import remote
from homeassistant.const import CONF_HOST
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Roku remote platform."""
if not discovery_info:
retu... | (remote.RemoteDevice):
"""Device that sends commands to an Roku."""
def __init__(self, host):
"""Initialize the Roku device."""
from roku import Roku
self.roku = Roku(host)
self._device_info = {}
def update(self):
"""Retrieve latest state."""
try:
... | RokuRemote | identifier_name |
remote.py | """Support for the Roku remote."""
import requests.exceptions
from homeassistant.components import remote
from homeassistant.const import CONF_HOST
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Roku remote platform."""
if not discovery_info:
retu... |
getattr(self.roku, single_command)()
| continue | conditional_block |
extents.rs | Reader<R>
where
R: ReadAt,
{
pub fn new(
inner: R,
block_size: u32,
size: u64,
core: [u8; crate::INODE_CORE_SIZE],
checksum_prefix: Option<u32>,
) -> Result<TreeReader<R>, Error> {
let extents = load_extent_tree(
&mut |block| crate::load_disc_bytes... | random_line_split | ||
extents.rs | part: u32,
start: u64,
len: u16,
}
pub struct TreeReader<R> {
inner: R,
pos: u64,
len: u64,
block_size: u32,
extents: Vec<Extent>,
}
impl<R> TreeReader<R>
where
R: ReadAt,
{
pub fn new(
inner: R,
block_size: u32,
size: u64,
core: [u8; crate::INOD... |
FoundPart::Sparse(max) => {
let max_bytes = u64::from(max) * block_size;
let read = std::cmp::min(max_bytes, buf.len() as u64) as usize;
let read = std::cmp::min(read as u64, self.len - self.pos) as usize;
zero(&mut buf[0..read]);
... | {
let bytes_through_extent =
(block_size * u64::from(wanted_block - extent.part)) + read_of_this_block;
let remaining_bytes_in_extent =
(u64::from(extent.len) * block_size) - bytes_through_extent;
let to_read = std::cmp::min(remaini... | conditional_block |
extents.rs | .
part: u32,
start: u64,
len: u16,
}
pub struct TreeReader<R> {
inner: R,
pos: u64,
len: u64,
block_size: u32,
extents: Vec<Extent>,
}
impl<R> TreeReader<R>
where
R: ReadAt,
{
pub fn new(
inner: R,
block_size: u32,
size: u64,
core: [u8; crate::IN... | (buf: &mut [u8]) {
unsafe { std::ptr::write_bytes(buf.as_mut_ptr(), 0u8, buf.len()) }
}
#[cfg(test)]
mod tests {
use std::convert::TryFrom;
use std::io::Read;
use crate::extents::Extent;
use crate::extents::TreeReader;
#[test]
fn simple_tree() {
let data = (0..255u8).collect::<Vec... | zero | identifier_name |
extents.rs | part: u32,
start: u64,
len: u16,
}
pub struct TreeReader<R> {
inner: R,
pos: u64,
len: u64,
block_size: u32,
extents: Vec<Extent>,
}
impl<R> TreeReader<R>
where
R: ReadAt,
{
pub fn new(
inner: R,
block_size: u32,
size: u64,
core: [u8; crate::INOD... | self.pos += u64::try_from(read).expect("infallible u64 conversion");
Ok(read)
}
FoundPart::Sparse(max) => {
let max_bytes = u64::from(max) * block_size;
let read = std::cmp::min(max_bytes, buf.len() as u64) as usize;
... | {
if buf.is_empty() {
return Ok(0);
}
let block_size = u64::from(self.block_size);
let wanted_block = u32::try_from(self.pos / block_size).unwrap();
let read_of_this_block = self.pos % block_size;
match find_part(wanted_block, &self.extents) {
F... | identifier_body |
key.py | # Copyright (C) 2011 Sam Rushing
# Copyright (C) 2012-2014 The python-bitcoinlib developers
# Copyright (C) 2015 The python-altcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of... |
def generate(self):
global _ssl
_ssl.EC_KEY_generate_key(self.k)
return self.k
__all__ = (
'CAltcoinECKey',
)
| padding = 32 - size
new_buffer = ctypes.create_string_buffer(32)
for idx in range(0, padding):
new_buffer[idx] = "\x00"
for idx in range(padding, 32):
new_buffer[idx] = mb[idx - padding]
return new_buffer.raw | conditional_block |
key.py | # Copyright (C) 2011 Sam Rushing
# Copyright (C) 2012-2014 The python-bitcoinlib developers
# Copyright (C) 2015 The python-altcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of... | (self):
CECKey.__init__(self)
def __del__(self):
CECKey.__del__(self)
def get_secret_bytes(self):
global _ssl
secret = _ssl.EC_KEY_get0_private_key(self.k)
mb = ctypes.create_string_buffer(32)
size = _ssl.BN_bn2bin(secret, mb)
if size == 32:
... | __init__ | identifier_name |
key.py | # Copyright (C) 2011 Sam Rushing
# Copyright (C) 2012-2014 The python-bitcoinlib developers
# Copyright (C) 2015 The python-altcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of... |
def get_secret_bytes(self):
global _ssl
secret = _ssl.EC_KEY_get0_private_key(self.k)
mb = ctypes.create_string_buffer(32)
size = _ssl.BN_bn2bin(secret, mb)
if size == 32:
return mb.raw
else:
# Move the data into a zero-padded buffer of 32 b... | CECKey.__del__(self) | identifier_body |
key.py | # Copyright (C) 2011 Sam Rushing
# Copyright (C) 2012-2014 The python-bitcoinlib developers
# Copyright (C) 2015 The python-altcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of... |
# CECKey with added support for key generation
class CAltcoinECKey(CECKey):
def __init__(self):
CECKey.__init__(self)
def __del__(self):
CECKey.__del__(self)
def get_secret_bytes(self):
global _ssl
secret = _ssl.EC_KEY_get0_private_key(self.k)
mb = ctypes.create_... |
import ctypes
import ctypes.util
from bitcoin.core.key import CECKey, _ssl | random_line_split |
errorcode.js | // Copyright 2011 The Closure Library Authors. 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... | /**
* @fileoverview Defines error codes to be thrown by storage mechanisms.
*/
goog.provide('goog.storage.mechanism.ErrorCode');
/**
* Errors thrown by storage mechanisms.
* @enum {string}
*/
goog.storage.mechanism.ErrorCode = {
INVALID_VALUE: 'Storage mechanism: Invalid value was encountered',
QUOTA_EXCEED... | // See the License for the specific language governing permissions and
// limitations under the License.
| random_line_split |
assert.js | /*
* Should
* Copyright(c) 2010-2015 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
var util = require('../util')
, assert = require('./_assert')
, AssertionError = require('../assertion-error');
module.exports = function(should) {
var i = should.format;
/*
* Expose assert to should
*
* T... |
};
should.not = {};
/**
* Asserts _obj_ does not exist, with optional message.
*
* @name not.exist
* @static
* @memberOf should
* @category assertion assert
* @alias should.not.exists
* @param {*} obj
* @param {String} [msg]
* @example
*
* should.not.exist(null);
* should.... | {
throw new AssertionError({
message: msg || ('expected ' + i(obj) + ' to exist'), stackStartFunction: should.exist
});
} | conditional_block |
assert.js | /*
* Should
* Copyright(c) 2010-2015 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
var util = require('../util')
, assert = require('./_assert')
, AssertionError = require('../assertion-error'); |
module.exports = function(should) {
var i = should.format;
/*
* Expose assert to should
*
* This allows you to do things like below
* without require()ing the assert module.
*
* should.equal(foo.bar, undefined);
*
*/
util.merge(should, assert);
/**
* Assert _obj_ exists, with op... | random_line_split | |
error.rs | use postgres::error::Error as PostgresError;
use std::error::Error as StdError;
use std::fmt;
use std::result::Result as StdResult;
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub enum Error {
Postgres(PostgresError),
CategoryNameEmpty,
CategoryNotFound,
ColumnNotFound,
FeedNameEmpt... | Error::CategoryNotFound => "Category not found",
Error::ColumnNotFound => "Can't fetch a column",
Error::FeedNameEmpty => "Feed name is empty",
Error::FeedUrlEmpty => "Feed URL is empty",
Error::FeedNotFound => "Feed not found",
Error::TokenNotFoun... | match *self {
Error::Postgres(ref err) => err.description(),
Error::CategoryNameEmpty => "Category name is empty", | random_line_split |
error.rs | use postgres::error::Error as PostgresError;
use std::error::Error as StdError;
use std::fmt;
use std::result::Result as StdResult;
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub enum Error {
Postgres(PostgresError),
CategoryNameEmpty,
CategoryNotFound,
ColumnNotFound,
FeedNameEmpt... |
fn cause(&self) -> Option<&StdError> {
match *self {
Error::Postgres(ref err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
write!(out, "{}", self.description())
}
}
| {
match *self {
Error::Postgres(ref err) => err.description(),
Error::CategoryNameEmpty => "Category name is empty",
Error::CategoryNotFound => "Category not found",
Error::ColumnNotFound => "Can't fetch a column",
Error::FeedNameEmpty => "Feed name is... | identifier_body |
error.rs | use postgres::error::Error as PostgresError;
use std::error::Error as StdError;
use std::fmt;
use std::result::Result as StdResult;
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub enum Error {
Postgres(PostgresError),
CategoryNameEmpty,
CategoryNotFound,
ColumnNotFound,
FeedNameEmpt... | (&self) -> Option<&StdError> {
match *self {
Error::Postgres(ref err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
write!(out, "{}", self.description())
}
}
| cause | identifier_name |
directive.d.ts | /**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contribu... | *
* import {directive, html} from 'lit-html';
*
* const immutable = directive((v) => (part) => {
* if (part.value !== v) {
* part.setValue(v)
* }
* });
*/
export declare const directive: <F extends DirectiveFactory>(f: F) => F;
export declare const isDirective: (o: unknown) => o is DirectiveF... | * @example
| random_line_split |
fans.js | var fans=require('../../modules/blog/fans');
var User=require('../../modules/resume/user');
var async = require('asyncawait/async');
var await = require('asyncawait/await');
module.exports=(async(function(method,req,res){
var result;
if(method==='get'){
}
else if(method==='post') | msg:"已关注"
}
}
else{
var fansDate=await(fans.create({
userId:userId,
targetId:targetId
}))
if(fansDate){
result={
status:0,
msg:"关注成功"
}
}else{
result={
status:-1,
msg:"关注失败"
}
}
}
}
}else{
result=... | {
var userId=req.session.uid;
var targetId=req.body.targetId;
if(userId){
if(userId==targetId){
result={
status:-1,
msg:"你咋可以自己关注自己呢?自恋!"
}
}else{
//已登录才能关注,查询是否已关注过
var isFansDate=await(fans.findOne({
where:{
userId:userId,
targetId:targetId
}
}))
if(... | conditional_block |
fans.js | var fans=require('../../modules/blog/fans');
var User=require('../../modules/resume/user');
var async = require('asyncawait/async');
var await = require('asyncawait/await');
module.exports=(async(function(method,req,res){
var result;
if(method==='get'){
}
else if(method==='post'){
var userId=req.session.uid;
v... | status:0,
msg:"取消关注成功"
}
}else{
result={
status:-1,
msg:"取消关注失败"
}
}
}
else{
result={
status:-1,
msg:"未关注"
}
}
}else{
result={
status:-1,
msg:"未登录"
}
}
}
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
res.end(... | if(fansDate){
result={ | random_line_split |
HttpHandler.ts |
import * as http from 'http';
import * as Rx from 'rxjs';
import { withLatestFrom } from 'rxjs/Operator/withLatestFrom'
// import { HttpServerConfig } from './../ConfigRX'
import { HttpPair } from './../servers/Http';
import { RouteHandler } from '../routing/Router';
import { Request, Authorization } from './../me... | (public req: Request, public res: Response) {
super({req, res});
let self = this;
this.req.parse();
super.next({req, res});
let handler$ = req.getHandler()
.do(routeHandler => {
let pair = self.value
pair.req.routeHandler = routeHandler
return super.next(pair)
})
let headers$ = ... | constructor | identifier_name |
HttpHandler.ts |
import * as http from 'http';
import * as Rx from 'rxjs';
import { withLatestFrom } from 'rxjs/Operator/withLatestFrom'
// import { HttpServerConfig } from './../ConfigRX'
import { HttpPair } from './../servers/Http';
import { RouteHandler } from '../routing/Router';
import { Request, Authorization } from './../me... |
private _httpNext(value: any): void {}
private _handleError(error: Error): void {}
} | {
let id = this.req.socket.address()
return Object.assign(this.req.id, id, {
timestamp: Date.now(),
insertId: (id.address + ' | ' + id.family)
}).insertId
} | identifier_body |
HttpHandler.ts | import * as http from 'http';
import * as Rx from 'rxjs';
import { withLatestFrom } from 'rxjs/Operator/withLatestFrom'
// import { HttpServerConfig } from './../ConfigRX'
import { HttpPair } from './../servers/Http';
import { RouteHandler } from '../routing/Router';
import { Request, Authorization } from './../messa... |
constructor(public req: Request, public res: Response) {
super({req, res});
let self = this;
this.req.parse();
super.next({req, res});
let handler$ = req.getHandler()
.do(routeHandler => {
let pair = self.value
pair.req.routeHandler = routeHandler
return super.next(pair)
})
le... |
_id: string
routeHandler: RouteHandler | random_line_split |
HttpHandler.ts |
import * as http from 'http';
import * as Rx from 'rxjs';
import { withLatestFrom } from 'rxjs/Operator/withLatestFrom'
// import { HttpServerConfig } from './../ConfigRX'
import { HttpPair } from './../servers/Http';
import { RouteHandler } from '../routing/Router';
import { Request, Authorization } from './../me... |
})
.do(auth => {
if (auth.isRequired && !auth.isAuthorized) {
throw new Error('Not authorized')
}
let pair = self.value
pair.req.auth = auth
return super.next(pair)
})
.flatMap(auth => req.routeHandler.observable(req.routeHandler.config))
.subscribe(res)
}
get id() {
retur... | {
let pair = self.value
pair.req.auth.isRequired = routeHandler.config.auth.isRequired
if(!pair.req.auth.isRequired) {
pair.req.auth.isAuthorized = true
super.next(pair)
return Rx.Observable.from([(<Authorization>{
isRequired: false,
isAuthorized: true
})])
}
... | conditional_block |
abi.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
// NB: This ordering MUST match the AbiDatas array below.
// (This is ensured by the test indices_are_correct().)
// Single platform ABIs come first (`for_arch()` relies on this)
Cdecl,
Stdcall,
Fastcall,
Aapcs,
Win64,
// Multiplatform ABIs second
Rust,
C,
System,
... | Abi | identifier_name |
abi.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | X86_64,
Arm,
Mips,
Mipsel
}
impl Copy for Architecture {}
pub struct AbiData {
abi: Abi,
// Name of this ABI as we like it called.
name: &'static str,
}
impl Copy for AbiData {}
pub enum AbiArchitecture {
/// Not a real ABI (e.g., intrinsic)
RustArch,
/// An ABI that specifi... | random_line_split | |
abi.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
impl fmt::Show for Abi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"{}\"", self.name())
}
}
impl fmt::Show for Os {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
OsLinux => "linux".fmt(f),
OsWindows => "windows".fmt... | {
self.data().name
} | identifier_body |
test.py | import luhn
def test_checksum_len1():
assert luhn.checksum('7') == 7
def test_checksum_len2():
assert luhn.checksum('13') == 5
def test_checksum_len3():
|
def test_checksum_len4():
assert luhn.checksum('2827') == 3
def test_checksum_len13():
assert luhn.checksum('4346537657597') == 9
def test_checksum_len14():
assert luhn.checksum('27184931073326') == 1
def test_valid():
assert luhn.verify('356938035643809')
def test_invalid():
assert not luhn.v... | assert luhn.checksum('383') == 3 | identifier_body |
test.py | import luhn
def test_checksum_len1():
assert luhn.checksum('7') == 7
def test_checksum_len2():
assert luhn.checksum('13') == 5
def test_checksum_len3():
assert luhn.checksum('383') == 3
def test_checksum_len4():
assert luhn.checksum('2827') == 3
def test_checksum_len13():
assert luhn.checksum('... |
def test_invalid():
assert not luhn.verify('4222222222222222')
def test_generate():
assert luhn.generate('7992739871') == 3
def test_append():
assert luhn.append('53461861341123') =='534618613411234' | def test_checksum_len14():
assert luhn.checksum('27184931073326') == 1
def test_valid():
assert luhn.verify('356938035643809') | random_line_split |
test.py | import luhn
def test_checksum_len1():
assert luhn.checksum('7') == 7
def test_checksum_len2():
assert luhn.checksum('13') == 5
def test_checksum_len3():
assert luhn.checksum('383') == 3
def test_checksum_len4():
assert luhn.checksum('2827') == 3
def test_checksum_len13():
assert luhn.checksum('... | ():
assert luhn.append('53461861341123') =='534618613411234'
| test_append | identifier_name |
connectInformationMessage.ts | *
* 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 go... | *
* 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 | random_line_split | |
connectInformationMessage.ts | can not connect to mail server!','無互聯網,郵件伺服器無法到達!'],
systemError:
['CoNET客户端故障,请重启后再试','端末故障です、CoNETを再起動してください','CoNET client error! Restart CoNET please!','CoNET客戶端故障,請重啟後再試'],
reConnectCoNET:
['CoNET链接已中断','CoNETとの接続が中断され','CoNET connection lost.','CoNET的鏈接已中斷'
],
connectingToCoNET:
['正在连接CoNET...','CoNETへ... | identifier_body | ||
connectInformationMessage.ts | can not connect to mail server!','無互聯網,郵件伺服器無法到達!'],
systemError:
['CoNET客户端故障,请重启后再试','端末故障です、CoNETを再起動してください','CoNET client error! Restart CoNET please!','CoNET客戶端故障,請重啟後再試'],
reConnectCoNET:
['CoNET链接已中断','CoNETとの接続が中断され','CoNET connection lost.','CoNET的鏈接已中斷'
],
connectingToCoNET:
['正在连接CoNET...','CoNETへ... | conditional_block | ||
connectInformationMessage.ts | can not connect to mail server!','無互聯網,郵件伺服器無法到達!'],
systemError:
['CoNET客户端故障,请重启后再试','端末故障です、CoNETを再起動してください','CoNET client error! Restart CoNET please!','CoNET客戶端故障,請重啟後再試'],
reConnectCoNET:
['CoNET链接已中断','CoNETとの接続が中断され','CoNET connection lost.','CoNET的鏈接已中斷'
],
connectingToCoNET:
['正在连接CoNET...','CoNETへ... | identifier_name | ||
iap_buy_more_credits.js | odoo.define('iap.buy_more_credits', function (require) {
'use strict';
var widgetRegistry = require('web.widget_registry');
var Widget = require('web.Widget');
var core = require('web.core');
var rpc = require('web.rpc');
var QWeb = core.qweb;
var IAPBuyMoreCreditsWidget = Widget.extend({
className: 'o_field_ia... | }); |
return IAPBuyMoreCreditsWidget; | random_line_split |
naive_bayes.py | import numpy as np
from Orange.classification import Learner, Model
from Orange.data import Instance, Storage, Table, DiscreteVariable
from Orange.statistics import contingency
from Orange.preprocess import Discretize
__all__ = ["NaiveBayesLearner"]
class NaiveBayesLearner(Learner):
"""
Naive Bayes classifi... | (self, cont, class_freq, domain):
super().__init__(domain)
self.cont = cont
self.class_freq = class_freq
def predict_storage(self, data):
if isinstance(data, Instance):
data = [data]
ncv = len(self.domain.class_var.values)
probs = np.zeros((len(data), ncv... | __init__ | identifier_name |
naive_bayes.py | import numpy as np
from Orange.classification import Learner, Model
from Orange.data import Instance, Storage, Table, DiscreteVariable
from Orange.statistics import contingency
from Orange.preprocess import Discretize
__all__ = ["NaiveBayesLearner"]
class NaiveBayesLearner(Learner):
"""
Naive Bayes classifi... | class NaiveBayesModel(Model):
def __init__(self, cont, class_freq, domain):
super().__init__(domain)
self.cont = cont
self.class_freq = class_freq
def predict_storage(self, data):
if isinstance(data, Instance):
data = [data]
ncv = len(self.domain.class_var.va... | random_line_split | |
naive_bayes.py | import numpy as np
from Orange.classification import Learner, Model
from Orange.data import Instance, Storage, Table, DiscreteVariable
from Orange.statistics import contingency
from Orange.preprocess import Discretize
__all__ = ["NaiveBayesLearner"]
class NaiveBayesLearner(Learner):
"""
Naive Bayes classifi... | if isinstance(data, Instance):
data = [data]
ncv = len(self.domain.class_var.values)
probs = np.zeros((len(data), ncv))
for i, ins in enumerate(data):
for c in range(ncv):
py = (1 + self.class_freq[c]) / (ncv + sum(self.class_freq))
log_pro... | identifier_body | |
naive_bayes.py | import numpy as np
from Orange.classification import Learner, Model
from Orange.data import Instance, Storage, Table, DiscreteVariable
from Orange.statistics import contingency
from Orange.preprocess import Discretize
__all__ = ["NaiveBayesLearner"]
class NaiveBayesLearner(Learner):
"""
Naive Bayes classifi... |
probs[i, c] = log_prob
np.exp(probs, out=probs)
probs /= probs.sum(axis=1)[:, None]
values = probs.argmax(axis=1)
return values, probs
| if not np.isnan(ins[a]):
relevant = 1 + self.cont[ai][c][a.to_val(ins[a])]
total = len(a.values) + self.class_freq[c]
log_prob += np.log(relevant / total) | conditional_block |
send_serial.rs | use printspool_machine::components::ControllerConfig;
use super::*;
use crate::gcode_parser::parse_gcode;
pub fn send_serial(
effects: &mut Vec<Effect>,
gcode_line: GCodeLine,
context: &mut Context,
is_polling: bool,
) {
// Allow for a byte of spacing between receiving and sending over the serial ... | .map_err(|err| warn!("{}", err));
let ControllerConfig {
long_running_code_timeout,
fast_code_timeout,
long_running_codes,
blocking_codes,
..
} = &context.controller.model;
let mut duration = fast_code_timeout;
let mut is_blocking = false;
if let O... | // eprintln!("TX: {:?}", gcode_line.gcode);
context.push_gcode_tx(gcode_line.gcode.clone(), is_polling);
let parser_result = parse_gcode(&gcode_line.gcode, context) | random_line_split |
send_serial.rs | use printspool_machine::components::ControllerConfig;
use super::*;
use crate::gcode_parser::parse_gcode;
pub fn send_serial(
effects: &mut Vec<Effect>,
gcode_line: GCodeLine,
context: &mut Context,
is_polling: bool,
) | } = &context.controller.model;
let mut duration = fast_code_timeout;
let mut is_blocking = false;
if let Ok(Some((mnemonic, major_number))) = parser_result {
let gcode_macro = format!("{}{}", mnemonic, major_number);
if long_running_codes.contains(&gcode_macro) {
duration... | {
// Allow for a byte of spacing between receiving and sending over the serial port
// The choice of 1 byte was arbitrary but sending without a spin lock seems to
// loose GCodes.
// let seconds_per_bit: u64 = (60 * 1000 * 1000 / context.baud_rate).into();
// spin_sleep::sleep(Duration::from_micros(... | identifier_body |
send_serial.rs | use printspool_machine::components::ControllerConfig;
use super::*;
use crate::gcode_parser::parse_gcode;
pub fn | (
effects: &mut Vec<Effect>,
gcode_line: GCodeLine,
context: &mut Context,
is_polling: bool,
) {
// Allow for a byte of spacing between receiving and sending over the serial port
// The choice of 1 byte was arbitrary but sending without a spin lock seems to
// loose GCodes.
// let second... | send_serial | identifier_name |
send_serial.rs | use printspool_machine::components::ControllerConfig;
use super::*;
use crate::gcode_parser::parse_gcode;
pub fn send_serial(
effects: &mut Vec<Effect>,
gcode_line: GCodeLine,
context: &mut Context,
is_polling: bool,
) {
// Allow for a byte of spacing between receiving and sending over the serial ... | ;
effects.push(Effect::SendSerial(gcode_line));
if is_blocking {
effects.push(
Effect::CancelDelay { key: "tickle_delay".to_string() }
);
} else {
effects.push(
Effect::Delay {
key: "tickle_delay".to_string(),
// TODO: configur... | {
let gcode_macro = format!("{}{}", mnemonic, major_number);
if long_running_codes.contains(&gcode_macro) {
duration = long_running_code_timeout
}
is_blocking = blocking_codes.contains(&gcode_macro)
} | conditional_block |
base.py | Meta, abstractmethod
from pathlib import Path
from random import randint
from threading import Event, Thread
from kytos.core.events import KytosEvent
from kytos.core.logs import NAppLog
__all__ = ('KytosNApp',)
LOG = NAppLog()
class NApp:
"""Class to represent a NApp."""
# pylint: disable=too-many-argumen... |
return napp
def as_json(self):
"""Dump all NApp attributes on a json format."""
return json.dumps(self.__dict__)
def match(self, pattern):
"""Whether a pattern is present on NApp id, description and tags."""
try:
pattern = '.*{}.*'.format(pattern)
... | setattr(napp, attribute, value) | conditional_block |
base.py | Meta, abstractmethod
from pathlib import Path
from random import randint
from threading import Event, Thread
from kytos.core.events import KytosEvent
from kytos.core.logs import NAppLog
__all__ = ('KytosNApp',)
LOG = NAppLog()
class NApp:
"""Class to represent a NApp."""
# pylint: disable=too-many-argumen... | (self):
"""Call the execute method, looping as needed.
It should not be overriden.
"""
self.notify_loaded()
LOG.info("Running NApp: %s", self)
self.execute()
while self.__interval > 0 and not self.__event.is_set():
self.__event.wait(self.__interval)
... | run | identifier_name |
base.py | Meta, abstractmethod
from pathlib import Path
from random import randint
from threading import Event, Thread
from kytos.core.events import KytosEvent
from kytos.core.logs import NAppLog
__all__ = ('KytosNApp',)
LOG = NAppLog()
class NApp:
"""Class to represent a NApp."""
# pylint: disable=too-many-argumen... | """Return a new NApp instance from a metadata file."""
with open(filename, encoding='utf-8') as data_file:
data = json.loads(data_file.read())
return cls.create_from_dict(data)
@classmethod
def create_from_dict(cls, data):
"""Return a new NApp instance from metadata... | random_line_split | |
base.py | Meta, abstractmethod
from pathlib import Path
from random import randint
from threading import Event, Thread
from kytos.core.events import KytosEvent
from kytos.core.logs import NAppLog
__all__ = ('KytosNApp',)
LOG = NAppLog()
class NApp:
"""Class to represent a NApp."""
# pylint: disable=too-many-argumen... |
def run(self):
"""Call the execute method, looping as needed.
It should not be overriden.
"""
self.notify_loaded()
LOG.info("Running NApp: %s", self)
self.execute()
while self.__interval > 0 and not self.__event.is_set():
self.__event.wait(self.... | """Run :meth:`execute` within a loop. Call this method during setup.
By calling this method, the application does not need to worry about
loop details such as sleeping and stopping the loop when
:meth:`shutdown` is called. Just call this method during :meth:`setup`
and implement :meth:`... | identifier_body |
views.py | #coding:utf-8
from django.shortcuts import render,render_to_response,redirect
from django.core.urlresolvers import reverse
from block.models import Blocks
from models import Article
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.decorators import login_required
... | rticle_id):
article_id=int(article_id)
article=Article.objects.get(id=article_id)
return render_to_response("article_detail.html",{"article":article},context_instance=RequestContext(requset)) | title=request.POST['title'].strip()
content=request.POST['content'].strip()
if not title or not content:
messages.add_message(request,messages.ERROR,u'标题和内容不能为空!')
return render_to_response("article_create.html",{"b":block,"title":title,"content":content},context_... | conditional_block |
views.py | #coding:utf-8
from django.shortcuts import render,render_to_response,redirect
from django.core.urlresolvers import reverse
from block.models import Blocks | from django.contrib import messages
from django.contrib.auth.decorators import login_required
# Create your views here.
def article_list(request,block_id):
block_id=int(block_id)
block=Blocks.objects.get(id=block_id)
articles=Article.objects.filter(block=block).order_by("-last_update_timestamp")
return... | from models import Article
from django.template import RequestContext | random_line_split |
views.py | #coding:utf-8
from django.shortcuts import render,render_to_response,redirect
from django.core.urlresolvers import reverse
from block.models import Blocks
from models import Article
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.decorators import login_required
... | article=Article.objects.get(id=article_id)
return render_to_response("article_detail.html",{"article":article},context_instance=RequestContext(requset)) | identifier_body | |
views.py | #coding:utf-8
from django.shortcuts import render,render_to_response,redirect
from django.core.urlresolvers import reverse
from block.models import Blocks
from models import Article
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.decorators import login_required
... | (request,block_id):
block_id=int(block_id)
block=Blocks.objects.get(id=block_id)
articles=Article.objects.filter(block=block).order_by("-last_update_timestamp")
return render_to_response("articles_list.html",{"articles":articles,"b":block},context_instance=RequestContext(request))
@login_required()
def... | article_list | identifier_name |
svd.ts | (1.0 + b * b);
}
if (b > 0) {
a /= b;
return b * Math.sqrt(1.0 + a * a);
}
return 0.0;
}
const EPSILON = 0.0000001192092896;
const FLT_MIN = 1E-37;
export function JacobiSVDImpl(At: NumberArray, astep: number, _W: NumberArray, Vt: NumberArray, vstep: number, m: number, n: number, n1: n... | random_line_split | ||
svd.ts | * Math.sqrt(1.0 + b * b);
}
if (b > 0) {
a /= b;
return b * Math.sqrt(1.0 + a * a);
}
return 0.0;
}
const EPSILON = 0.0000001192092896;
const FLT_MIN = 1E-37;
export function JacobiSVDImpl(At: NumberArray, astep: number, _W: NumberArray, Vt: NumberArray, vstep: number, m: number, n: n... |
}
}
sd = 0;
for (k = 0; k < m; k++) {
t = At[i * | {
At[i * astep + k] *= asum;
} | conditional_block |
svd.ts |
const EPSILON = 0.0000001192092896;
const FLT_MIN = 1E-37;
export function JacobiSVDImpl(At: NumberArray, astep: number, _W: NumberArray, Vt: NumberArray, vstep: number, m: number, n: number, n1: number) {
const eps = EPSILON * 2.0;
const minval = FLT_MIN;
let i = 0;
let j = 0;
let k = 0;
let... | {
a = Math.abs(a);
b = Math.abs(b);
if (a > b) {
b /= a;
return a * Math.sqrt(1.0 + b * b);
}
if (b > 0) {
a /= b;
return b * Math.sqrt(1.0 + a * a);
}
return 0.0;
} | identifier_body | |
svd.ts | (A: NumberArray, i0: number, i1: number, t: number) {
t = A[i0];
A[i0] = A[i1];
A[i1] = t;
}
export function hypot(a: number, b: number) {
a = Math.abs(a);
b = Math.abs(b);
if (a > b) {
b /= a;
return a * Math.sqrt(1.0 + b * b);
}
if (b > 0) {
a /= b;
ret... | swap | identifier_name | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
with open('HISTORY.rst') as history_file:
HISTORY = history_file.read()
| 'requests_cache',
]
TEST_REQUIREMENTS = [
'pytest',
'mock',
]
setup(
name='packyou',
version='0.1.6',
description="Downloads or clones a python project from github and allows to import it from anywhere. Very useful when the repo is not a package",
long_description=README + '\n\n' + HISTORY... | REQUIREMENTS = [
'gitpython',
'requests',
'tqdm', | random_line_split |
db.ts | import { Db, MongoClient } from "mongodb";
import { getRecipeId, IRecipe } from "./recipe";
import { getRecipeUnlockId, IRecipeUnlock } from "./recipeunlock";
interface ITimestamp {
timestamp: Date;
}
let dbPromise: Promise<Db> | null = null;
export const connect = () =>
dbPromise || (dbPromise = new Promise... |
}
interface IWrappedRecipe {
element: IRecipe[];
}
export const getRecipesForItems = async (...ids: number[]): Promise<IRecipe[]> => {
if (ids.length === 0) {
return [];
}
const db = await connect();
const orCondition = ids.map((id: number) => ({
"results.id": id,
}));
/* ... | {
super("No timestamp found on db.");
/* tslint:disable:max-line-length */
// see https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, NoTimestampError.prototype);
... | identifier_body |
db.ts | import { Db, MongoClient } from "mongodb";
import { getRecipeId, IRecipe } from "./recipe";
import { getRecipeUnlockId, IRecipeUnlock } from "./recipeunlock";
interface ITimestamp {
timestamp: Date;
}
let dbPromise: Promise<Db> | null = null;
export const connect = () =>
dbPromise || (dbPromise = new Promise... |
const db = await connect();
/* during updates, we could have more than one item with the same timestamp: here we filter them,
taking only the last one */
const unlocks = (await (await getRecipeUnlocksCollection())
.aggregate([
{ $match: { recipe_id: { $in: ids } } },
{ $... | {
return [];
} | conditional_block |
db.ts | import { Db, MongoClient } from "mongodb";
import { getRecipeId, IRecipe } from "./recipe";
import { getRecipeUnlockId, IRecipeUnlock } from "./recipeunlock";
interface ITimestamp {
timestamp: Date;
}
let dbPromise: Promise<Db> | null = null;
export const connect = () =>
dbPromise || (dbPromise = new Promise... | filter: { _id: extendedRecipeUnlock._id },
update: extendedRecipeUnlock,
upsert: true,
},
};
}),
{
ordered: false,
});
async function retry<T>(numRetry: number, func: () =... | updateOne: { | random_line_split |
db.ts | import { Db, MongoClient } from "mongodb";
import { getRecipeId, IRecipe } from "./recipe";
import { getRecipeUnlockId, IRecipeUnlock } from "./recipeunlock";
interface ITimestamp {
timestamp: Date;
}
let dbPromise: Promise<Db> | null = null;
export const connect = () =>
dbPromise || (dbPromise = new Promise... | <T>(numRetry: number, func: () => Promise<T>) {
// the whole retry cycle is due to: https://jira.mongodb.org/browse/SERVER-14322
let attempt = 0;
while (true) {
try {
return await func();
} catch (e) {
if (attempt < numRetry &&
e instanceof Error &&
... | retry | identifier_name |
typed-array-test-cases.js | /*
Copyright (c) 2019 The Khronos Group Inc.
Use of this source code is governed by an MIT-style license that can be
found in the LICENSE.txt file.
*/
// The "name" attribute is a concession to browsers which don't
// implement the "name" property on function objects.
var testCases =
[ {name: "Float32Array",
un... | },
{name: "Uint8Array",
unsigned: true,
integral: true,
elementSizeInBytes: 1,
testValues: [ 0, 255, -1, 256 ],
expectedValues: [ 0, 255, 255, 0 ]
},
{name: "Uint8ClampedArray",
unsigned: true,
integral: true,
elementSizeInBytes: 1,
testValues: [ 0... | unsigned: false,
integral: true,
elementSizeInBytes: 4,
testValues: [ -2147483648, 2147483647, -2147483649, 2147483648 ],
expectedValues: [ -2147483648, 2147483647, 2147483647, -2147483648 ] | random_line_split |
cubes.py | #python
import k3d
k3d.check_node_environment(context, "MeshSourceScript")
# Construct a cube mesh primitive ...
cubes = context.output.primitives().create("cube")
matrices = cubes.topology().create("matrices", "k3d::matrix4")
materials = cubes.topology().create("materials", "k3d::imaterial*")
uniform = cubes.attribu... |
matrices.append(k3d.translate3(k3d.vector3(0, 0, 0)))
materials.append(None)
color.append(k3d.color(0, 1, 0))
matrices.append(k3d.translate3(k3d.vector3(7, 0, 0)))
materials.append(None)
color.append(k3d.color(0, 0, 1))
print repr(context.output) | random_line_split | |
local.js | path = require("path");
udpRelay = require("./udprelay");
utils = require('./utils');
inet = require('./inet');
Encryptor = require("./encrypt").Encryptor;
connections = 0;
createServer = function(serverAddr, serverPort, port, key, method, timeout, local_address) {
var getServer, server, udpServ... | }
if (addrtype === 3) {
addrLen = data[4];
} else if (addrtype !== 1 && addrtype !== 4) {
utils.error("unsupported addrtype: " + addrtype);
connection.destroy();
return;
}
addrToSend = data.slice(3, 4).to... | {
try {
cmd = data[1];
addrtype = data[3];
if (cmd === 1) {
} else if (cmd === 3) {
utils.info("UDP assc request from " + connection.localAddress + ":" + connection.localPort);
reply = new Buffer(10);
reply.write("\u000... | conditional_block |
local.js | ");
path = require("path");
udpRelay = require("./udprelay");
utils = require('./utils');
inet = require('./inet');
Encryptor = require("./encrypt").Encryptor;
connections = 0;
createServer = function(serverAddr, serverPort, port, key, method, timeout, local_address) {
var getServer, server, ud... | });
connection.on("error", function(e) {
utils.debug("connection on error");
return utils.error("local error: " + e);
});
connection.on("close", function(had_error) {
connected = false;
utils.debug("connection on close:" + had_error);
if (had_error) {
... | utils.debug("connection on end");
if (remote) {
return remote.end();
} | random_line_split |
LazyValue.ts | /*
Copyright 2021 The Matrix.org Foundation C.I.C.
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 ... |
/**
* Whether or not a cached value is present.
*/
public get present(): boolean {
// we use a tracking variable just in case the final value is falsey
return this.done;
}
/**
* Gets the value without invoking a get. May be undefined until the
* value is fetched pr... | {
} | identifier_body |
LazyValue.ts | /*
Copyright 2021 The Matrix.org Foundation C.I.C.
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 ... | // Fork the promise chain to avoid accidentally making it return undefined always.
this.prom.then(v => {
this.val = v;
this.done = true;
});
return this.prom;
}
} | random_line_split | |
LazyValue.ts | /*
Copyright 2021 The Matrix.org Foundation C.I.C.
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 ... | (): Promise<T> {
if (this.prom) return this.prom;
this.prom = this.getFn();
// Fork the promise chain to avoid accidentally making it return undefined always.
this.prom.then(v => {
this.val = v;
this.done = true;
});
return this.prom;
}
}
| value | identifier_name |
rss_inputer.ts | import styled from 'styled-components'
import css from '@/utils/css'
import { theme } from '@/utils/themes'
import Input from '@/widgets/Input'
| /* width: 100%; */
`
export const Title = styled.div`
color: ${theme('thread.articleTitle')};
font-size: 18px;
margin-bottom: 20px;
margin-left: 8px;
`
export const InputerWrapper = styled.div`
position: relative;
`
export const Inputer = styled(Input)`
width: calc(100% - 20px);
color: ${theme('thread.a... | export const Wrapper = styled.div`
/* ${css.flexColumn('align-center')}; */ | random_line_split |
iflytek.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# iflytek.py ---
#
# Filename: iflytek.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Thu Sep 14 09:01:20 2017 (+0800)
#
# Change Log:
#
#
import time
from ctypes import *
from io import BytesIO
import wave
import platform
import logging
import os
... | (self, appid=None, voice_name=None, speed=None, volume=None, pitch=None):
self.__appid = not_none_return(appid, '59b4d5d4')
self.__voice_name = not_none_return(voice_name, 'xiaowanzi')
self.__speed = not_none_return(speed, 50)
self.__volume = not_none_return(volume, 50)
self.__pi... | __init__ | identifier_name |
iflytek.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# iflytek.py ---
#
# Filename: iflytek.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Thu Sep 14 09:01:20 2017 (+0800)
#
# Change Log:
#
#
import time
from ctypes import *
from io import BytesIO
import wave
import platform
import logging
import os
... |
return True
def get_tts_audio(self, src_text, filename, language='zh', options=None):
fname = os.path.join('/tmp/', filename + '.' + 'wav')
QTTSSessionBegin = self.__cur.QTTSSessionBegin
QTTSTextPut = self.__cur.QTTSTextPut
QTTSAudioGet = self.__cur.QTTSAudioGet
Q... | logging.error("MSPLogin failed, error code: {}".format(ret))
return False | conditional_block |
iflytek.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# iflytek.py ---
#
# Filename: iflytek.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Thu Sep 14 09:01:20 2017 (+0800)
#
# Change Log:
#
#
import time
from ctypes import *
from io import BytesIO
import wave
import platform
import logging
import os
... | return obj
else:
return defobj
class iflytekTTS():
def __init__(self, appid=None, voice_name=None, speed=None, volume=None, pitch=None):
self.__appid = not_none_return(appid, '59b4d5d4')
self.__voice_name = not_none_return(voice_name, 'xiaowanzi')
self.__speed = not_none... | BASEPATH=os.path.split(os.path.realpath(__file__))[0]
def not_none_return(obj, defobj):
if obj: | random_line_split |
iflytek.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# iflytek.py ---
#
# Filename: iflytek.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Thu Sep 14 09:01:20 2017 (+0800)
#
# Change Log:
#
#
import time
from ctypes import *
from io import BytesIO
import wave
import platform
import logging
import os
... |
def __save_file(self, raw_data, _tmpFile = '/tmp/test.wav'):
if os.path.exists(_tmpFile) :
return
tmpFile = _tmpFile + '.tmp'
with contextlib.closing(wave.open(tmpFile , 'w')) as f:
f.setparams((1, 2, 16000, 262720, 'NONE', 'not compressed'))
f.writefra... | self.__appid = not_none_return(appid, '59b4d5d4')
self.__voice_name = not_none_return(voice_name, 'xiaowanzi')
self.__speed = not_none_return(speed, 50)
self.__volume = not_none_return(volume, 50)
self.__pitch = not_none_return(pitch, 50)
self.__cur = cdll.LoadLibrary(os.path.joi... | identifier_body |
websocket.client.ts | /*
[ZYNAPTIC_CODE_FILE_HEADER STYLE="FULL" /]
[CREATED YEAR="16" MONTH="24" DAY="24" /]
[DESCRIPTION]Client Web Socket wrapper implementation[/DESCRIPTION]
[ZYNAPTIC_CODE_FILE_HEADER:BEGIN]
*/
/// <reference path="../typings/node.d.ts" />
/// <reference path="../typings/socket.io-client.d.ts" />
"use strict";
var pa... | {
socket: SocketIOClient.Socket;
constructor() {
console.log("WebSocket Client Create...");
}
public initAndStart() {
console.log("Initializing Web Socket Client...");
this.setupEventListeners();
this.initSocket();
}
// For an easy default behaviour, no params needed
// for io, it will try to use sam... | WebSocketClient | identifier_name |
websocket.client.ts | /*
[ZYNAPTIC_CODE_FILE_HEADER STYLE="FULL" /]
[CREATED YEAR="16" MONTH="24" DAY="24" /]
[DESCRIPTION]Client Web Socket wrapper implementation[/DESCRIPTION]
[ZYNAPTIC_CODE_FILE_HEADER:BEGIN]
*/
/// <reference path="../typings/node.d.ts" />
/// <reference path="../typings/socket.io-client.d.ts" />
"use strict";
var pa... | }
} | this.socket.on(WebSocketEvents.EVENT, function(data) {
console.log(WebSocketEvents.EVENT, data);
}); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.