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 |
|---|---|---|---|---|
votesctrl.js | var votesControllers = angular.module('votesControllers', []);
votesControllers.controller('VotesCtrl', ['$scope','$routeParams','$location', '$http','$rootScope','$cookies','GetVotes','GetLastVotes','GetVotesById',
function($scope,$routeParams,$location, $http,$rootScope,$cookies,GetVotes,GetLastVotes,GetVotesById) ... | GetVotes.query(json_data,function(data) {
console.log(data);
$scope.votes=data;
var matchid;
setTimeout(function(){
for (var i = 0; i < data.length; i++) {
matchid=data[i].match_id;
console.log(matchid);
$("... | $scope.pagination_number=1;
var json_data={data:{name:$scope.summoner,pagination:$scope.pagination}}; | random_line_split |
votesctrl.js |
var votesControllers = angular.module('votesControllers', []);
votesControllers.controller('VotesCtrl', ['$scope','$routeParams','$location', '$http','$rootScope','$cookies','GetVotes','GetLastVotes','GetVotesById',
function($scope,$routeParams,$location, $http,$rootScope,$cookies,GetVotes,GetLastVotes,GetVotesById)... |
}
}]);
| {
$('#decrease_pagination').fadeOut();
} | conditional_block |
Link.spec.js | import React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import 'styled-components-test-utils/lib/jest';
import getTheme from '../src/getTheme';
import Link from '../src/Link';
import * as utils from '../src/utils/';
const theme = getTheme({
font: {
size: '16px',
},
});
describe('Link',... | modifier: '&:hover',
}).toHaveStyleRule('color', 'white');
expect(spy).toHaveBeenCalled();
});
test('should have the correct font size', () => {
const component = ReactTestRenderer.create(
<Link
theme={theme}
/>,
);
expect(component).toHaveStyleRule('font-size', '16px'... | hoverColor="white"
/>,
);
expect({
component, | random_line_split |
ScanTargetStep.tsx | import * as React from 'react';
import {
Card,
CardHeader,
CardText,
} from 'material-ui/Card';
import {
IWorkflowStepProps,
WorkflowActionTargets,
} from './workflow';
import ActionButtonContainer from './ActionButtonContainer';
export default class ScanTargetStep extends React.Component<IWorkflowStepPro... | title={this.props.workflowStep.title}
/>
<CardText
style={{ flexGrow: 1 }}
>
This space intentionally left blank
</CardText>
<ActionButtonContainer
actions={this.props.workflowStep.actions}
onActionDispatched={this.onActionDispa... | containerStyle={ScanTargetStep.containerStyle}
expandable={false}
style={ScanTargetStep.rootStyle}
>
<CardHeader | random_line_split |
bmp180.py | Tijn/Tijndagamer
Copyright 2015-2017
Released under the MIT license.
"""
import smbus
import math
from time import sleep
class bmp180:
# Global variables
address = None
bus = smbus.SMBus(1)
mode = 1 # TODO: Add a way to change the mode
# BMP180 registers
CONTROL_REG = 0xF4
DATA_REG = 0xF6... | (self, register):
"""Reads an unsigned 16-bit value.
Reads the given register and the following, and combines them as an
unsigned 16-bit value.
register -- the register to read from.
Returns the read value.
"""
msb = self.bus.read_byte_data(self.address, register... | read_unsigned_16_bit | identifier_name |
bmp180.py | Tijn/Tijndagamer
Copyright 2015-2017
Released under the MIT license.
"""
import smbus
import math
from time import sleep
class bmp180:
# Global variables
address = None
bus = smbus.SMBus(1)
mode = 1 # TODO: Add a way to change the mode
# BMP180 registers
CONTROL_REG = 0xF4
DATA_REG = 0xF6... | X1 = ((UT - self.calAC6) * self.calAC5) / math.pow(2, 15)
X2 = (self.calMC * math.pow(2, 11)) / (X1 + self.calMD)
B5 = X1 + X2
# Todo: change math.pow cals to constants
B6 = B5 - 4000
X1 = (self.calB2 * (B6 * B6 / math.pow(2, 12))) / math.pow(2, 11)
X2 = self.cal... | """Reads and calculates the actual pressure.
Returns the actual pressure in Pascal.
"""
UP = self.get_raw_pressure()
UT = self.get_raw_temp()
B3 = 0
B4 = 0
B5 = 0
B6 = 0
B7 = 0
X1 = 0
X2 = 0
X3 = 0
pressure = 0
... | identifier_body |
bmp180.py | MrTijn/Tijndagamer
Copyright 2015-2017
Released under the MIT license.
"""
import smbus
import math
from time import sleep
class bmp180:
# Global variables
address = None
bus = smbus.SMBus(1)
mode = 1 # TODO: Add a way to change the mode
# BMP180 registers
CONTROL_REG = 0xF4
DATA_REG = 0... | def get_raw_pressure(self):
"""Reads and returns the raw pressure data."""
# Write appropriate data to sensor to start the measurement
self.bus.write_byte_data(self.address, self.CONTROL_REG, 0x34 + (self.mode << 6))
# Sleep for 8 ms.
# TODO: Way to use the correct wait time... | random_line_split | |
bmp180.py | Tijn/Tijndagamer
Copyright 2015-2017
Released under the MIT license.
"""
import smbus
import math
from time import sleep
class bmp180:
# Global variables
address = None
bus = smbus.SMBus(1)
mode = 1 # TODO: Add a way to change the mode
# BMP180 registers
CONTROL_REG = 0xF4
DATA_REG = 0xF6... |
X1 = (pressure / math.pow(2, 8)) * (pressure / math.pow(2, 8))
X1 = (X1 * 3038) / math.pow(2, 16)
X2 = (-7357 * pressure) / math.pow(2, 16)
pressure = pressure + (X1 + X2 + 3791) / math.pow(2, 4)
return pressure
def get_altitude(self, sea_level_pressure = 101325):
... | pressure = (B7 / B4) * 2 | conditional_block |
util.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Import zero symbols from zone.js. This causes the zone ambient type to be
// added to the type-checker, without e... | return '[' + token.map(stringify).join(', ') + ']';
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
const res = token.toString();
if (res == null) {
return '' + res;
}
... | }
if (token instanceof Array) { | random_line_split |
util.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Import zero symbols from zone.js. This causes the zone ambient type to be
// added to the type-checker, without e... |
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
const res = token.toString();
if (res == null) {
return '' + res;
}
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}... | {
return '' + token;
} | conditional_block |
util.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Import zero symbols from zone.js. This causes the zone ambient type to be
// added to the type-checker, without e... | (token: any): string {
if (typeof token === 'string') {
return token;
}
if (token instanceof Array) {
return '[' + token.map(stringify).join(', ') + ']';
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
... | stringify | identifier_name |
util.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Import zero symbols from zone.js. This causes the zone ambient type to be
// added to the type-checker, without e... |
// JS has NaN !== NaN
export function looseIdentical(a: any, b: any): boolean {
return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
}
export function stringify(token: any): string {
if (typeof token === 'string') {
return token;
}
if (token instanceof Array) {
r... | {
if (typeof Zone === 'undefined') {
// use promise to schedule microTask instead of use Zone
promise.then(() => { fn && fn.apply(null, null); });
} else {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
} | identifier_body |
mod.rs | //!Routers stores request handlers, using an HTTP method and a path as keys.
//!
//!Rustful provides a tree structured all-round router called `TreeRouter`,
//!but any other type of router can be used, as long as it implements the
//!`Router` trait. This will also make it possible to initialize it using the
//![`insert... | (handler: Option<&'a T>) -> Endpoint<'a, T> {
Endpoint {
handler: handler,
variables: HashMap::new(),
hypermedia: Hypermedia::new()
}
}
}
///A common trait for routers.
///
///A router must to implement this trait to be usable in a Rustful server. This
///trait w... | from | identifier_name |
mod.rs | //!Routers stores request handlers, using an HTTP method and a path as keys.
//!
//!Rustful provides a tree structured all-round router called `TreeRouter`,
//!but any other type of router can be used, as long as it implements the
//!`Router` trait. This will also make it possible to initialize it using the
//![`insert... |
impl<'a> Route<'a> for str {
type Segments = RouteIter<Split<'a, u8, fn(&u8) -> bool>>;
fn segments(&'a self) -> <Self as Route<'a>>::Segments {
self.as_bytes().segments()
}
}
impl<'a> Route<'a> for [u8] {
type Segments = RouteIter<Split<'a, u8, fn(&u8) -> bool>>;
fn segments(&'a self) ... | {
*c == b'/'
} | identifier_body |
mod.rs | //!Routers stores request handlers, using an HTTP method and a path as keys.
//!
//!Rustful provides a tree structured all-round router called `TreeRouter`,
//!but any other type of router can be used, as long as it implements the
//!`Router` trait. This will also make it possible to initialize it using the
//![`insert... | //!multiple times. This can be useful to lower the risk of typing errors,
//!among other things.
//!
//!Routes may also be added using the insert method, like this:
//!
//!```
//!extern crate rustful;
//!use rustful::Method::Get;
//!use rustful::{Router, TreeRouter};
//!# use rustful::{Handler, Context, Response};
//!
... | //!```
//!
//!This macro creates the same structure as the example below, but it allows
//!tree structures to be defined without the need to write the same paths | random_line_split |
util.py | from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... | (*args, **kwargs):
# Tell python-dbus that "sender" will be the keyword to use for the sender unless otherwise
# defined.
kwargs.setdefault("sender_keyword", "sender")
return dbus.service.method(*args, **kwargs)
def dbus_service_signal(*args, **kwargs):
"""
Decorator used for signal
:param... | dbus_service_method | identifier_name |
util.py | from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... |
# Raise exception string as JSON string. Thus it can be parsed and printed properly.
error_msg = json.dumps(
{
"exception": type(err).__name__,
"severity": severity,
"message": err_msg
}
)
six.reraise(exceptions.RHS... | severity = err.severity | conditional_block |
util.py | from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... | "exception": type(err).__name__,
"severity": severity,
"message": err_msg
}
)
six.reraise(exceptions.RHSM1DBusException, exceptions.RHSM1DBusException(error_msg), trace)
def dbus_service_method(*args, **kwargs):
# Tell python-dbus that "... | """Decorator to handle exceptions, log them, and wrap them if necessary"""
try:
ret = func(*args, **kwargs)
return ret
except Exception as err:
log.exception(err)
trace = sys.exc_info()[2]
severity = "error"
# Remove "HTTP error (...): " string from the messages:... | identifier_body |
util.py | from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... | if hasattr(err, 'severity'):
severity = err.severity
# Raise exception string as JSON string. Thus it can be parsed and printed properly.
error_msg = json.dumps(
{
"exception": type(err).__name__,
"severity": severity,
"mess... | random_line_split | |
post-process-phase-spec.ts | import path from 'path';
import { DataEntity, debugLogger } from '@terascope/utils';
import {
OperationsManager, PostProcessPhase, Loader, PostProcessingDict
} from '../../src';
describe('post_process phase', () => {
const logger = debugLogger('postProcessPhaseTest');
const opManager = new OperationsManage... | (s: string) {
return Buffer.from(s).toString('base64');
}
const str = 'hello';
const data = [
new DataEntity({ host: 'www.example.com', field1: `${encode(str)}` }, { selectors: ['host:example.com'] }),
new DataEntity({ host: 'www.example.com', field1: {} }, { ... | encode | identifier_name |
post-process-phase-spec.ts | import path from 'path';
import { DataEntity, debugLogger } from '@terascope/utils';
import {
OperationsManager, PostProcessPhase, Loader, PostProcessingDict
} from '../../src';
describe('post_process phase', () => {
const logger = debugLogger('postProcessPhaseTest');
const opManager = new OperationsManage... |
const str = 'hello';
const data = [
new DataEntity({ host: 'www.example.com', field1: `${encode(str)}` }, { selectors: ['host:example.com'] }),
new DataEntity({ host: 'www.example.com', field1: {} }, { selectors: ['host:example.com'] }),
new DataEntity(
... | {
return Buffer.from(s).toString('base64');
} | identifier_body |
post-process-phase-spec.ts | import path from 'path';
import { DataEntity, debugLogger } from '@terascope/utils';
import {
OperationsManager, PostProcessPhase, Loader, PostProcessingDict
} from '../../src';
describe('post_process phase', () => {
const logger = debugLogger('postProcessPhaseTest');
const opManager = new OperationsManage... | }); | random_line_split | |
crm_partner_assign.py | Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU A... |
for lead in self.browse(cr, uid, ids, context=context):
if not partner_id:
partner_id = partner_ids.get(lead.id, False)
if not partner_id:
continue
self.assign_geo_localize(cr, uid, [lead.id], lead.partner_latitude, lead.partner_longitude, con... | partner_ids = self.search_geo_partner(cr, uid, ids, context=context) | conditional_block |
crm_partner_assign.py | Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU A... |
def assign_partner(self, cr, uid, ids, partner_id=False, context=None):
partner_ids = {}
res = False
res_partner = self.pool.get('res.partner')
if not partner_id:
partner_ids = self.search_geo_partner(cr, uid, ids, context=context)
for lead in self.browse(cr, uid... | random_line_split | |
crm_partner_assign.py | Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU A... | (self, cr, uid, ids, partner_assigned_id, context=None):
"""This function updates the "assignation date" automatically, when manually assign a partner in the geo assign tab
"""
if not partner_assigned_id:
return {'value':{'date_assign': False}}
else:
partners = s... | onchange_assign_id | identifier_name |
crm_partner_assign.py | Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU A... |
class res_partner_activation(osv.osv):
_name = 'res.partner.activation'
_order = 'sequence'
_columns = {
'sequence' : fields.integer('Sequence'),
'name' : fields.char('Name', size=32, required=True),
}
class res_partner(osv.osv):
_inherit = "res.partner"
_columns = {
... | _order = 'sequence'
_name = 'res.partner.grade'
_columns = {
'sequence': fields.integer('Sequence'),
'active': fields.boolean('Active'),
'name': fields.char('Grade Name', size=32),
'partner_weight': fields.integer('Grade Weight',
help="Gives the probability to assign ... | identifier_body |
backgroundImage.js | /**
* Created by User on 2/26/2015.
*/
'use strict';
angular.module('common').directive('backgroundImage', ['$timeout', function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var imgSrc = attrs['backgroundImage'];
var bodyBgImage = new Image... |
bodyBgImage.onload = function() {
document.getElementsByTagName("html")[0].className = "height100pcnt bg-body";
document.getElementsByTagName("body")[0].className = "bg-body";
};
}
};
}]); | random_line_split | |
os_tenant_networks.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 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.apach... |
def _sync_networks(context, project_id, session):
ctx = nova_context.RequestContext(user_id=None, project_id=project_id)
ctx = ctx.elevated()
networks = nova.network.api.API().get_all(ctx)
return dict(networks=len(networks))
if CONF.enable_network_quota:
QUOTAS.register_resource(quota.Reservabl... | """Tenant-based Network Management Extension."""
name = "OSTenantNetworks"
alias = "os-tenant-networks"
namespace = ("http://docs.openstack.org/compute/"
"ext/os-tenant-networks/api/v2")
updated = "2012-03-07T09:46:43-05:00"
def get_resources(self):
ext = extensions.Resour... | identifier_body |
os_tenant_networks.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 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.apach... |
except Exception:
if CONF.enable_network_quota:
QUOTAS.rollback(context, reservation)
msg = _("Create networks failed")
LOG.exception(msg, extra=network)
raise exc.HTTPServiceUnavailable(explanation=msg)
return {"network": network_dict(net... | QUOTAS.commit(context, reservation) | conditional_block |
os_tenant_networks.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 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.apach... | except netexc.AddrConversionError:
msg = _("Address could not be converted.")
raise exc.HTTPBadRequest(explanation=msg)
networks = []
try:
if CONF.enable_network_quota:
reservation = QUOTAS.reserve(context, networks=1)
exce... | raise exc.HTTPBadRequest(explanation=msg)
except netexc.AddrFormatError:
msg = _("CIDR is malformed.")
raise exc.HTTPBadRequest(explanation=msg) | random_line_split |
os_tenant_networks.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 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.apach... | (network):
return {"id": network.get("uuid") or network.get("id"),
"cidr": network.get("cidr"),
"label": network.get("label")}
class NetworkController(object):
def __init__(self, network_api=None):
self.network_api = nova.network.API()
self._defa... | network_dict | identifier_name |
main.js | 'use strict';
var Foundationify = (function () {
// Initalize product image gallery function on product pages
function | () {
// Define the scope
var $productImages = $('#product-images', 'body.product');
// Select the thumbnails
var $thumbs = $('ul img', $productImages);
if ($thumbs.length) {
// Select the large image
var $largeImage = $('img', $productImages).first();
// Change the large image src and alt attrib... | initProductImages | identifier_name |
main.js | 'use strict';
var Foundationify = (function () {
// Initalize product image gallery function on product pages
function initProductImages() | }
// Change the cursor to the loading cursor
$('body').css('cursor', 'progress');
// Change the src and alt attributes of the large image
$largeImage.attr('src', $(this).parent('a').attr('href'))
.attr('alt', $(this).attr('alt'));
});
// Return the loading cursor to default after ... | {
// Define the scope
var $productImages = $('#product-images', 'body.product');
// Select the thumbnails
var $thumbs = $('ul img', $productImages);
if ($thumbs.length) {
// Select the large image
var $largeImage = $('img', $productImages).first();
// Change the large image src and alt attribute... | identifier_body |
main.js | 'use strict';
var Foundationify = (function () {
// Initalize product image gallery function on product pages
function initProductImages() {
// Define the scope
var $productImages = $('#product-images', 'body.product');
// Select the thumbnails
var $thumbs = $('ul img', $productImages);
if ($thumbs.len... |
// Change the cursor to the loading cursor
$('body').css('cursor', 'progress');
// Change the src and alt attributes of the large image
$largeImage.attr('src', $(this).parent('a').attr('href'))
.attr('alt', $(this).attr('alt'));
});
// Return the loading cursor to default after the l... | {
return;
} | conditional_block |
main.js | 'use strict';
var Foundationify = (function () {
// Initalize product image gallery function on product pages
function initProductImages() {
// Define the scope
var $productImages = $('#product-images', 'body.product');
// Select the thumbnails | if ($thumbs.length) {
// Select the large image
var $largeImage = $('img', $productImages).first();
// Change the large image src and alt attributes on click
$thumbs.on('click', function (e) {
e.preventDefault();
// Skip if thumb matches large
if ($largeImage.attr('src') === $(this).parent(... | var $thumbs = $('ul img', $productImages);
| random_line_split |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (PythonPackage):
"""A fast implementation of the Cassowary constraint solver"""
homepage = "https://github.com/nucleic/kiwi"
pypi = "kiwisolver/kiwisolver-1.1.0.tar.gz"
version('1.3.2', sha256='fc4453705b81d03568d5b808ad8f09c77c47534f6ac2e72e733f9ca4714aa75c')
version('1.3.1', sha256='950a199911a8... | PyKiwisolver | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyKiwisolver(PythonPackage):
| """A fast implementation of the Cassowary constraint solver"""
homepage = "https://github.com/nucleic/kiwi"
pypi = "kiwisolver/kiwisolver-1.1.0.tar.gz"
version('1.3.2', sha256='fc4453705b81d03568d5b808ad8f09c77c47534f6ac2e72e733f9ca4714aa75c')
version('1.3.1', sha256='950a199911a8d94683a6b10321f9345d5... | identifier_body | |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyKiwisolver(PythonPackage):
"""A fast implementation of the Cassowary constraint solver""... | depends_on('py-cppy@1.1.0:', type='build', when='@1.2.0:') | random_line_split | |
assign_mutable_fields.rs | // Copyright 2017 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-MIT or ... | () {
let mut x: (u32, u32);
x.0 = 1;
x.1 = 22;
drop(x); //~ ERROR
}
fn main() { }
| assign_both_fields_the_use_var | identifier_name |
assign_mutable_fields.rs | // Copyright 2017 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-MIT or ... |
// Currently, we permit you to assign to individual fields of a mut
// var, but we do not permit you to use the complete var afterwards.
// We hope to fix this at some point.
//
// FIXME(#21232)
fn assign_both_fields_and_use() {
let mut x: (u32, u32);
x.0 = 1;
x.1 = 22;
drop(x.0); //~ ERROR
drop(x... | // option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
assign_mutable_fields.rs | // Copyright 2017 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-MIT or ... | { } | identifier_body | |
inlineDocs.tsx | import React from 'react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import {loadDocs} from 'app/actionCreators/projects';
import {Client} from 'app/api';
import LoadingIndicator from 'app/components/loadingIndicator';
import {PlatformKey} from 'app/data/platformCategories';
import... | () {
this.fetchData();
}
fetchData = async () => {
const {platform, api, orgSlug, projectSlug} = this.props;
if (!platform) {
return;
}
this.setState({loading: true});
let tracingPlatform: PlatformKey;
switch (platform) {
case 'sentry.python': {
tracingPlatform = ... | componentDidMount | identifier_name |
inlineDocs.tsx | import React from 'react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import {loadDocs} from 'app/actionCreators/projects';
import {Client} from 'app/api';
import LoadingIndicator from 'app/components/loadingIndicator';
import {PlatformKey} from 'app/data/platformCategories';
import... |
if (this.state.loading) {
return (
<div>
<LoadingIndicator />
</div>
);
}
if (this.state.html) {
return (
<div>
<h4>{t('Requires Manual Instrumentation')}</h4>
<DocumentationWrapper dangerouslySetInnerHTML={{__html: this.state.html}}... | {
return null;
} | conditional_block |
inlineDocs.tsx | import React from 'react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import {loadDocs} from 'app/actionCreators/projects';
import {Client} from 'app/api';
import LoadingIndicator from 'app/components/loadingIndicator';
import {PlatformKey} from 'app/data/platformCategories';
import... | tracingPlatform = 'python-tracing';
break;
}
case 'sentry.javascript.node': {
tracingPlatform = 'node-tracing';
break;
}
default: {
this.setState({loading: false});
return;
}
}
try {
const {html, link} = await loadDocs(api, org... | this.setState({loading: true});
let tracingPlatform: PlatformKey;
switch (platform) {
case 'sentry.python': { | random_line_split |
inlineDocs.tsx | import React from 'react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import {loadDocs} from 'app/actionCreators/projects';
import {Client} from 'app/api';
import LoadingIndicator from 'app/components/loadingIndicator';
import {PlatformKey} from 'app/data/platformCategories';
import... |
fetchData = async () => {
const {platform, api, orgSlug, projectSlug} = this.props;
if (!platform) {
return;
}
this.setState({loading: true});
let tracingPlatform: PlatformKey;
switch (platform) {
case 'sentry.python': {
tracingPlatform = 'python-tracing';
brea... | {
this.fetchData();
} | identifier_body |
textInputFloatingFilter.ts | import { IFloatingFilterParams } from '../floatingFilter';
import { RefSelector } from '../../../widgets/componentAnnotations';
import { ProvidedFilterModel } from '../../../interfaces/iFilter';
import { debounce } from '../../../utils/function';
import { ProvidedFilter } from '../../provided/providedFilter';
import { ... |
public onParentModelChanged(model: ProvidedFilterModel, event: FilterChangedEvent): void {
if (this.isEventFromFloatingFilter(event)) {
// if the floating filter triggered the change, it is already in sync
return;
}
this.setLastTypeFromModel(model);
this.eF... | {
return 500;
} | identifier_body |
textInputFloatingFilter.ts | import { IFloatingFilterParams } from '../floatingFilter';
import { RefSelector } from '../../../widgets/componentAnnotations';
import { ProvidedFilterModel } from '../../../interfaces/iFilter';
import { debounce } from '../../../utils/function';
import { ProvidedFilter } from '../../provided/providedFilter';
import { ... | (editable: boolean): void {
this.eFloatingFilterInput.setDisabled(!editable);
}
}
| setEditable | identifier_name |
textInputFloatingFilter.ts | import { IFloatingFilterParams } from '../floatingFilter';
import { RefSelector } from '../../../widgets/componentAnnotations';
import { ProvidedFilterModel } from '../../../interfaces/iFilter';
import { debounce } from '../../../utils/function';
import { ProvidedFilter } from '../../provided/providedFilter';
import { ... |
this.setLastTypeFromModel(model);
this.eFloatingFilterInput.setValue(this.getTextFromModel(model));
this.setEditable(this.canWeEditAfterModelFromParentFilter(model));
}
public init(params: IFloatingFilterParams): void {
super.init(params);
this.params = params;
... | {
// if the floating filter triggered the change, it is already in sync
return;
} | conditional_block |
textInputFloatingFilter.ts | import { IFloatingFilterParams } from '../floatingFilter';
import { RefSelector } from '../../../widgets/componentAnnotations';
import { ProvidedFilterModel } from '../../../interfaces/iFilter';
import { debounce } from '../../../utils/function';
import { ProvidedFilter } from '../../provided/providedFilter';
import { ... | <ag-input-text-field ref="eFloatingFilterInput"></ag-input-text-field>
</div>`);
}
protected getDefaultDebounceMs(): number {
return 500;
}
public onParentModelChanged(model: ProvidedFilterModel, event: FilterChangedEvent): void {
if (this.isEventFromFloatin... | @PostConstruct
private postConstruct(): void {
this.setTemplate(/* html */`
<div class="ag-floating-filter-input" role="presentation"> | random_line_split |
plugin.ts | /**
* Created by johan on 11/11/2015.
*/
var router = require('express').Router();
var pwd = require('path');
router.get('/:name', function (req, res) {
var pluginName = req.params.name;
var data = req.query;
console.log(data);
var plugin: any = getModule(data.path, data.script);
console.lo... |
plugin = new plugin.Index();
plugin.action(data, function (response) {
//console.log(response);
res.send(response);
//_actionPluginResponse(res, response);
}, JSON.parse(data.config));
});
var getModule = function (pathPlugin, script) {
var module = false;
var path = ... | {
console.log('Error in load plugin :' + pluginName);
res.send(400);
return;
} | conditional_block |
plugin.ts | /**
* Created by johan on 11/11/2015.
*/
var router = require('express').Router();
var pwd = require('path');
router.get('/:name', function (req, res) {
var pluginName = req.params.name;
var data = req.query;
console.log(data);
var plugin: any = getModule(data.path, data.script);
console.lo... |
module.exports = router; | {
delete require.cache[require.resolve(module)]
return require(module)
} | identifier_body |
plugin.ts | /**
* Created by johan on 11/11/2015.
*/
var router = require('express').Router();
var pwd = require('path');
router.get('/:name', function (req, res) {
var pluginName = req.params.name;
var data = req.query;
console.log(data);
var plugin: any = getModule(data.path, data.script);
console.lo... | (module) {
delete require.cache[require.resolve(module)]
return require(module)
}
module.exports = router; | requireUncached | identifier_name |
plugin.ts | /**
* Created by johan on 11/11/2015.
*/
var router = require('express').Router();
var pwd = require('path');
router.get('/:name', function (req, res) {
var pluginName = req.params.name;
var data = req.query;
console.log(data);
| console.log('plugin : ' + pluginName);
console.log('params : ' + JSON.stringify(req.body));
if (!plugin) {
console.log('Error in load plugin :' + pluginName);
res.send(400);
return;
}
plugin = new plugin.Index();
plugin.action(data, function (response) {
//cons... | var plugin: any = getModule(data.path, data.script);
| random_line_split |
route.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chalk = require("chalk");
const utils_1 = require("../../utils");
const index_1 = require("./index");
const index_2 = require("../../http/index");
/**
* @description Registers application routes.
*
* @export
* @class RouteRegister
*... | // Register express route.
this.application[defaultMethod](uri, (request, response) => {
// Check if any of the required params are missing.
let required = new index_1.RouteRequired().verify(request, Reflect.getMetadata('unison:requ... | {
for (let component of this.components) {
// Retrive the component metadata. This will be used to get the
// component configuration for things like "routeUrl" and "method".
let metadata = Reflect.getMetadata('unison:component', component);
for (let method of uti... | identifier_body |
route.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chalk = require("chalk");
const utils_1 = require("../../utils"); | * @export
* @class RouteRegister
*/
class RouteRegister {
constructor(components, injectables, application) {
this.components = components;
this.injectables = injectables;
this.application = application;
this.initialize();
}
/**
* @description - Registers application ... | const index_1 = require("./index");
const index_2 = require("../../http/index");
/**
* @description Registers application routes.
* | random_line_split |
route.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chalk = require("chalk");
const utils_1 = require("../../utils");
const index_1 = require("./index");
const index_2 = require("../../http/index");
/**
* @description Registers application routes.
*
* @export
* @class RouteRegister
*... | {
constructor(components, injectables, application) {
this.components = components;
this.injectables = injectables;
this.application = application;
this.initialize();
}
/**
* @description - Registers application routes.
*
* @private
*
* @memberOf Rou... | RouteRegister | identifier_name |
route.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chalk = require("chalk");
const utils_1 = require("../../utils");
const index_1 = require("./index");
const index_2 = require("../../http/index");
/**
* @description Registers application routes.
*
* @export
* @class RouteRegister
*... |
new component(...dependencies)[method](request, response)
.catch(error => { });
})
.catch(error => { });
});
this.logRoute(uri, defaultMethod);
}
... | {
for (let dependency of Reflect.getMetadata('design:paramtypes', component))
dependencies.push(this.injectables[utils_1.ClassName(dependency)]);
} | conditional_block |
IArrayUtils.ts | export interface IArrayUtils { | * @param length
* @return {number[]}
*/
createWithRange (length: number): number[];
/**
* @param {number} length
* @param {(index: number) => TValue} valueFunction
* @returns {TValue[]}
*/
fillWithRange <TValue> (length: number, valueFunction: (index: number) => TValue): ... | /** | random_line_split |
util.py | hop-by-hop
# headers, but they are in the purview of the
# origin server which the WSGI spec says we should
# act like. So we drop them and add our own.
#
# In the future, concatenation server header values
# might be better, but nothing else does it and
# dropping them is easier.
hop_headers = set("""
connection ... | maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if (maxfd == resource.RLIM_INFINITY):
maxfd = MAXFD
return maxfd
def close_on_exec(fd):
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(fd, fcntl.F_SETFD, flags)
def set_non_blocking(fd):
flags = f... | return (host, port)
def get_maxfd(): | random_line_split |
util.py | -by-hop
# headers, but they are in the purview of the
# origin server which the WSGI spec says we should
# act like. So we drop them and add our own.
#
# In the future, concatenation server header values
# might be better, but nothing else does it and
# dropping them is easier.
hop_headers = set("""
connection keep... | (filename):
_waitfor(os.unlink, filename)
else:
_unlink = os.unlink
def unlink(filename):
try:
_unlink(filename)
except OSError as error:
# The filename need not exist.
if error.errno not in (errno.ENOENT, errno.ENOTDIR):
raise
def is_ipv6(addr):
try:
... | _unlink | identifier_name |
util.py | == 1:
try:
if uri.startswith("#"):
uri = uri[1:]
return pkg_resources.load_entry_point("gunicorn",
section, uri)
except:
exc = traceback.format_exc()
raise RuntimeError("class uri %r... | if os.fork():
os._exit(0)
os.setsid()
if os.fork():
os._exit(0)
os.umask(0)
maxfd = get_maxfd()
closerange(0, maxfd)
os.open(REDIRECT_TO, os.O_RDWR)
os.dup2(0, 1)
os.dup2(0, 2) | conditional_block | |
util.py | setproctitle
def _setproctitle(title):
setproctitle("gunicorn: %s" % title)
except ImportError:
def _setproctitle(title):
return
try:
from importlib import import_module
except ImportError:
def _resolve_name(name, package, level):
"""Return the absolute name of the module to b... | return "-".join([w.lower().capitalize() for w in name.split("-")]) | identifier_body | |
vec_map.rs | #[derive(Clone)]
pub struct VecMap<K, V> {
vec: Vec<(K, V)>,
}
impl<K: PartialEq, V> VecMap<K, V> {
pub fn new() -> VecMap<K, V> {
VecMap {
vec: Vec::new()
}
}
pub fn insert(&mut self, key: K, value: V) {
match self.find(&key) {
Some(pos) => self.vec[pos... | (&self, key: &K) -> bool {
self.find(key).is_some()
}
pub fn len(&self) -> usize { self.vec.len() }
pub fn iter(&self) -> ::std::slice::Iter<(K, V)> {
self.vec.iter()
}
pub fn remove(&mut self, key: &K) -> Option<V> {
self.find(key).map(|pos| self.vec.remove(pos)).map(|(_, v... | contains_key | identifier_name |
vec_map.rs | #[derive(Clone)]
pub struct VecMap<K, V> {
vec: Vec<(K, V)>,
}
impl<K: PartialEq, V> VecMap<K, V> {
pub fn new() -> VecMap<K, V> {
VecMap {
vec: Vec::new()
}
}
pub fn insert(&mut self, key: K, value: V) |
pub fn entry(&mut self, key: K) -> Entry<K, V> {
match self.find(&key) {
Some(pos) => Entry::Occupied(OccupiedEntry {
vec: self,
pos: pos,
}),
None => Entry::Vacant(VacantEntry {
vec: self,
key: key,
... | {
match self.find(&key) {
Some(pos) => self.vec[pos] = (key, value),
None => self.vec.push((key, value))
}
} | identifier_body |
vec_map.rs | #[derive(Clone)]
pub struct VecMap<K, V> {
vec: Vec<(K, V)>,
}
impl<K: PartialEq, V> VecMap<K, V> {
pub fn new() -> VecMap<K, V> {
VecMap {
vec: Vec::new()
}
}
pub fn insert(&mut self, key: K, value: V) {
match self.find(&key) {
Some(pos) => self.vec[pos... | self.find(key).is_some()
}
pub fn len(&self) -> usize { self.vec.len() }
pub fn iter(&self) -> ::std::slice::Iter<(K, V)> {
self.vec.iter()
}
pub fn remove(&mut self, key: &K) -> Option<V> {
self.find(key).map(|pos| self.vec.remove(pos)).map(|(_, v)| v)
}
pub fn clea... |
pub fn contains_key(&self, key: &K) -> bool { | random_line_split |
ZkPaths.ts | /**
* @module node-zk-treecache
*/
/** */
import { validatePath } from "./PathUtils"
import { Client, ACL, Id, CreateMode, Exception } from "node-zookeeper-client"
const PATH_SEPARATOR = "/"
const ANYONE_ID_UNSAFE = new Id("world", "anyone")
const OPEN_ACL_UNSAFE = [new ACL(31, ANYONE_ID_UNSAFE)]
const EMPTY_CALLB... | throw new Error(`Error while validating ${path}, it should have been valid`)
return last
}
/**
* Given a parent path and a child node, create a combined full path
*
* @param parent the parent
* @param child the child
* @return full path
*/
export function makePath(parent: string, child: string): string {... |
const last = path.split(PATH_SEPARATOR).pop()
if (last === undefined) | random_line_split |
ZkPaths.ts | /**
* @module node-zk-treecache
*/
/** */
import { validatePath } from "./PathUtils"
import { Client, ACL, Id, CreateMode, Exception } from "node-zookeeper-client"
const PATH_SEPARATOR = "/"
const ANYONE_ID_UNSAFE = new Id("world", "anyone")
const OPEN_ACL_UNSAFE = [new ACL(31, ANYONE_ID_UNSAFE)]
const EMPTY_CALLB... | (asContainers: boolean) {
return CreateMode.PERSISTENT
}
/**
* Make sure all the nodes in the path are created. NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish
* between directories and files. So, every node in the path is created. The data for each node is an empty blob
*
* @private
* @param zkClient... | getCreateMode | identifier_name |
ZkPaths.ts | /**
* @module node-zk-treecache
*/
/** */
import { validatePath } from "./PathUtils"
import { Client, ACL, Id, CreateMode, Exception } from "node-zookeeper-client"
const PATH_SEPARATOR = "/"
const ANYONE_ID_UNSAFE = new Id("world", "anyone")
const OPEN_ACL_UNSAFE = [new ACL(31, ANYONE_ID_UNSAFE)]
const EMPTY_CALLB... |
}
/**
* @private
* @param path the path to split
*/
export function split(path: string): string[] {
validatePath(path)
return path.split(PATH_SEPARATOR).filter(s => s.length > 0)
}
export interface ACLProvider {
getDefaultAcl(): ACL[] | null
getAclForPath(path: string): ACL[] | null
}
// Verify if we ar... | {
return null
} | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
from flask import Flask
from flask.views import http_method_funcs
from .auth import secure
from .config import config_autoapi
from .messages import message
from .operations import invalid_operation, login, logout, password, roles, user
from .views import get, post, delete, put, patch
class Au... | """ Implement this method to add more routes """
pass | identifier_body | |
__init__.py | # -*- coding: utf-8 -*-
from flask import Flask
from flask.views import http_method_funcs
from .auth import secure
from .config import config_autoapi
from .messages import message
from .operations import invalid_operation, login, logout, password, roles, user
from .views import get, post, delete, put, patch
class | (Flask):
def __init__(self, auth=False, cors=True, port=None):
super(AutoApi, self).__init__(self.__class__.__name__)
self.auth = auth
self.cors = cors
config_autoapi(self, cors=cors, force_port=port)
# AutoApi operation routes
self.prefix = 'AutoApi'
self.l... | AutoApi | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
from flask import Flask
from flask.views import http_method_funcs
from .auth import secure
from .config import config_autoapi
from .messages import message
from .operations import invalid_operation, login, logout, password, roles, user
from .views import get, post, delete, put, patch
class Au... | # AutoApi rest routes
self.prefix = 'AutoApi'
self.load_api_rest()
def welcome(self):
return message('Welcome to AutoApi.')
def _name(self, view):
return '{prefix}.{name}'.format(prefix=self.prefix, name=view.__name__)
def add(
self, path, view, api=None, s... | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
from flask import Flask
from flask.views import http_method_funcs
from .auth import secure
from .config import config_autoapi
from .messages import message
from .operations import invalid_operation, login, logout, password, roles, user
from .views import get, post, delete, put, patch
class Au... |
def load_api_rest(self):
""" Bind automatic API REST for AutoApi """
path = '/<api>/<path:path>'
self.add(path, get, method='GET', role='read')
self.add(path, post, method='POST', role='create')
self.add(path, delete, method='DELETE', role='delete')
self.add(path, ... | self.add('/login', login, skip_auth=True)
self.add('/logout', logout)
self.add('/user', user, role='admin')
self.add('/password', password)
self.add('/roles', roles, role='admin') | conditional_block |
reftest.rs | = env::args().collect();
let mut parts = args[1..].split(|e| &**e == "--");
let harness_args = parts.next().unwrap(); // .split() is never empty
let servo_args = parts.next().unwrap_or(&[]);
let (render_mode_string, base_path, testnames) = match harness_args {
[ref render_mode_string, ref ba... | let mut tests = parse_lists(&file, testnames, servo_args, render_mode, len);
println!("\t{} [{} tests]", file.display(), tests.len());
all_tests.append(&mut tests);
}
}
_ => {}
}
}
let test_opts = TestOp... | if extension == OsStr::new("list") && file.is_file() {
let len = all_tests.len(); | random_line_split |
reftest.rs | = env::args().collect();
let mut parts = args[1..].split(|e| &**e == "--");
let harness_args = parts.next().unwrap(); // .split() is never empty
let servo_args = parts.next().unwrap_or(&[]);
let (render_mode_string, base_path, testnames) = match harness_args {
[ref render_mode_string, ref ba... | (file: &Path,
filters: &[String],
servo_args: &[String],
render_mode: RenderMode,
id_offset: usize)
-> Vec<TestDescAndFn> {
let mut tests = Vec::new();
let contents = {
let mut f = File::open(file).unwrap();
let mut conte... | parse_lists | identifier_name |
forms.py | # -*- coding: utf-8 -*-
import re
from django.forms import ValidationError, ModelForm, Form, CharField, PasswordInput, TextInput
from django.utils.translation import ugettext_lazy as _
from accounts.models import MyUser
class SignUpForm(ModelForm):
"""
Регистрационная форма.
"""
password = CharField... | f):
pass1 = self.data['password']
pass2 = self.data['password_repeat']
if pass1 != pass2:
raise ValidationError(
_("Пароли не совпадают."))
return pass2
def clean_email(self):
if MyUser.objects.filter(email=self.cleaned_data['email']).exists():
... | ерный формат фамилии: первыя буква должна быть заглавной, допустимы только русские символы.'))
return self.cleaned_data['last_name']
def clean_password(self):
l = len(self.cleaned_data['password'])
if l <= 5 or l >= 30:
raise ValidationError(
_('Неверная длина па... | identifier_body |
forms.py | # -*- coding: utf-8 -*-
import re
from django.forms import ValidationError, ModelForm, Form, CharField, PasswordInput, TextInput
from django.utils.translation import ugettext_lazy as _
from accounts.models import MyUser
class SignUpForm(ModelForm):
"""
Регистрационная форма.
"""
password = CharField... | pass2
def clean_email(self):
if MyUser.objects.filter(email=self.cleaned_data['email']).exists():
raise ValidationError(_('Этот e-mail уже используется.'))
return self.cleaned_data['email']
| raise ValidationError(
_("Пароли не совпадают."))
return | conditional_block |
forms.py | # -*- coding: utf-8 -*-
import re
from django.forms import ValidationError, ModelForm, Form, CharField, PasswordInput, TextInput
from django.utils.translation import ugettext_lazy as _
from accounts.models import MyUser
class SignUpForm(ModelForm):
"""
Регистрационная форма.
"""
password = CharField... | .data['password']
pass2 = self.data['password_repeat']
if pass1 != pass2:
raise ValidationError(
_("Пароли не совпадают."))
return pass2
def clean_email(self):
if MyUser.objects.filter(email=self.cleaned_data['email']).exists():
raise Validati... | pass1 = self | identifier_name |
forms.py | # -*- coding: utf-8 -*-
import re
from django.forms import ValidationError, ModelForm, Form, CharField, PasswordInput, TextInput
from django.utils.translation import ugettext_lazy as _
from accounts.models import MyUser
class SignUpForm(ModelForm):
"""
Регистрационная форма. | model = MyUser
fields = ('email', 'organisation', 'last_name', 'first_name')
labels = {
'email': _('E-mail'),
'first_name': _('Имя'),
'last_name': _('Фамилия'),
'organisation': _('Организация')
}
widgets = {
'email': Tex... | """
password = CharField(label=_('Пароль'), widget=PasswordInput(attrs={'placeholder': _('Пароль')}))
password_repeat = CharField(label=_('Пароль ещё раз'), widget=PasswordInput(attrs={'placeholder': _('Пароль ещё раз')}))
class Meta: | random_line_split |
color.js | import 'ui/stringify/editors/color.less';
import _ from 'lodash';
import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format';
import colorTemplate from 'ui/stringify/editors/color.html';
export default function ColorFormatProvider(Private) |
_Color.editor = {
template: colorTemplate,
controller($scope) {
$scope.addColor = function () {
$scope.editor.formatParams.colors.push(_.cloneDeep(DEFAULT_COLOR));
};
$scope.removeColor = function (index) {
$scope.editor.formatParams.colors.splice(index, 1);
};
}
... | {
const FieldFormat = Private(IndexPatternsFieldFormatProvider);
const convertTemplate = _.template('<span style="<%- style %>"><%- val %></span>');
const DEFAULT_COLOR = {
range: `${Number.NEGATIVE_INFINITY}:${Number.POSITIVE_INFINITY}`,
text: '#000000',
background: '#ffffff'
};
_.class(_Color)... | identifier_body |
color.js | import 'ui/stringify/editors/color.less';
import _ from 'lodash';
import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format';
import colorTemplate from 'ui/stringify/editors/color.html';
export default function ColorFormatProvider(Private) {
const FieldFormat = Private(IndexPatternsF... | (params) {
_Color.Super.call(this, params);
}
_Color.id = 'color';
_Color.title = 'Color';
_Color.fieldType = [
'number'
];
_Color.editor = {
template: colorTemplate,
controller($scope) {
$scope.addColor = function () {
$scope.editor.formatParams.colors.push(_.cloneDeep(DEFAU... | _Color | identifier_name |
color.js | import 'ui/stringify/editors/color.less';
import _ from 'lodash';
import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format';
import colorTemplate from 'ui/stringify/editors/color.html';
export default function ColorFormatProvider(Private) {
const FieldFormat = Private(IndexPatternsF... |
if (!color) return _.asPrettyString(val);
let style = '';
if (color.text) style += `color: ${color.text};`;
if (color.background) style += `background-color: ${color.background};`;
return convertTemplate({ val, style });
}
};
return _Color;
}; | return val >= Number(start) && val <= Number(end);
}); | random_line_split |
loadingbar.js | import { Audio } from './legacy/audio.js';
import { Sprite } from './sprite.js';
import { utilTHREE } from "./threejs/utilthree.js";
/**
* Loading bar.
* @param {Array.<Object>=} objectsToPoll Objects that contain loadedFraction()
* function that returns 1 when the object is fully loaded.
* @constructor
*/
const ... | if (gl !== undefined) {
if (this.sinceLoaded > 0.0) {
// WebGL loading bar doesn't support fading out yet.
return;
}
var restoreClearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
var restoreScissor = gl.getParameter(gl.SCISSOR_BOX)... | if (typeof THREE !== 'undefined' && ctx instanceof THREE.WebGLRenderer) {
gl = ctx.context;
} | random_line_split |
loadingbar.js |
import { Audio } from './legacy/audio.js';
import { Sprite } from './sprite.js';
import { utilTHREE } from "./threejs/utilthree.js";
/**
* Loading bar.
* @param {Array.<Object>=} objectsToPoll Objects that contain loadedFraction()
* function that returns 1 when the object is fully loaded.
* @constructor
*/
const... |
this.objectsToPoll = objectsToPoll;
this.loadedFraction = 0;
this.allLoaded = false;
this.sinceLoaded = 0;
this.sinceStarted = 0;
};
/**
* @param {number} deltaTime Time passed from the last frame.
* @return {boolean} True when fully loaded.
*/
LoadingBar.prototype.update = function(deltaTime) ... | {
objectsToPoll = [Sprite, Audio, utilTHREE];
} | conditional_block |
index.tsx | import React, { FC, useMemo } from 'react'
import { shallowEqual } from 'react-redux'
import { Layout } from 'antd'
import { useTranslate } from '@/_helpers/i18n'
import { getProfileName } from '@/_helpers/profile-manager'
import { useSelector } from '@/content/redux'
import { HeadInfoMemo } from './HeadInfo'
import '... | openProfilesTab: (entry: 'Profiles') => void
}
export const Header: FC<HeaderProps> = props => {
const { t, ready } = useTranslate(['options', 'common'])
const { profileId, profileIDList } = useSelector(
state => ({
profileId: state.activeProfile.id,
profileIDList: state.profiles
}),
shal... | export interface HeaderProps { | random_line_split |
Channel.js | /**
* @module Audio
* @namespace Audio
*/
var TW = TW || {};
define(['./Sound', '../Utils/Polyfills'], function(Sound) {
TW.Audio = TW.Audio || {};
/**
* Channel class is an utility for manage multiple sounds with a same source.
*
* By default, a sound object can't be played twice simulaneously.
* The ... |
}.bind(this);
for (var i = 0; i < this._sounds.length; ++i) {
var sound = this._sounds[i];
if (i === 0) {
sound.onReady = handleAllSoundsReady;
}
sound.load(0, 0, 1);
}
};
/**
* Get a playable sound.
*
* @method getPlayableSound
* @return {Object} A playable sound.
*/
Channel.proto... | {
this.allSoundsReady(this);
} | conditional_block |
Channel.js | /**
* @module Audio
* @namespace Audio
*/
var TW = TW || {};
define(['./Sound', '../Utils/Polyfills'], function(Sound) {
TW.Audio = TW.Audio || {};
/**
* Channel class is an utility for manage multiple sounds with a same source.
*
* By default, a sound object can't be played twice simulaneously.
* The ... | (src, max, id) {
/**
* Array of Sound.
*
* @property {Sound[]} _sounds
* @default []
*/
this._sounds = [];
/**
* Callback function when all sound is ready to play in this channel.
*
* @property {Function} allSoundsReady
* @default null
*/
this.allSoundsReady = null;
/**
* S... | Channel | identifier_name |
Channel.js | /**
* @module Audio
* @namespace Audio
*/
var TW = TW || {};
define(['./Sound', '../Utils/Polyfills'], function(Sound) {
TW.Audio = TW.Audio || {};
/**
* Channel class is an utility for manage multiple sounds with a same source.
*
* By default, a sound object can't be played twice simulaneously.
* The ... | /**
* Channel id.
*
* @property {Number} id
* @default id
* @readonly
*/
this.id = id;
this.add(max);
}
/**
* Add max sound instance with sources in channel.
*
* @method add
* @param {Number} max The number of sound allocated in this channel.
*/
Channel.prototype.add = function(ma... | this._src = src;
| random_line_split |
Channel.js | /**
* @module Audio
* @namespace Audio
*/
var TW = TW || {};
define(['./Sound', '../Utils/Polyfills'], function(Sound) {
TW.Audio = TW.Audio || {};
/**
* Channel class is an utility for manage multiple sounds with a same source.
*
* By default, a sound object can't be played twice simulaneously.
* The ... | * Can contains many values (first compatible are used).
*
* @property {String|String[]} _src
* @private
*/
this._src = src;
/**
* Channel id.
*
* @property {Number} id
* @default id
* @readonly
*/
this.id = id;
this.add(max);
}
/**
* Add max sound instance with sources i... | {
/**
* Array of Sound.
*
* @property {Sound[]} _sounds
* @default []
*/
this._sounds = [];
/**
* Callback function when all sound is ready to play in this channel.
*
* @property {Function} allSoundsReady
* @default null
*/
this.allSoundsReady = null;
/**
* Source sound for... | identifier_body |
check_button.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create widgets with a discrete toggle button
use glib::translate::ToGlibPtr;
use ffi;
/... | nemonic: &str) -> Option<CheckButton> {
let tmp_pointer = unsafe {
ffi::gtk_check_button_new_with_mnemonic(mnemonic.to_glib_none().0)
};
check_pointer!(tmp_pointer, CheckButton)
}
}
impl_drop!(CheckButton);
impl_TraitWidget!(CheckButton);
impl ::ContainerTrait for CheckButton {... | w_with_mnemonic(m | identifier_name |
check_button.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create widgets with a discrete toggle button
use glib::translate::ToGlibPtr;
use ffi;
/... | pub fn new_with_mnemonic(mnemonic: &str) -> Option<CheckButton> {
let tmp_pointer = unsafe {
ffi::gtk_check_button_new_with_mnemonic(mnemonic.to_glib_none().0)
};
check_pointer!(tmp_pointer, CheckButton)
}
}
impl_drop!(CheckButton);
impl_TraitWidget!(CheckButton);
impl ::Co... | let tmp_pointer = unsafe {
ffi::gtk_check_button_new_with_label(label.to_glib_none().0)
};
check_pointer!(tmp_pointer, CheckButton)
}
| identifier_body |
check_button.rs | // Copyright 2013-2015, The Gtk-rs Project Developers. |
use glib::translate::ToGlibPtr;
use ffi;
/// CheckButton — Create widgets with a discrete toggle button
struct_Widget!(CheckButton);
impl CheckButton {
pub fn new() -> Option<CheckButton> {
let tmp_pointer = unsafe { ffi::gtk_check_button_new() };
check_pointer!(tmp_pointer, CheckButton)
}
... | // See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create widgets with a discrete toggle button | random_line_split |
TeamMatch.ts | import {Team} from "./Team";
import {ParticipantMatch} from "./ParticipantMatch";
export interface TeamMatch {
id?: string;
round: number;
teamOne: Team;
teamTwo: Team;
participantMatches?: ParticipantMatch[];
section: number;
scoreTeamOne: number;
scoreTeamTwo: number;
sgwTeamOne: number;
sg... | }
export function getTeamMatchForJSON(id: string, json: any): TeamMatch {
return {
id: id,
round: json.round,
teamOne: json.teamOne,
teamTwo: json.teamTwo,
participantMatches: json.participantMatches ? json.participantMatches : [],
section: json.section ? json.section : 0,
scoreTeamOn... | random_line_split | |
TeamMatch.ts | import {Team} from "./Team";
import {ParticipantMatch} from "./ParticipantMatch";
export interface TeamMatch {
id?: string;
round: number;
teamOne: Team;
teamTwo: Team;
participantMatches?: ParticipantMatch[];
section: number;
scoreTeamOne: number;
scoreTeamTwo: number;
sgwTeamOne: number;
sg... | (id: string, json: any): TeamMatch {
return {
id: id,
round: json.round,
teamOne: json.teamOne,
teamTwo: json.teamTwo,
participantMatches: json.participantMatches ? json.participantMatches : [],
section: json.section ? json.section : 0,
scoreTeamOne: json.scoreTeamOne ? json.scoreTeamO... | getTeamMatchForJSON | identifier_name |
TeamMatch.ts | import {Team} from "./Team";
import {ParticipantMatch} from "./ParticipantMatch";
export interface TeamMatch {
id?: string;
round: number;
teamOne: Team;
teamTwo: Team;
participantMatches?: ParticipantMatch[];
section: number;
scoreTeamOne: number;
scoreTeamTwo: number;
sgwTeamOne: number;
sg... | finishedParticipantGames: json.finishedParticipantGames ? json.finishedParticipantGames : 0,
matchDate: json.matchDate ? json.matchDate : new Date(),
};
}
export enum TeamMatchResult {
teamOneWin = 't1',
teamTwoWin = 't2',
draw = 'draw',
}
| {
return {
id: id,
round: json.round,
teamOne: json.teamOne,
teamTwo: json.teamTwo,
participantMatches: json.participantMatches ? json.participantMatches : [],
section: json.section ? json.section : 0,
scoreTeamOne: json.scoreTeamOne ? json.scoreTeamOne : 0,
scoreTeamTwo: json.scor... | identifier_body |
io.py | KT_READ_PTR, c_char_p], restype=GEOM_PTR, errcheck=check_geom
)
# WKTWriter routines
wkt_writer_create = GEOSFuncFactory('GEOSWKTWriter_create', restype=WKT_WRITE_PTR)
wkt_writer_destroy = GEOSFuncFactory('GEOSWKTWriter_destroy', argtypes=[WKT_WRITE_PTR])
wkt_writer_write = GEOSFuncFactory(
'GEOSWKTWriter_write', ... |
class WKBWriterSet(GEOSFuncFactory):
argtypes = [WKB_WRITE_PTR, c_int]
wkb_writer_get_byteorder = WKBWriterGet('GEOSWKBWriter_getByteOrder')
wkb_writer_set_byteorder = WKBWriterSet('GEOSWKBWriter_setByteOrder')
wkb_writer_get_outdim = WKBWriterGet('GEOSWKBWriter_getOutputDimension')
wkb_writer_set_outdim = WKBWr... | restype = c_int
| random_line_split |
io.py | _READ_PTR, c_char_p], restype=GEOM_PTR, errcheck=check_geom
)
# WKTWriter routines
wkt_writer_create = GEOSFuncFactory('GEOSWKTWriter_create', restype=WKT_WRITE_PTR)
wkt_writer_destroy = GEOSFuncFactory('GEOSWKTWriter_destroy', argtypes=[WKT_WRITE_PTR])
wkt_writer_write = GEOSFuncFactory(
'GEOSWKTWriter_write', ar... |
return geom
def write(self, geom):
"Returns the WKB representation of the given geometry."
from django.contrib.gis.geos import Polygon
geom = self._handle_empty_point(geom)
wkb = wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t()))
if isinstance(geom, Polygon) an... | raise ValueError('Empty point is not representable in WKB.') | conditional_block |
io.py | _READ_PTR, c_char_p], restype=GEOM_PTR, errcheck=check_geom
)
# WKTWriter routines
wkt_writer_create = GEOSFuncFactory('GEOSWKTWriter_create', restype=WKT_WRITE_PTR)
wkt_writer_destroy = GEOSFuncFactory('GEOSWKTWriter_destroy', argtypes=[WKT_WRITE_PTR])
wkt_writer_write = GEOSFuncFactory(
'GEOSWKTWriter_write', ar... | (self, geom):
"Returns the WKB representation of the given geometry."
from django.contrib.gis.geos import Polygon
geom = self._handle_empty_point(geom)
wkb = wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t()))
if isinstance(geom, Polygon) and geom.empty:
# Fix GEO... | write | identifier_name |
io.py | KT_READ_PTR, c_char_p], restype=GEOM_PTR, errcheck=check_geom
)
# WKTWriter routines
wkt_writer_create = GEOSFuncFactory('GEOSWKTWriter_create', restype=WKT_WRITE_PTR)
wkt_writer_destroy = GEOSFuncFactory('GEOSWKTWriter_destroy', argtypes=[WKT_WRITE_PTR])
wkt_writer_write = GEOSFuncFactory(
'GEOSWKTWriter_write', ... |
class _WKBReader(IOBase):
_constructor = wkb_reader_create
_destructor = wkb_reader_destroy
ptr_type = WKB_READ_PTR
def read(self, wkb):
"Returns a _pointer_ to C GEOS Geometry object from the given WKB."
if isinstance(wkb, six.memoryview):
wkb_s = bytes(wkb)
... | _constructor = wkt_reader_create
_destructor = wkt_reader_destroy
ptr_type = WKT_READ_PTR
def read(self, wkt):
if not isinstance(wkt, (bytes, six.string_types)):
raise TypeError
return wkt_reader_read(self.ptr, force_bytes(wkt)) | identifier_body |
kepmsg.py | #!/usr/bin/env python
import sys, time, string
# -----------------------------------------------------------
# write message to log file and shell
def log(file,message,verbose):
if (verbose):
# print to shell
| output = open(file,'a')
output.write(message+'\n')
output.close()
# -----------------------------------------------------------
# write error message to log file and shell
def err(file,message,verbose):
if verbose:
log(file,message,verbose)
else:
pass
return 1
# ----------... | print (message)
# print to log file
if (file): | random_line_split |
kepmsg.py | #!/usr/bin/env python
import sys, time, string
# -----------------------------------------------------------
# write message to log file and shell
def log(file,message,verbose):
if (verbose):
# print to shell
print (message)
# print to log file
if (file):
output = open(file,'a')
output.write(mes... |
# -----------------------------------------------------------
# write message to log file
def file(file,message,verbose):
if (file and verbose):
output = open(file,'a')
output.write(message+'\n')
output.close()
# -----------------------------------------------------------
# test the log... | message = text + ': ' + time.asctime(time.localtime())
log(file,message,verbose) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.